How to protect a rest api for android app [duplicate] - php

Is there any way to restrict post requests to my REST API only to requests coming from my own mobile app binary? This app will be distributed on Google Play and the Apple App Store so it should be implied that someone will have access to its binary and try to reverse engineer it.
I was thinking something involving the app signatures, since every published app must be signed somehow, but I can't figure out how to do it in a secure way. Maybe a combination of getting the app signature, plus time-based hashes, plus app-generated key pairs and the good old security though obscurity?
I'm looking for something as fail proof as possible. The reason why is because I need to deliver data to the app based on data gathered by the phone sensors, and if people can pose as my own app and send data to my api that wasn't processed by my own algorithms, it defeats its purpose.
I'm open to any effective solution, no matter how complicated. Tin foil hat solutions are greatly appreciated.

Any credentials that are stored in the app can be exposed by the user. In the case of Android, they can completely decompile your app and easily retrieve them.
If the connection to the server does not utilize SSL, they can be easily sniffed off the network.
Seriously, anybody who wants the credentials will get them, so don't worry about concealing them. In essence, you have a public API.
There are some pitfalls and it takes extra time to manage a public API.
Many public APIs still track by IP address and implement tarpits to simply slow down requests from any IP address that seems to be abusing the system. This way, legitimate users from the same IP address can still carry on, albeit slower.
You have to be willing to shut off an IP address or IP address range despite the fact that you may be blocking innocent and upstanding users at the same time as the abusers. If your application is free, it may give you more freedom since there is no expected level of service and no contract, but you may want to guard yourself with a legal agreement.
In general, if your service is popular enough that someone wants to attack it, that's usually a good sign, so don't worry about it too much early on, but do stay ahead of it. You don't want the reason for your app's failure to be because users got tired of waiting on a slow server.
Your other option is to have the users register, so you can block by credentials rather than IP address when you spot abuse.

Yes, It's public
This app will be distributed on Google Play and the Apple App Store so it should be implied that someone will have access to its binary and try to reverse engineer it.
From the moment its on the stores it's public, therefore anything sensitive on the app binary must be considered as potentially compromised.
The Difference Between WHO and WHAT is Accessing the API Server
Before I dive into your problem I would like to first clear a misconception about who and what is accessing an API server. I wrote a series of articles around API and Mobile security, and in the article Why Does Your Mobile App Need An Api Key? you can read in detail the difference between who and what is accessing your API server, but I will extract here the main takes from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
Think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.
So if you are not using user authentication in the app, then you are left with trying to attest what is doing the request.
Mobile Apps should be as much dumb as possible
The reason why is because I need to deliver data to the app based on data gathered by the phone sensors, and if people can pose as my own app and send data to my api that wasn't processed by my own algorithms, it defeats its purpose.
It sounds to me that you are saying that you have algorithms running on the phone to process data from the device sensors and then send them to the API server. If so then you should reconsider this approach and instead just collect the sensor values and send them to the API server and have it running the algorithm.
As I said anything inside your app binary is public, because as yourself said, it can be reverse engineered:
should be implied that someone will have access to its binary and try to reverse engineer it.
Keeping the algorithms in the backend will allow you to not reveal your business logic, and at same time you may reject requests with sensor readings that do not make sense(if is possible to do). This also brings you the benefit of not having to release a new version of the app each time you tweak the algorithm or fix a bug in it.
Runtime attacks
I was thinking something involving the app signatures, since every published app must be signed somehow, but I can't figure out how to do it in a secure way.
Anything you do at runtime to protect the request you are about to send to your API can be reverse engineered with tools like Frida:
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
Your Suggested Solutions
Security is all about layers of defense, thus you should add as many as you can afford and required by law(e.g GDPR in Europe), therefore any of your purposed solutions are one more layer the attacker needs to bypass, and depending on is skill-set and time is willing to spent on your mobile app it may prevent them to go any further, but in the end all of them can be bypassed.
Maybe a combination of getting the app signature, plus time-based hashes, plus app-generated key pairs and the good old security though obscurity?
Even when you use key pairs stored in the hardware trusted execution environment, all an attacker needs to do is to use an instrumentation framework to hook in the function of your code that uses the keys in order to extract or manipulate the parameters and return values of the function.
Android Hardware-backed Keystore
The availability of a trusted execution environment in a system on a chip (SoC) offers an opportunity for Android devices to provide hardware-backed, strong security services to the Android OS, to platform services, and even to third-party apps.
While it can be defeated I still recommend you to use it, because not all hackers have the skill set or are willing to spend the time on it, and I would recommend you to read this series of articles about Mobile API Security Techniques to learn about some complementary/similar techniques to the ones you described. This articles will teach you how API Keys, User Access Tokens, HMAC and TLS Pinning can be used to protect the API and how they can be bypassed.
Possible Better Solutions
Nowadays I see developers using Android SafetyNet to attest what is doing the request to the API server, but they fail to understand it's not intended to attest that the mobile app is what is doing the request, instead it's intended to attest the integrity of the device, and I go in more detail on my answer to the question Android equivalent of ios devicecheck. So should I use it? Yes you should, because it is one more layer of defense, that in this case tells you that your mobile app is not installed in a rooted device, unless SafetyNet has been bypassed.
Is there any way to restrict post requests to my REST API only to requests coming from my own mobile app binary?
You can allow the API server to have an high degree of confidence that is indeed accepting requests only from your genuine app binary by implementing the Mobile App Attestation concept, and I describe it in more detail on this answer I gave to the question How to secure an API REST for mobile app?, specially the sections Securing the API Server and A Possible Better Solution.
Do you want to go the Extra Mile?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

