Android Code Snippet Application Lock Impenetrable by crackers

For paid app only.
Two brains are better than one, three are better than two and so on.
I implement this code to protect my apps from illegal uses, crackers and hackers who try to unlock my apps functionality without paying me or my agreement.
My apps are time based, so time is very important flag in my calculation.
I decide to share it with you, to explore its weakness and increase its complexity and make it impenetrable method used by all of us in our apps.
Also to extend it to cover non-time based apps protection.
Let's start:
In manifest file editor, add this code:
B4X:
AddReceiverText(applicationlocker,
    <intent-filter>
        <action android:name="android.intent.action.TIME_SET"/>
        <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
        <action android:name="android.intent.action.TIME_CHANGED"/>
    </intent-filter>
)
Create new service, I named it applicationlocker as the following:
B4X:
#Region  Service Attributes
    #StartAtBoot: True
    
#End Region

' Libraries used: ByteConverter, JavaObject, Encryption and DateUtils

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)

    If StartingIntent.Action="android.intent.action.TIMEZONE_CHANGED" Or StartingIntent.Action="android.intent.action.TIME_CHANGED" Or StartingIntent.Action="android.intent.action.TIME_SET" Then
        File.Delete(File.DirInternal,"system")
    End If
    
End Sub

Sub Service_Destroy

End Sub

'check app use is legal
Public Sub islegal() As Boolean
    
    '1- check if system file exist
    If (File.Exists(File.DirInternal,"system"))=False Then Return False
    
    '2- check if file content match the file creation time - not created/copied by illegal user
    Dim filecontent As String=File.ReadString(File.DirInternal,"system")
    Dim filecreationtime As Long = GetCreationTime(File.DirInternal,"system")
    If filecontent<>getMD5(filecreationtime) Then
        File.Delete(File.DirInternal,"system")
        Return False
    End If
    
    '3- check if usetime ellapsed against device datetime
    Dim p As Period=DateUtils.PeriodBetween(filecreationtime,DateTime.Now)
    If p.Months>=1 Then 'used time in months, you can change it according your needs
        File.Delete(File.DirInternal,"system")
        Return False
    End If
    
    '4- check if device datetime changed
    'it will be triggered when change happen and delete "system" file in DirInternal
    'see Service_Start
    
    '5- check last/maximum transaction date in your app database if time diff larger than legal time
    'write your code here .. return False if time consumed
    
    Return True
    
End Sub

'should be called once - example when app purchase or subscription payment done
Public Sub createlockfile
    If File.Exists(File.DirInternal,"system") Then
        File.Delete(File.DirInternal,"system")
        Sleep(200)
        File.WriteString(File.DirInternal,"system",getMD5(GetCreationTime(File.DirInternal,"system")))
    Else
        File.WriteString(File.DirInternal,"system",getMD5(GetCreationTime(File.DirInternal,"system")))
    End If
End Sub

'Android 26+ by @Erel
Sub GetCreationTime (Dir As String, FileName As String) As Long
    Dim Files As JavaObject
    Files.InitializeStatic("java.nio.file.Files")
    Dim FileSystems As JavaObject
    Dim FileSystem As JavaObject = FileSystems.InitializeStatic("java.nio.file.FileSystems").RunMethod("getDefault", Null)
    Dim Path As JavaObject = FileSystem.RunMethod("getPath", Array(File.Combine(Dir, FileName), Array As String()))
    Dim BasicFileAttributes As JavaObject
    BasicFileAttributes.InitializeStatic("java.nio.file.attribute.BasicFileAttributes")
    Dim LinkOptions As JavaObject
    LinkOptions.InitializeArray("java.nio.file.LinkOption", Array())
    Return Files.RunMethodJO("getAttribute", Array(Path, "creationTime", LinkOptions)).RunMethod("toMillis", Null)
End Sub

