Detect jailbroken bypass in Xamarin forms - xamarin.forms

My Xamarin based iOS application should not run in jailbroken devices. This is due to a IS audit. I have implemented the jailbroken detect mechanism. But I cannot find a way to detect whether someone using a jailbroken bypass method like for example A-bypass, shadow tweaks. Anyone with these tweaks can easily by pass the jailbroken detect code.
This is the class I used,
[assembly: Dependency(typeof(CheckHardware))]
namespace CustApp.iOS
{
public class CheckHardware : IHardwareSecurity
{
public CheckHardware()
{
}
public bool IsJailBreaked()
{
if (isPath() || canCreateFile() || isOpenLink())
{
return true;
}
else
{
return false;
}
}
private bool isPath()
{
bool res = false;
List<string> pathList = new List<string>
{
"/Applications/Cydia.app",
"/Applications/Checkra1n.app",
"/Applications/FakeCarrier.app",
"/Applications/Icy.app",
"/Applications/IntelliScreen.app",
"/Applications/MxTube.app",
"/Applications/RockApp.app",
"/Applications/SBSettings.app",
"/Applications/WinterBoard.app",
"/Applications/blackra1n.app",
"/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist",
"/Library/MobileSubstrate/DynamicLibraries/Veency.plist",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/System/Library/LaunchDaemons/com.ikey.bbot.plist",
"/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist",
"/etc/apt",
"/private/var/lib/apt",
"/private/var/lib/apt/",
"/private/var/lib/cydia",
"/private/var/mobile/Library/SBSettings/Themes",
"/private/var/stash",
"/private/var/tmp/cydia.log",
"/usr/bin/sshd",
"/var/cache/apt",
"/var/lib/apt",
"/usr/libexec/sftp-server",
"/usr/sbin/sshd",
"/bin/bash",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/var/lib/cydia"
};
foreach (var fullPath in pathList)
{
if (File.Exists(fullPath))
{
res = true;
}
}
return res;
}
private bool canCreateFile()
{
try
{
File.WriteAllText("/private/jailbreak.txt", "This is a test.");
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
private bool isOpenLink()
{
if (UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString("cydia://package/com.example.package")))
{
return true;
}
else
{
return false;
}
}
public bool IsInEmulator()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
return isSimulator;
}
}
}

Related

Unity - The name 'auth' does not exist in the current context

I am currently trying to create user authentication in unity and I am having some issues.
The code below is what I have at the moment and I keep receiving the error saying Auth does not exist in the current context.
Does anyone have any idea why this is? Probably a simple fix that I am just overlooking.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Text.RegularExpressions;
using Firebase;
using Firebase.Auth;
public class Register : MonoBehaviour {
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-"};
public void RegisterButton(){
bool EM = false;
bool PW = false;
bool CPW = false;
if (Email != ""){
EmailValidation();
if (EmailValid){
if(Email.Contains("#")){
if(Email.Contains(".")){
EM = true;
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email Field Empty");
}
if (Password != ""){
if(Password.Length > 5){
PW = true;
} else {
Debug.LogWarning("Password Must Be atleast 6 Characters long");
}
} else {
Debug.LogWarning("Password Field Empty");
}
if (ConfPassword != ""){
if (ConfPassword == Password){
CPW = true;
} else {
Debug.LogWarning("Passwords Don't Match");
}
} else {
Debug.LogWarning("Confirm Password Field Empty");
}
if (EM == true&&PW == true&&CPW == true)
{
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Tab)){
if (email.GetComponent<InputField>().isFocused){
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused){
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return)){
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != ""){
RegisterButton();
}
}
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation(){
bool SW = false;
bool EW = false;
for(int i = 0;i<Characters.Length;i++){
if (Email.StartsWith(Characters[i])){
SW = true;
}
}
for(int i = 0;i<Characters.Length;i++){
if (Email.EndsWith(Characters[i])){
EW = true;
}
}
if(SW == true&&EW == true){
EmailValid = true;
} else {
EmailValid = false;
}
}
}
I do not see you ever creating the variable auth?
While you refer to it here:
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
So I assume you will have to create a variable auth and instantiate it with something related to FireBase.Auth (unless I am overlooking something).

How to save current location?

I have a question. I am working on mobile app where my user can store experience from trip by loggin current location.
I am connected to SQLite fo now and I am just exploring the Geolocator nuget from James Monemagno. SO far I can get the pin on map with current location, but I am unsure how to store the location in databse. I guess it wont be"position" and it must be Latitude and Longitude but then how will i get again the picture with the pin displayed under my post? Do you guys have some experience?
Public clas NoteViewMode : BaseViewModel
{
/////
private string _location;
public string Location
{
get { return _location; }
set
{
_location = value;
OnPropertyChanged();
}
}
public double _latitude;
public double Latitude
{
get { return _latitude; }
set
{
_latitude = value;
OnPropertyChanged();
}
}
private double _longitude;
public double Longitude
{
get { return _longitude; }
set
{
_longitude = value;
OnPropertyChanged();
}
}
}
public Map()
{
InitializeComponent();
GetPremissions();
BindingContext = ViewModel = new AdLogEntryViewModel();
}
private async void GetPremissions()
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
{
await DisplayAlert("We need location", "", "Ok");
}
var result = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (result.ContainsKey(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
status = result[Plugin.Permissions.Abstractions.Permission.LocationWhenInUse];
}
if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
locationsMap.IsShowingUser = true;
hasLocationPermission = true;
GetLocation();
}
else
{
await DisplayAlert("Location denied", "", "");
}
}
catch (Exception ex)
{
await DisplayAlert("erroe", ex.Message, "ok");
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
locator.PositionChanged += Locator_PositionChanged;
await locator.StartListeningAsync(TimeSpan.Zero, 100);
}
GetLocation();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= Locator_PositionChanged;
}
void Locator_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
MoveMap(e.Position);
}
private async void GetLocation()
{
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
MoveMap(position);
}
}
private async void MoveMap(Position position)
{
var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var span = new Xamarin.Forms.Maps.MapSpan(center, 1, 1);
locationsMap.MoveToRegion(span);
}
you can programmatically add a Pin to a Map
Pin pin = new Pin
{
Label = "Santa Cruz",
Address = "The city with a boardwalk",
Type = PinType.Place,
Position = new Position(36.9628066, -122.0194722)
};
map.Pins.Add(pin);