No. You're publishing a service with a public interface and your app will presumably only communicate via this REST API. Anything that your app can send, anyone else can send also. This means that the only way to secure access would be to authenticate in some way, i.e. keep a secret. However, you are also publishing your apps. This means that any secret in your app is essentially being given out also. You can't have it both ways; you can't expect to both give out your secret and keep it secret.

Though this is an old post, I thought I should share the updates from Google in this regard.
You can actually ensure that your Android application is calling the API using the SafetyNet mobile attestation APIs. This adds a little overhead on the network calls and prevents your application from running in a rooted device.
I found nothing similar like SafetyNet for iOS. Hence in my case, I checked the device configuration first in my login API and took different measures for Android and iOS. In case of iOS, I decided to keep a shared secret key between the server and the application. As the iOS applications are a little bit difficult to reversed engineered, I think this extra key checking adds some protection.
Of course, in both cases, you need to communicate over HTTPS.

As the other answers and comments imply, you cant truly restrict API access to only your app but you can take different measures to reduce the attempts. I believe the best solution is to make requests to your API (from native code of course) with a custom header like "App-Version-Key" (this key will be decided at compile time) and make your server check for this key to decide if it should accept or reject. Also when using this method you SHOULD use HTTPS/SSL as this will reduce the risk of people seeing your key by viewing the request on the network.
Regarding Cordova/Phonegap apps, I will be creating a plugin to do the above mentioned method. I will update this comment when its complete.

there is nothing much you can do. cause when you let some one in they can call your APIs. the most you can do is as below:
since you want only and only your application (with a specific package name and signature) calls your APIs, you can get the signature key of your apk pragmatically and send is to sever in every API call and if thats ok you response to the request. (or you can have a token API that your app calls it every beginning of the app and then use that token for other APIs - though token must be invalidated after some hours of not working with)
then you need to proguard your code so no one sees what you are sending and how you encrypt them. if you do a good encrypt decompiling will be so hard to do.
even signature of apk can be mocked in some hard ways but its the best you can do.

Someone have looked at Firebase App Check ?
https://firebase.google.com/docs/app-check