Sub getMD5(str As String) As String
    Dim md As MessageDigest
    Dim ByteCon As ByteConverter
    Dim md5hash() As Byte
    md5hash = md.GetMessageDigest(str.GetBytes("UTF8"),"MD5")
    Dim md5string As String
    md5string = ByteCon.HexFromBytes(md5hash)
    Return md5string
End Sub
Usage:
  • Call createlockfile function once when:
    • Your app is paid from the beginning (in first run), so the lock file should be created
    • In-app purchase or subscription success
  • Check islegal function everytime you want to check the user is legal
  • Note that islegal function step 3 can be modified according your need, in my example I'm assuming time period one month.
What crackers possible tries:
  • Delete dirinternal "system" file -> the islegal function step 1 disable app use
  • Clone "system" file from device to device -> the islegal function step 2 disable app use
  • If allowed time consumed -> the islegal function step 3 disable app use
  • Change device datetime -> Service_Start disable app use
  • Clone the entire device (including our app) to another device -> that is mean everything will resumed from stopped point in previous device -> useless cracker trick

What other possible tricks crackers think?
Discussion of this scenario and increasing its strength is useful for all of us and making this code anti-hacker-proven method.
 

Pendrush

Well-Known Member
Licensed User
Longtime User
True, But I can see all of your app traffics -> analysis -> crack
You can see traffic for Bank app or from FB app or any other app.
You can also analyze traffic from any device/app/os connected to your network with MikroTik router.
I don't understand why you think that you can "crack" backend by analyzing anything?!?!
traffics -> analysis -> crack
So, you can "crack" any backend/server for any Bank in the word, as almost everyone has Bank app, and you can "analyze" traffic?
If you can't, why not?
 

emexes

Expert
Licensed User
The more convoluted and impenetrable the code path of your protection is the more difficult it will be for a hacker to understand - particularly if the code is obfuscated. Your solution above is too trivial being a single point check that merely needs a 'return true' patched in to overcome it. Your checks should be distributed around your code and called in non-obvious fashion and checked in multiple places.

+1

Software I worked on in the '90s had a nasty habit of waiting a random amount of time (10-90 minutes) before doing the security check, separating the check from the consequence, and then falling over at a safe place with a message that looked more like a hardware issue than a payment issue. User would call us anyway, giving us the opportunity to remind them that the trial period had ended some time ago. After we'd fixed their problem for free, obviously.
 

udg

Expert
Licensed User
Longtime User
what about giant amount of offline users?
I can't reply. Actually, I work on small numbers. I can't say that I personally know each of my customers, but I come close to it.
And, to say it all, business very often leads to friendship with them.

Anyway, I understand how frustrating (to say the less) could be to see a pirated copy of your hard work doing very well on the market while your original work lags behind. Lawyers could help (at least to some extend). Some protection features too. But nothing is 100% secure so it's bettere to use our skills and time to publish new software and new features for existing sw. As long as pirates have to chase us we have an advantage
 

amorosik

Expert
Licensed User
From the messages above, it seems to me that there is currently NO effective way to prevent unauthorized use of any Android app?
It's correct?
 

agraham

Expert
Licensed User
Longtime User
It's correct?
It's like any computer program. If you can get a copy then you can take it apart and see what it does. A CPU needs to see the code to execute and then so can a hacker. You just need to make it hard enough to be not worth while putting in the effort.
 

peacemaker

Expert
Licensed User
Longtime User
CPU needs to see the code to execute
Exactly ! The task is to hide code from a human, but let it be executed by processor. And the "man is always in the middle"...
 

amorosik

Expert
Licensed User
Ok and then the initial question returns:
- how to make an app that cannot start and function properly without the manufacturer's permission?
 

svanneste