Intercept global event Xamarin Forms

In MainActivity.cs I have this method
public override bool OnKeyUp(Keycode keyCode, KeyEvent e)
{
if (keyCode.ToString().Equals("F1"))
{
App.Left = true;
App.Right = false;
}
else if (keyCode.ToString().Equals("F2"))
{
App.Left = false;
App.Right = true;
}
else
{
App.Left = false;
App.Right = false;
}
return base.OnKeyUp(keyCode, e);
}
In my Page class, how can I constantly check whether left or right are true and in case trigger an event?
Create a plugin using Dependency Service and your shared interface should look like this:
public interface IKeyEvent
{
event Action<KeyResult> OnKeyEvent;
}
public enum KeyResult {None, Left, Right};
Implement this for different platforms (Android/iOS/UWP) accordingly and bind it to PCL project. (Check dependency service implementation for help)
Link it to platform-specific KeyUp event.
for android it would be like this:
Droid.KeyEventHandler
[assembly: Dependency(typeof(KeyEventHandler))]
namespace YourNameSpace.Droid
{
public class KeyEventHandler : IKeyEvent
{
public static KeyEventHandler Current;
public KeyEventHandler()
{
Current = this;
}
public event Action<KeyResult> OnKeyResult;
public void RaiseKeyEvent(KeyResult key)
{
OnKeyResult?.Invoke(key);
}
}
}
MainActivity
public override bool OnKeyUp(Keycode keyCode, KeyEvent e)
{
KeyResult keyResult = KeyResult.None; // need to reference YourNameSpace.Shared project to use this enum
if (keyCode == KeyCode.A)
{
keyResult = KeyResult.Left;
}
else if (keyCode == KeyCode.D))
{
keyResult = KeyResult.Right;
}
else
{
keyResult = KeyResult.None;
}
if (KeyEventHandler.Current != null)
{
KeyEventHandler.Current.RaiseKeyEvent(keyResult);
}
return base.OnKeyUp(keyCode, e);
}
NOTE: Left and right keys are mapped to A and D of physical keyboard respectively, for some reason my Macbook's F1/F2 keys were not registering to simulator so I used A/D.
Hope this helps :)

QR detection using ZXing with Vuforia in Unity