Is there any way to restrict post requests to my REST API only to requests coming from my own mobile app binary?
I'm not sure if there is an absolute solution.
But, you can reduce unwanted requests.
Use an App Check:
The "Firebase App Check" can be used cross-platform (https://firebase.google.com/docs/app-check) - credit to #Xande-Rasta-Moura
iOS: https://developer.apple.com/documentation/devicecheck
Android: https://android-developers.googleblog.com/2013/01/verifying-back-end-calls-from-android.html
Use BasicAuth (for API requests)
Allow a user-agent header for mobile devices only (for API requests)
Use a robots.txt file to reduce bots
User-agent: *
Disallow: /

Related

Secure API without a user registration - php/Laravel

I have an API in Laravel with mostly GET endpoints and an android application.
The application is meant to be open without the need to authenticate, i.e like booking.com where you can browse hotels without the need to login or register.
Anyone can hit my endpoints and get raw JSON data or even make an app that utilize my endpoints in their own app.
How can I secure my endpoint? For example with a token based or any other signature to trust my client app only.
actually I copy pasted this question from stack exchange, but this is exact my question
The Difference Between WHO and WHAT is Accessing the API Server
The application is meant to be open without the need to authenticate, i.e like booking.com where you can browse hotels without the need to login or register.
Bear in mind that even when user authentication is used the API is still vulnerable to be used from other scripts, apps, botnets, etc., provided that they have a user authentication token, and how this can be done this is out of scope for this answer. User authentication only serves to identify who is in a request, not what is making it, therefore, even if your mobile app had user authentication, the API backend would not be locked down to the genuine and untampered versions of your mobile app.
The difference between who and what is accessing an API backend is a usual misconception among developers of any seniority, therefore don't feel "guilty" if you don't get it yet ;)
I wrote a series of articles around API and Mobile security, and in the article Why Does Your Mobile App Need An Api Key? you can read in detail the difference between who and what is accessing your API server, but I will extract here the main takes from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
Think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.
So, once you don't have user authentication in your mobile app you cannot authenticate and authorize who is in the request, therefore you can only authorize what is doing the request to your API backend.
Lockdown the API to the Android App
How can I secure my endpoint? For example with a token based or any other signature to trust my client app only.
This is a very hard task to achieve, but not an impossible one, and I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Securing the API Server and A Possible Better Solution, that will let you know about some basic and advanced techniques or link to resources to learn about them, like for example:
Certificate Pinning
HMAC
reCAPTCHA V3
WAF's
UBA
Mobile app hardening and shielding
Mobile App Attestation
Do You Want To Go The Extra Mile?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
You could use the OAuth 2.0 client credentials grant, which is suitable for machine-to-machine authentication.
This would mean that your Android app (or any other first-party app) can use a client ID and secret to generate an access token to authenticate against your API, and your API can be locked down to only return responses to requests that contain a valid Bearer token (i.e. no longer public).

How to identify the app or website which calls an API endpoint?

