Given the plugins that are available in the Nativescript community, your Nativescript app may or may not be sufficient to pass security penetration testing.
Below are two plugins to list a few.
https://www.npmjs.com/package/#nstudio/root-detection
https://www.npmjs.com/package/nativescript-jailbreak-detector
In some scenarios, you could achieve better results by manually writing your own checks against a jailbreak and dynamic instrumentation (e.g. Frida), since there are so many tools to bypass jailbreak detection (e.g. HideJB) nowadays.
What are some ways we can detect jailbreak and protect against dynamic instrumentation on iOS Nativescript?
Detection can be carried out on multi-levels:
Check if URLs are openable via illegal URL schemes
Check if files are openable on illegal directories
Check if illegal files exist (incl. Cydia, Sileo, HideJB, etc.)
Check if files are writable on restricted directories
Code
public amIJailbroken(): boolean {
let urlSchemes: Array<string> = ['undecimus://', 'cydia://', 'sileo://', 'zbra://', 'filza://', 'activator://'];
// List of suspicious files associated with jailbreak
let paths: Array<string> = [
'/.bootstrapped_electra',
'/.cydia_no_stash',
'/.installed_unc0ver',
'/Applications/blackra1n.app',
'/Applications/Cydia.app',
'/Applications/FakeCarrier.app',
'/Applications/HideJB.app',
'/Applications/Icy.app',
'/Applications/IntelliScreen.app',
'/Applications/MxTube.app',
'/Applications/RockApp.app',
'/Applications/SBSettings.app',
'/Applications/SBSetttings.app',
'/Applications/Sileo.app',
'/Applications/Snoop-itConfig.app',
'/Applications/WinterBoard.app',
'/bin.sh',
'/bin/bash',
'/bin/sh',
'/etc/apt',
'/etc/apt/sources.list.d/electra.list',
'/etc/apt/sources.list.d/sileo.sources',
'/etc/apt/undecimus/undecimus.list',
'/etc/ssh/sshd_config',
'/jb/amfid_payload.dylib',
'/jb/jailbreakd.plist',
'/jb/libjailbreak.dylib',
'/jb/lzma',
'/jb/offsets.plist',
'/Library/dpkg/info/re.frida.server.list',
'/Library/LaunchDaemons/re.frida.server.plist',
'/Library/MobileSubstrate/CydiaSubstrate.dylib',
'/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist',
'/Library/MobileSubstrate/DynamicLibraries/Veency.plist',
'/Library/MobileSubstrate/HideJB.dylib',
'/Library/MobileSubstrate/MobileSubstrate.dylib',
'/Library/PreferenceBundles/ABypassPrefs.bundle',
'/Library/PreferenceBundles/FlyJBPrefs.bundle',
'/Library/PreferenceBundles/HideJBPrefs.bundle',
'/Library/PreferenceBundles/LibertyPref.bundle',
'/Library/PreferenceBundles/ShadowPreferences.bundle',
'/private/etc/apt',
'/private/etc/dpkg/origins/debian',
'/private/etc/ssh/sshd_config',
'/private/var/cache/apt/',
'/private/var/lib/apt',
'/private/var/lib/apt/',
'/private/var/lib/cydia',
'/private/var/log/syslog',
'/private/var/mobile/Library/SBSettings/Themes',
'/private/var/mobileLibrary/SBSettingsThemes/',
'/private/var/stash',
'/private/var/tmp/cydia.log',
'/private/var/Users/',
'/System/Library/LaunchDaemons/com.ikey.bbot.plist',
'/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist',
'/usr/bin/cycript',
'/usr/bin/ssh',
'/usr/bin/sshd',
'/usr/lib/libcycript.dylib',
'/usr/lib/libhooker.dylib',
'/usr/lib/libjailbreak.dylib',
'/usr/lib/libsubstitute.dylib',
'/usr/lib/substrate',
'/usr/lib/TweakInject',
'/usr/libexec/cydia/',
'/usr/libexec/cydia/firmware.sh',
'/usr/libexec/sftp-server',
'/usr/libexec/ssh-keysign',
'/usr/local/bin/cycript',
'/usr/sbin/frida-server',
'/usr/sbin/sshd',
'/usr/share/jailbreak/injectme.plist',
'/var/binpack',
'/var/cache/apt',
'/var/checkra1n.dmg',
'/var/lib/apt',
'/var/lib/cydia',
'/var/lib/dpkg/info/mobilesubstrate.md5sums',
'/var/log/apt',
'/var/log/syslog',
'/var/tmp/cydia.log',
];
// Check if target is not an iOS simulator
if (!isIOS || !this.isTarget()) return false;
else {
// Check URL schemes
for (const url of urlSchemes) {
if (this.canOpenIllegalURL(url)) return true;
}
// Check files and directories associated with jailbreaks
for (const path of paths) {
if (this.canOpenIllegalFile(path)) return true;
}
// Check file permissions outside device sandbox, if writtable = jailbroken
if (this.canWriteToRestrictedDirectories()) return true;
return false;
}
}
/*
********** Helper Methods **********
*/
/* Check if environment is being run as a RELEASE build */
private isTarget() {
return process.env.RELEASE_ENV;
}
/* Check if we can open illegal URL schemes */
private canOpenIllegalURL(url): boolean {
return UIApplication.sharedApplication.canOpenURL(NSURL.URLWithString(url + 'package/com.example.app'));
}
/* Check if file is openable */
private canOpenIllegalFile(path): boolean {
const file = fopen(path, 'r');
if (!file) {
fclose(file);
return this.fileExists(path) || this.directoryExists(path);
}
fclose(file);
return true;
}
/* Check if file exists at path */
private fileExists(path): boolean {
return NSFileManager.defaultManager.fileExistsAtPath(path);
}
/* Check if directory exists at path */
private directoryExists(path): boolean {
return NSFileManager.defaultManager.fileExistsAtPathIsDirectory(path, new interop.Reference());
}
/* Check if file is writtable to illegal directory */
private canWriteToRestrictedDirectories(): boolean {
let error;
try {
const stringToBeWritten = NSString.stringWithString('I am evil.');
stringToBeWritten.writeToFileAtomicallyEncodingError('/private/jailbreak.txt', true, NSUTF8StringEncoding);
stringToBeWritten.writeToFileAtomicallyEncodingError('/root/jailbreak.txt', true, NSUTF8StringEncoding);
NSFileManager.defaultManager.removeItemAtPathError('/private/jailbreak.txt');
NSFileManager.defaultManager.removeItemAtPathError('/root/jailbreak.txt');
} catch (e) {
error = e;
}
return !error ? true : false;
}
References
The research comes from a consolidation of the following ideas:
https://stackoverflow.com/a/26712383/2192332
https://mobile-security.gitbook.io/mobile-security-testing-guide/ios-testing-guide/0x06j-testing-resiliency-against-reverse-engineering
https://github.com/securing/IOSSecuritySuite/blob/master/IOSSecuritySuite/JailbreakChecker.swift
https://github.com/avltree9798/isJailbroken/blob/master/isJailbroken/JB.m
Improvements
Please feel free to suggest!
E.g. Checking for illegal dynamic libraries in memory using _dyld_get_image_name
Related
I am targeting Android API 30. My app was storing log file and taking database backup in location "/storage/emulated/0/SpecialDir/". Now I am facing access denied issue while my app was workinng fine previously.
I got an overview about scoped storage and came to know that we have some managed locaitons where we can store our data accordingly. i.e Audio, Video, Images, and Download
My question is What is the solution for existing apps that was previously saving files on "/storage/emulated/0/SpecialDir/".
Can anyone please guide me what should i do.
string dir = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "LogFolder");
if (Directory.Exists(dir))
{
return Path.Combine(dir, "MyLogFile.txt");
}
try
{
string newDirectory = Directory.CreateDirectory(dir).FullName;
path = Path.Combine(newDirectory, "MyLogFile.txt");
System.IO.File.WriteAllText(path, "This is some testing log.");
}
catch (Exception ex)
{
string msg = ex.Message;
}
The above code is used to make 'LogFolder' if not exist and 'MyLogFile' as well. What changes do i needed to make it compatiable to Android 10. Thankyou
In Android 10, Google has introduced a new feature for external Storage. Its name is Scoped Storage. Google officially translates it as partitioned Storage, or Scoped Storage.The intent is to limit what programs can do with public directories in external storage. Partitioned storage has no effect on either the internal storage private directory or the external storage private directory.In short, in Android 10, there is no change to private directory reads and writes, and you can still use the File set without any permissions. For reading and writing to public directories, you must use the API provided by MediaStore or the SAF (storage access framework), which means you can no longer use the File set to manipulate public directories at will.
If you set targetSdkVersion above 29,you could try to add below codes into your AndroidManifest.Then you could access the File as before.
<manifest ... >
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Update (you could try this for public external storage ):
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
Update for Android 11:
add MANAGE_EXTERNAL_STORAGE permission in your AndroidManifest.
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
in your activity:
if (Environment.IsExternalStorageManager)
{
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
else
{
StartActivityForResult(new Intent(Settings.ActionManageAllFilesAccessPermission), 0);
}
I'm trying to write a java program that reacts if a new entry occures in the file C:/xampp/apache/logs/access.log in order to recognize a new request to my Apache Server.
I used the following code:
public static void monitor() throws IOException {
WatchService watcher = FileSystems.getDefault().newWatchService();
File file = new File("C:/xampp/apache/logs/");
Path dir = file.toPath();
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// get file name
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == OVERFLOW) {
continue;
} else if (kind == ENTRY_CREATE) {
System.out.println("entry created occured");
// process create event
} else if (kind == ENTRY_DELETE) {
// process delete event
} else if (kind == ENTRY_MODIFY && fileName.toString().equals("access.log")) {
System.out.println("entry modified occured");
// process modify event
}
}
// Reset the key -- this step is critical if you want to
// receive further watch events. If the key is no longer valid,
// the directory is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
But it does not recognize the change in access.log until I manually open the file. Is there something wrong with my code?
There are differents options.
There are two questions that can be kind of similiar, the only difference is that they want to check a whole direcotry instead of just a file, but you could adapt the code to detect if the modified file is the one that you want.
Watching a Directory for Changes in Java
Java detect changes in filesystem
For a specific solution I've found
http://www.rgagnon.com/javadetails/java-0490.html
This code launches a thread that checks the lastModified value of the file, if it's different from the previous one, it means that the file has been modified. I don't know if it's very efficient, check them out.
Is it possible to detect at runtime that an application has been installed through TestFlight Beta (submitted through iTunes Connect) vs the App Store? You can submit a single app bundle and have it available through both. Is there an API that can detect which way it was installed? Or does the receipt contain information that allows this to be determined?
For an application installed through TestFlight Beta the receipt file is named StoreKit/sandboxReceipt vs the usual StoreKit/receipt. Using [NSBundle appStoreReceiptURL] you can look for sandboxReceipt at the end of the URL.
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSString *receiptURLString = [receiptURL path];
BOOL isRunningTestFlightBeta = ([receiptURLString rangeOfString:#"sandboxReceipt"].location != NSNotFound);
Note that sandboxReceipt is also the name of the receipt file when running builds locally and for builds run in the simulator.
Swift Version:
let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
Based on combinatorial's answer I created the following SWIFT helper class. With this class you can determine if it's a debug, testflight or appstore build.
enum AppConfiguration {
case Debug
case TestFlight
case AppStore
}
struct Config {
// This is private because the use of 'appConfiguration' is preferred.
private static let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
// This can be used to add debug statements.
static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
static var appConfiguration: AppConfiguration {
if isDebug {
return .Debug
} else if isTestFlight {
return .TestFlight
} else {
return .AppStore
}
}
}
We use these methods in our project to supply different tracking id's or connection string per environment:
func getURL(path: String) -> String {
switch (Config.appConfiguration) {
case .Debug:
return host + "://" + debugBaseUrl + path
default:
return host + "://" + baseUrl + path
}
}
OR:
static var trackingKey: String {
switch (Config.appConfiguration) {
case .Debug:
return debugKey
case .TestFlight:
return testflightKey
default:
return appstoreKey
}
}
UPDATE 05-02-2016:
A prerequisite to use a preprocessor macro like #if DEBUG is to set some Swift Compiler Custom Flags. More information in this answer: https://stackoverflow.com/a/24112024/639227
Modern Swift version, which accounts for Simulators (based on accepted answer):
private func isSimulatorOrTestFlight() -> Bool {
guard let path = Bundle.main.appStoreReceiptURL?.path else {
return false
}
return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
}
I use extension Bundle+isProduction on Swift 5.2:
import Foundation
extension Bundle {
var isProduction: Bool {
#if DEBUG
return false
#else
guard let path = self.appStoreReceiptURL?.path else {
return true
}
return !path.contains("sandboxReceipt")
#endif
}
}
Then:
if Bundle.main.isProduction {
// do something
}
There is one way that I use it for my projects. Here are the steps.
In Xcode, go to the the project settings (project, not target) and add "beta" configuration to the list:
Then you need to create new scheme that will run project in "beta" configuration. To create scheme go here:
Name this scheme whatever you want. The you should edit settings for this scheme. To do this, tap here:
Select Archive tab where you can select Build configuration
Then you need to add a key Config with value $(CONFIGURATION) the projects info property list like this:
Then its just the matter what you need in code to do something specific to beta build:
let config = Bundle.main.object(forInfoDictionaryKey: "Config") as! String
if config == "Debug" {
// app running in debug configuration
}
else if config == "Release" {
// app running in release configuration
}
else if config == "Beta" {
// app running in beta configuration
}
I want to store a small bit of information in a file, persisted between runs of a command-line app. Probably the best location is a small file in the user's home directory.
I'd like to write a property/config file into a user's home directory. How can I tell, for Windows, Mac, and Linux, what the user's home directory is? I am using Dart.
Identify the OS then use the designated environment variable for that particular OS. You can read the OS/environment variables from platform. For e.g. :
OS : String os = Platform.operatingSystem; Various checks like isLinux, isAndroid are given
Map<String, String> envVars = Platform.environment;
An example:
import 'dart:io' show Platform, stdout;
void main() {
String os = Platform.operatingSystem;
String home = "";
Map<String, String> envVars = Platform.environment;
if (Platform.isMacOS) {
home = envVars['HOME'];
} else if (Platform.isLinux) {
home = envVars['HOME'];
} else if (Platform.isWindows) {
home = envVars['UserProfile'];
}
stdout.writeln(home);
}
Home dirs taken from here : http://en.wikipedia.org/wiki/Home_directory
This will do:
String get userHome =>
Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
I don't have access to a windows machine, but I found this logic in pub:
if (Platform.environment.containsKey('PUB_CACHE')) {
cacheDir = Platform.environment['PUB_CACHE'];
} else if (Platform.operatingSystem == 'windows') {
var appData = Platform.environment['APPDATA'];
cacheDir = path.join(appData, 'Pub', 'Cache');
} else {
cacheDir = '${Platform.environment['HOME']}/.pub-cache';
}
Looks like for Linux and Mac, we can do:
Platform.environment['HOME']
For Windows, it's better to find a location inside of Platform.environment['APPDATA']
Similar to other answers:
// Get the home directory or null if unknown.
String homeDirectory() {
switch (Platform.operatingSystem) {
case 'linux':
case 'macos':
return Platform.environment['HOME'];
case 'windows':
return Platform.environment['USERPROFILE'];
case 'android':
// Probably want internal storage.
return '/storage/sdcard0';
case 'ios':
// iOS doesn't really have a home directory.
return null;
case 'fuchsia':
// I have no idea.
return null;
default:
return null;
}
}
You can tweak how it behaves according to your needs. I did try and figure out the answer for Fuchsia but I can't work out if it even has home directories to be honest!
I am trying to save some files on micro SDCard. To check the availability of SDCard, I am using the following method;
private boolean isSdCardReady() {
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
if (e.nextElement().toString().equalsIgnoreCase("sdcard/")) {
return true;
}
}
return false;
}
Even if this method returns true, when I try to save files, it gives exception net.rim.device.api.io.file.FileIOException: File system is not ready.
What does this means? If SDCard is not available, then why its listed in FileSystemRegistry.listRoots()?
How can I make sure that SDCard is available for writing?
My development environment:
BlackBerry JDE Eclipse Plugin 1.5.0
BlackBerry OS 4.5
BlackBerry Bold with a 3G card
Usually I had this error when I tried to access SD card on device restart. You have to postpone all operations in app until startup finished:
while (ApplicationManager.getApplicationManager().inStartup()) {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
I remember one more possible cause mentioned here. You have to close all streams after using.
Solved the problem. I was looking for "sdcard" while rootsEnum.nextElement().toString(); returns "SDCard". Yeah, its case sensitive. Now, instead of using hard-coded "SDCard", I've changed the above method to the following;
private static String getSdCardRootDir() {
Enumeration rootsEnum = FileSystemRegistry.listRoots();
while (rootsEnum.hasMoreElements()) {
String rootDir = rootsEnum.nextElement().toString();
if (rootDir.equalsIgnoreCase("sdcard/")) {
return "file:///" + rootDir;
}
}
return null;
}
Using this, I got the root directory in its system defined case.