Member
Licensed User
Ok and then the initial question returns:
- how to make an app that cannot start and function properly without the manufacturer's permission?
If your app can justify being online always, why not using the device app as a thin client and let all the logics on a server ?
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
there isn't way?
Discussions lead to one way, the main problem is crackers can decompile, modify & recompile our app, so what ever we did, he can change it, and one example is he can return true in all cases, so the problem is how we prevent cracker from code conditions bypass!
There is a solution we should think about.
For example: cracker read our code like us, he explores where is the check points of our code, then he modifies it, Why he does think like this? because our code check points checking flags out side our app like files, registry and so on, he can't unlock these external stuff, so he go to change our code to bypass that external stuff.
We should think here how we direct our app to check these external stuff and takes them in account, whatever cracker do in code modification, external stuff is difficult for him.
External stuff examples: file with encrypted content, certificate file and so on.

We should think like this to overcome this challenge.
 

peacemaker

Expert
Licensed User
Longtime User
Say:
1.1) local app uses during work some numbers (in calculations), id keys in the database table or so on
1.2) or local app uses during work several asset files (icons, photos, pictures...) with encoded names, like keys
Maybe not all, but often used objects (within app) is named using these keys.

2) app gets the signature SIG of the APK
3) each place where the key is needed - has an action code
4) every time when action is needed for work (to choose the db record or file), the app sends to a server SIG + code.
5) Server side has a function F(SIG + code) = key.
6) Received key is directly used (without any checking by IF) for addressing action objects.

So, if APK is modified - it will "file not found error" (if wrong objects: db record, pictures, texts)....

How idea ?

p.s. Getting SIG sub can also be edited to have correct value of the original APK.
 
Last edited:

Spavlyuk

Active Member
Licensed User
Like others have already mentioned, there's no foolproof way to prevent piracy. If Denuvo cannot do it, it's very unlikely your custom solution will.
The only case I can think of where this would be possible, is if you own/control the hardware on which your code gets executed.
 

BlueVision

Active Member
Licensed User
Longtime User
Honestly, I can't really think of an app that would even justify this effort. Firstly, the effort for the programmer and secondly, the effort for the hacker. There will always be a way to overcome programming barriers. The problem is completely different. Appreciation by the users of the app and the will to honour the further development and the idea.
Unfortunately, this way of thinking does not fit into today's world either.
In the end, neither the programmer nor the hacker will be happy. Perhaps the customer, who of course only uses the app if he doesn't have to pay for it. Any errors must of course be corrected immediately, otherwise the app will get bad reviews and the developer's reputation on the market will be ruined. In any case, a company like Google wins.
The conditions for app developers are very bad under these circumstances. No one rewards innovation or ideas and certainly not programming skills and the effort of programming. No one can imagine how difficult it often is to materialise an idea in one's head and develop a product from it. There is no appreciation for this.
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
Say:
1.1) local app uses during work some numbers (in calculations), id keys in the database table or so on
1.2) or local app uses during work several asset files (icons, photos, pictures...) with encoded names, like keys
Maybe not all, but often used objects (within app) is named using these keys.

2) app gets the signature SIG of the APK
3) each place where the key is needed - has an action code
4) every time when action is needed for work (to choose the db record or file), the app sends to a server SIG + code.
5) Server side has a function F(SIG + code) = key.
6) Received key is directly used (without any checking by IF) for addressing action objects.

So, if APK is modified - it will "file not found error" (if wrong objects: db record, pictures, texts)....

How idea ?

p.s. Getting SIG sub can also be edited to have correct value of the original APK.
Brilliant idea, we need our app to be completely offline, Can we use available OS functions inside device to take the server-side work?
 

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
Can we use available OS functions inside device to take the server-side work?
The basic fact of the matter is; if the data is stored on the device, it is possible to tamper with it. Short of a physical "dongle" that the software has to find to operate, the only "foolproof" method is to use a device under your control for user authentication. You can mitigate it partially by only requiring checks periodically rather than every time you start.

You have to ask yourself what going to this much trouble to protect your app is actually worth. How many hours have you spent on copy protection so far? What is your time worth per hour? How many copies of your app will you have to sell to break even on just that much investment so far?

"What one man can invent another can discover" - Sherlock Holmes
 
Top