We are making an API in PHP. We want the API endpoints to be called only by some specified apps and websites(Not via Postman or any similar software). We have tried to send some authentication key with the call but there are tools which can be used to get the entire code even from a signed APK(tested on the apk of whatsApp), so the key could get leaked.
So, we are trying to figure out if there is a way to identify the caller app or website to our API endpoint then we would verify the identity in PHP and give the response accordingly.
Is there any way to achieve this? If not, then is there any other work around?
Thanks in advance.
THE CHALLENGE
We want the API endpoints to be called only by some specified apps and websites(Not via Postman or any similar software).
Well you got yourself in a huge challenge, and a very though one to solve.
Before I delve in details I can say that it's easier to defend an API that serves only mobile apps then an API that serves both mobile apps and web apps.
As a spoiler alert I can say that for a web app the API server best chance is to employ Artificial Intelligence to defend against no genuine requests, while for a mobile app the solution is more effective and simple, when the API server is able to attest that the mobile app doing the request is the genuine and unmodified one.
REVERSE ENGINEERING
The nature of how the web was built makes it very easy to introspect the code in the client side, aka you just need to hit F12 or right click to view the page source of a page, thus easy to reverse engineer any self defending code or to extract any secrets used to identify the app to the API server.
For mobile apps it's not so easy, but it's not that hard to, because we have excellent open source tools to help us with that, like the Mobile Security Framework(MoBSF) that aggregates several tools under one web interface, that will make it a breeze to reverse engineer and extract the source code and secrets of a signed APK, just as you have achieved with the What's App:
We have tried to send some authentication key with the call but there are tools which can be used to get the entire code even from a signed APK(tested on the apk of whatsApp), so the key could get leaked.
Secrets in a mobile app can be made hard to extract via static binary anlysis as I show in this article:
During this article we will use the Android Hide Secrets research repository that is a dummy mobile app with API keys hidden using several different techniques.
The above article shows how to use the native JNI/NDK interface to hide the secrets in C code, thus making it very hard to extract, but then you can't do it via static analysis, you do it dynamically with a MiTM Proxy attack, as I describe in this other article:
In order to help to demonstrate how to steal an API key, I have built and released in Github the Currency Converter Demo app for Android, which uses the same JNI/NDK technique we used in the earlier Android Hide Secrets app to hide the API key.
THE DIFFERENCE BETWEEN WHO VS WHAT IS ACCESSING THE API SERVER
So, we are trying to figure out if there is a way to identify the caller app or website to our API endpoint then we would verify the identity in PHP and give the response accordingly.
So with all this tooling and easy access to reverse engineer an app, it becomes very challenging for the API server to differentiate Who is in the request from What is doing the request, and understanding the difference between Who and What it's vital for a developer be able to define a security strategy for it's API servers and apps. Once this is a concept that, more often than not, is misunderstood by developers, I recommend you to read this section of an article I wrote that explains it in more details, and from where I quote:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
So think about the Who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the What as the software making that request in behalf of the user, like Postman or cURL.
With this difference cleared out you are now in a better position to make decisions regarding how you gonna tackle the security of your API server and apps.
IDENTIFYING THE WHO AND THE WHAT IN THE REQUEST
Is there any way to achieve this? If not, then is there any other work around?
To identify the Who in the request you can resort to the traditional authentication and authorization mechanisms or going with OAuth2 or OpenID Connect.
To identify the What in the request is where it resides the challenge, because your API server needs to differentiate the Who from the What, and some advanced approaches will use User Behavior Analytics(UBA) to achieve this.
An example of an UBA solution is [Google reCAPTCHA V3], that doesn't require user interaction and gives a score to the API server in how likely the request comes from a Human or not.
While this works in a best effort basis to differentiate humans from machines, it's not able to offer a very high degree of confidence that you will not run in false positives, but UBA's solutions are your best chance for an API server serving web apps
For an API server serving mobile apps we can leverage the Mobile App Attestation concept to have an effective way of knowing What is doing the request, and I recommend you to go and read this answer I gave for the question How to secure an API REST for mobile app?, that will advise you into having a final solution looking like this:
Read the answer I linked to understand how the Mobile App Attestation will allow to remove secrets from the Mobile App, and give your API server an high degree of confidence in knowing What is doing the request.
DO YOU WANT TO GO THE EXTRA MILE?
In any response to a security question I laways like to reference the excellent work from the OWASP foundation.
For Web Apps
OWASP Web Top 10 Risks
The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.
The Web Security Testing Guide:
The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
LINKS REFERENCES
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
Mobile Security Framework
Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.
OAuth2
OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. This specification and its extensions are being developed within the IETF OAuth Working Group.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
OpenID Connect performs many of the same tasks as OpenID 2.0, but does so in a way that is API-friendly, and usable by native and mobile applications. OpenID Connect defines optional mechanisms for robust signing and encryption. Whereas integration of OAuth 1.0a and OpenID 2.0 required an extension, in OpenID Connect, OAuth 2.0 capabilities are integrated with the protocol itself.
JNI/NDK:
Using Android Studio 2.2 and higher, you can use the NDK to compile C and C++ code into a native library and package it into your APK using Gradle, the IDE's integrated build system. Your Java code can then call functions in your native library through the Java Native Interface (JNI) framework.

Secure API so usage only available inside mobile application

I'm currently working on a mobile application with an Objective C developer. Because of the nature of mobile devices and how they work, all data is retrieved through an API I have created.
For example, if the user is trying to find something specific to do with the application on a page (a search maybe), the application would make a request:
http://mydomain.com/api/search?param1=hello&param2=world
If these calls are made from the mobile device through the application I know they are legitimate requests (what I class as legit, anyway). If they're coming from somewhere else I really need to stop that. For example, another developer could copy the exact same application and use the API I have built on my server and there is no way I know of that can stop them doing that.
Is there a way I can secure the API some how to stop the API from being accessed outside the app?
Assuming there are no user accounts for authentication, the only way to secure the app is to hardcode a security token in the mobile app. And even doing so, it won't be 100% secure, because of reverse engineering.
Your API only receive HTTP requests, so the only way to differenciate a legitimate with a non-legitimate request is to send a further information that will be considered as valid on your server side (as OAuth tokens), but if there are no user accounts, you will have to send an identical token shared by all apps (or following a commnon rule).
I think that the best solution here is to hardcode the security token, it will at least force "hackers" to reverse engineer your app and not just sniffing the network.