We have implemented the QR detection functionality using ZXing.dll in Unity 5.3.4f1 with Vuforia Unity SDK 5.5.9. We have a QR detection script on GameObject which remains active throughout the app and using below mentioned (QRScanner.cs) code ( as mentioned on Unity Zxing QR code scanner integration ).
We are also using Vuforia for image detection (50 image targets) in the same scene where QR detection is expected. The Vuforia plugin is getting enabled / disabled multiple times as per our requirement. Both the image and QR detection is working perfectly for us on Android and iOS devices until the app is in focus. Whenever VuforiaBehaviour gets disabled and enabled, QR detection stops working after that. QRScanner script always receives null data after the app is resumed or AR camera is reloaded. We have tried keeping our QR detection script on AR camera prefab and also tried
qcarBehaviour.RegisterTrackablesUpdatedCallback(OnTrackablesUpdated);
qcarBehaviour.RegisterQCARStartedCallback(OnTrackablesUpdated);
callbacks every time AR camera starts but with no success. The QR detection stops working completely after pausing Vuforia plugin for any reason.
Does anybody have any idea how to fix this issue?
QRScanner.cs
using UnityEngine;
using System;
using System.Collections;
using Vuforia;
using System.Threading;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
/* ///////////////// QR detection does not work in editor //////////////// */
[AddComponentMenu("System/QRScanner")]
public class QRScanner : MonoBehaviour
{
private bool cameraInitialized;
private BarcodeReader barCodeReader;
public AppManager camScript;
void Start()
{
barCodeReader = new BarcodeReader();
StartCoroutine(InitializeCamera());
}
private IEnumerator InitializeCamera()
{
// Waiting a little seem to avoid the Vuforia's crashes.
yield return new WaitForSeconds(3f);
var isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Image.PIXEL_FORMAT.RGB888, true);
Debug.Log(String.Format("FormatSet : {0}", isFrameFormatSet));
// Force autofocus.
// var isAutoFocus = CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
// if (!isAutoFocus)
// {
// CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
// }
// Debug.Log(String.Format("AutoFocus : {0}", isAutoFocus));
cameraInitialized = true;
}
private void Update()
{
if (cameraInitialized)
{
try
{
var cameraFeed = CameraDevice.Instance.GetCameraImage(Image.PIXEL_FORMAT.RGB888);
if (cameraFeed == null)
{
return;
}
var data = barCodeReader.Decode(cameraFeed.Pixels, cameraFeed.BufferWidth, cameraFeed.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);
if (data != null)
{
// QRCode detected.
Debug.Log(data.Text);
Application.OpenURL (data.Text); // our function to call and pass url as text
data = null; // clear data
}
else
{
Debug.Log("No QR code detected !");
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
}
}
i have this problem to
but i fix that with place code on ARcam
using UnityEngine;
using System.Collections;
using Vuforia;
public class CameraSettings : MonoBehaviour
{
#region PRIVATE_MEMBERS
private bool mVuforiaStarted = false;
private bool mAutofocusEnabled = true;
private bool mFlashTorchEnabled = false;
private CameraDevice.CameraDirection mActiveDirection = CameraDevice.CameraDirection.CAMERA_DEFAULT;
#endregion //PRIVATE_MEMBERS
#region MONOBEHAVIOUR_METHODS
void Start () {
Debug.Log("CameraSettings Start");
VuforiaAbstractBehaviour vuforia = FindObjectOfType<VuforiaAbstractBehaviour>();
VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
VuforiaARController.Instance.RegisterOnPauseCallback(OnPaused);
VuforiaARController.Instance.RegisterTrackablesUpdatedCallback (OnTrack);
//VuforiaARController.Instance.RegisterVideoBgEventHandler(BgEventHandler);
}
#endregion // MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
public bool IsFlashTorchEnabled()
{
return mFlashTorchEnabled;
}
public void SwitchFlashTorch(bool ON)
{
if (CameraDevice.Instance.SetFlashTorchMode(ON))
{
Debug.Log("Successfully turned flash " + ON);
mFlashTorchEnabled = ON;
}
else
{
Debug.Log("Failed to set the flash torch " + ON);
mFlashTorchEnabled = false;
}
}
public bool IsAutofocusEnabled()
{
return mAutofocusEnabled;
}
public void SwitchAutofocus(bool ON)
{
if (ON)
{
if (CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO))
{
Debug.Log("Successfully enabled continuous autofocus.");
mAutofocusEnabled = true;
}
else
{
// Fallback to normal focus mode
Debug.Log("Failed to enable continuous autofocus, switching to normal focus mode");
mAutofocusEnabled = false;
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
}
else
{
Debug.Log("Disabling continuous autofocus (enabling normal focus mode).");
mAutofocusEnabled = false;
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
}
public void TriggerAutofocusEvent()
{
// Trigger an autofocus event
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_TRIGGERAUTO);
// Then restore original focus mode
StartCoroutine(RestoreOriginalFocusMode());
}
public void SelectCamera(CameraDevice.CameraDirection camDir)
{
if (RestartCamera (camDir))
{
mActiveDirection = camDir;
// Upon camera restart, flash is turned off
mFlashTorchEnabled = false;
}
}
public bool IsFrontCameraActive()
{
return (mActiveDirection == CameraDevice.CameraDirection.CAMERA_FRONT);
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
private void OnTrack() {
//Debug.Log("CameraSettings OnTrack");
}
private void BgEventHandler() {
//Debug.Log("CameraSettings BgEventHandler");
}
private void OnVuforiaStarted() {
//Debug.Log("CameraSettings OnVuforiaStarted");
mVuforiaStarted = true;
// Try enabling continuous autofocus
SwitchAutofocus(true);
//RestartCamera (CameraDevice.CameraDirection.CAMERA_DEFAULT);
}
private void OnPaused(bool paused) {
bool appResumed = !paused;
//Debug.Log("CameraSettings OnPaused");
if (appResumed && mVuforiaStarted)
{
// Restore original focus mode when app is resumed
if (mAutofocusEnabled)
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
else
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
// Set the torch flag to false on resume (cause the flash torch is switched off by the OS automatically)
mFlashTorchEnabled = false;
}
}
private IEnumerator RestoreOriginalFocusMode()
{
// Wait 1.5 seconds
yield return new WaitForSeconds(1.5f);
// Restore original focus mode
if (mAutofocusEnabled)
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
else
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
private bool RestartCamera(CameraDevice.CameraDirection direction)
{
ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker>();
if (tracker != null)
tracker.Stop();
CameraDevice.Instance.Stop();
CameraDevice.Instance.Deinit();
if (!CameraDevice.Instance.Init(direction))
{
Debug.Log("Failed to init camera for direction: " + direction.ToString());
return false;
}
if (!CameraDevice.Instance.Start())
{
Debug.Log("Failed to start camera for direction: " + direction.ToString());
return false;
}
if (tracker != null)
{
if (!tracker.Start())
{
Debug.Log("Failed to restart the Tracker.");
return false;
}
}
return true;
}
#endregion // PRIVATE_METHODS
}

I'm trying to dispose of an object when the system is low on memory - is there a better way than this?

What I am doing currently is adding an item to the Cache and disposing of my object when that object is removed from the Cache. The logic being that it gets removed when memory consumption gets too high. I'm open to outher suggestions but I would like to avoid creating a thread than continually measures memory statistics if possible. Here is my code:
public class WebServiceCache : ConcurrentDictionary<string, WebServiceCacheObject>, IDisposable
{
private WebServiceCache()
{
if (HttpContext.Current != null && HttpContext.Current.Cache != null)
{
HttpContext.Current.Cache.Add("CacheTest", true, null, DateTime.Now.AddYears(1), System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Low,
(key, obj, reason) => {
if (reason != System.Web.Caching.CacheItemRemovedReason.Removed)
{
WebServiceCache.Current.ClearCache(50);
}
});
}
}
private static WebServiceCache _current;
public static WebServiceCache Current
{
get
{
if (_current != null && _current.IsDisposed)
{
// Might as well clear it fully
_current = null;
}
if (_current == null)
{
_current = new WebServiceCache();
}
return _current;
}
}
public void ClearCache(short percentage)
{
try
{
if (percentage == 100)
{
this.Dispose();
return;
}
var oldest = _current.Min(c => c.Value.LastAccessed);
var newest = _current.Max(c => c.Value.LastAccessed);
var difference = (newest - oldest).TotalSeconds;
var deleteBefore = oldest.AddSeconds((difference / 100) * percentage);
// LINQ doesn't seem to work very well on concurrent dictionaries
//var toDelete = _current.Where(c => DateTime.Compare(c.Value.LastAccessed,deleteBefore) < 0);
var keys = _current.Keys.ToArray();
foreach (var key in keys)
{
if (DateTime.Compare(_current[key].LastAccessed, deleteBefore) < 0)
{
WebServiceCacheObject tmp;
_current.TryRemove(key, out tmp);
tmp = null;
}
}
keys = null;
}
catch
{
// If we throw an exception here then we are probably really low on memory
_current = null;
GC.Collect();
}
}
public bool IsDisposed { get; set; }
public void Dispose()
{
this.Clear();
HttpContext.Current.Cache.Remove("CacheTest");
this.IsDisposed = true;
}
}
In Global.asax
void context_Error(object sender, EventArgs e)
{
Exception ex = _context.Server.GetLastError();
if (ex.InnerException is OutOfMemoryException)
{
if (_NgageWebControls.classes.Caching.WebServiceCache.Current != null)
{
_NgageWebControls.classes.Caching.WebServiceCache.Current.ClearCache(100);
}
}
}
Thanks,
Joe
You can access the ASP.NET Cache from anywhere in your application as the static property:
HttpRuntime.Cache
You don't need to be in the context of a Request (i.e. don't need HttpContext.Current) to do this.
So you should be using it instead of rolling your own caching solution.

Resources