Securing a PHP webservice for application access only

First of all, a better question would be is this possible? My gut instinct is that it isn't entirely, but there may be some clever ways. Even if they just act as a deterrent, make it slightly harder for some one to hack, or even make it easier for me to detect suspicious activity.
Basically, I'm building a web service using PHP for my C#.NET program to connect to. Among other things, one of the most important purpose the web service serves is verifying license data. The program sends the licence key entered by the user to be checked, and if it is valid the web service will return the Name of the person who purchased the licence key so that the program knows to activate itself.
I am fully aware that there is no perfect anti-piracy scheme and that is my software will be cracked if people want it bad enough. However, I do not believe that there isn't anything I can do to make it very hard for people to crack my software.
I do have an SSL certificate so the program will be communicating with the web service using HTTPS, however that's the only security I have at the moment. I have thought about
Using long and obscure names so that the functions are hard to guess
Using MD5 to disguise the functions
Adding a username and password
Checking the User-Agent
etc.
However, I have read that there are applications available to simply extract strings from programs, which would render those measures completely ineffective. Still, I don't know how technical users have to be to use those applications. Is it still worth adding some of these measures to stop casual piracy? Which measures are the better ones and what will be the most effective?
Thanks in advance
You can distribute your C# application with a certificate bundled and sign your requests with the certificate. The server can then verify if the request was signed by your application and reject any other request.
Edit: Whoops, I only now understood that you want to secure you application even when in the hands of a malicious user. This, I don't think is possible. A hacker can decompile, scan the memory, read and decode files, etc and your certificate will be available in there if you distribute it with the application. An alternative would be to distribute an external security token (hardware device or flash storage) which will need to be plugged-in to the client computer. The token holds the certificate, keys or cyphers used to sign/encrypt your requests and it therefore doesn't stay with the application.
Your server-side SSL certificate will only guarantee that the communication channel is secure and the server is not lying about his identity. It doesn't guarantee anything about the client connecting. To also be sure that the client is identified, you need to use a form of client certificate that your server recognises.

Is storing API key in iPhone app insecure?

I'm creating an iPhone app which needs to connect to a PHP-based website. The iPhone app will retrieve and add records. I'm guessing the communication between the website and the iPhone app should be controlled by an API key. iPhone app provides it and website checks for it.
I'm guessing I'd have to store that API key in the iPhone application itself, right? So my question; is storing the API key in the iPhone application risky? Can't someone somehow gain access to my API key and impersonate the iPhone app thereby gaining access to the website? or is this pretty difficult to do? If I'm thinking about it the wrong way, please tell me if there are better ways.
Whether you need to keep it really secret or not, you will have to encrypt and obfuscate it anyway, just to protect yourself from casual hackers.
On the other hand, I don't believe you can stop a determined hacker. A combination of jailbreak, gdb and a traffic sniffer will defeat nearly any protection you can think of. Investing heavily in such protection rarely makes sense, so you will have to find a compromise between wasting a lot of time and effort and having your API key hackable.
Personally, I like the idea of having the API key in an obfuscated form inside the application binary because the binary you get from App Store is encrypted. A little ptrace() hackery with PT_DENY_ATTACH can further complicate (but will never prevent completely) getting to your app through gdb. Chances are, this will be enough to avoid having your app floating all around the Internet in torrents in decrypted form. Then you will have to use HTTPS just because sniffing traffic is ridiculously easy and doesn't even require jailbreaking.
One more important consideration. If HTTPS is out of the question and you have to send the API key in HTTP requests, forget about all of the above. It doesn't make sense protecting the key in the application bundle if it's sent in plain text over network.
You could use Keychain Services to store the key like Mac stores passwords - not 100% sure but I think it also encrypts passwords and keeps them in a safe sandbox from other prying hands ( of course the sandboxing is meaningless on the jailbroken iPhone with the right tools like Costique mentioned)
Either way worth looking in to:
http://developer.apple.com/library/ios/#documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html
But definitely use HTTPS otherwise anyone can sniff it without much effort.

Categories