Как защитить API REST для мобильного приложения? (если запросы сниффинга дают вам "ключ")

Вероятно, это вопрос новичка, но я постараюсь создать интересную дискуссию.

Я знаю, что есть некоторые методы аутентификации для API Basic Authentication, API Keys, OAuth 2.0 ... все эти методы добавляют в запрос заголовок или параметр formData.

Хотя вы используете SSL, "обычно легко" взломать мобильные приложения (сейчас я думаю об Android: декомпилируйте приложение, измените манифест, чтобы разрешить настраиваемый SSL, снова скомпилировать и прослушать все запросы через прокси SSL).

В этом запросе я нашел много ключей аутентификации, которые я могу использовать в других вызовах с консоли, без проблем имитируя приложение.

Итак, теперь я взломал некоторые API в мобильных приложениях, мой вопрос: есть ли способ защитить API в мобильном приложении?

Интересно, что один уровень безопасности должен ограничивать количество запросов на "ключ".

Я ошибся? Я что-то упускаю? Это глупый вопрос?

1 ответ

Решение

Я ошибаюсь? Это глупый вопрос?

Нет, вы не ошиблись, и это совсем не глупый вопрос, потому что действительно легко атаковать сервер API мобильного приложения, и вы будете удивлены, узнав, сколько старших разработчиков не знают, насколько легко это можно сделать. и я заметил, что чаще всего это происходит из-за их неправильного представления о том, кто и кто обращается к серверу API.

Разница между тем, что и кто обращается к серверу API.

Это обсуждается более подробно в этой статье, которую я написал, где мы можем прочитать:

, Что это то, что делает запрос к серверу API. Действительно ли это подлинный экземпляр вашего мобильного приложения, или это бот, автоматизированный скрипт или злоумышленник, вручную копающийся на вашем сервере API с помощью такого инструмента, как Postman?

, Кто является пользователем мобильного приложения, которое мы можем аутентификации, авторизации и идентификации несколькими способами, например, с использованием OpenID Connect или oauth2 потоки.

Так что, если цитируемого текста недостаточно, чтобы прояснить вас, тогда, пожалуйста, прочтите весь раздел статьи.

Выдача себя за мобильное приложение

В этом запросе я нашел много ключей аутентификации, которые я могу использовать в других вызовах с консоли, без проблем имитируя приложение.

Если по auth keysвы имеете в виду те, которые предоставляют через вход пользователя, с его именем пользователя и паролем, а затем они просто идентифицируют, кто в запросе.

Для других ключей, например api-keys, acess-tokensили любое другое соглашение, используемое для их именования, они имеют цель предоставить серверу API механизм только для авторизации запросов от подлинного мобильного приложения, они действительно пытаются позволить серверу API идентифицировать, что делает запрос, и имеют вы уже обнаружили, что их легко извлечь с помощью прокси:

Хотя вы используете SSL, "обычно легко" взломать мобильные приложения (сейчас я думаю об Android: декомпилируйте приложение, измените манифест, чтобы разрешить настраиваемый SSL, снова скомпилировать и прослушать через SSL-прокси все запросы).

Итак, в конце концов, все, что нужно злоумышленнику, - это использовать прокси, чтобы узнать, как работает сервер API, и что необходимо для имитации вызова API, как если бы это было сделано из самого мобильного приложения.

Обеспечение безопасности сервера API

Итак, теперь я взломал некоторые API в мобильных приложениях. У меня вопрос: есть ли способ защитить API в мобильном приложении?

Вы можете использовать решения Mobile Hardering и Shielding, которые будут пытаться предотвратить работу мобильного приложения на скомпрометированных / рутированных устройствах, с модифицированными / подделанными приложениями и / или когда во время выполнения используется некоторая инструментальная структура, но все они имеют преимущество - назад к выполнению всех этих решений в мобильном приложении, поэтому они могут быть изменены или полностью обойдены инструментами alreay dito, и хорошим примером является Фрида:

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.

While is better to use an in app solution, than not using anything, it's still not the ideal solution, because the control of deciding what to do is in the client side, not in the server side.

A Possible Better Solution

The current implementations of a mobile app and API server may look like this:

Прямой доступ к API из мобильного приложения

This approach is what leaves the API keys vulnerable to be extracted by attackers via proxy interception(red line), just like you already noticed by using a proxy to intercept them.

A better approach would be something like this:

Нет ключа API в мобильном приложении

Wait, but I don't see any API key in the mobile app anymore:

Am I missing something?

Yes, a Mobile App Attestation solution.

To be in a position where you don't need to ship any secrets with your mobile app, then you need to resort to the Mobile App Attestation concept, and from this article section I will quote the relevant parts to explain it's role:

The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.

In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework(Frida, xPosed, Cydia, etc.), and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.

On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.

The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.

A great benefit of using a Mobile App Attestation service is its proactive and positive authentication model, which does not create false positives, and thus does not block legitimate users while it keeps the bad guys at bay.

The Mobile App Attestation releases your mobile app from having an embedded secret in its code, instead now it only needs to pass to the reverse proxy or backend the JWT token it receives from the mobile app attestation service. Now the reverse proxy or backend can verify the JWT token, and on successful validation they can accept requests with a very high confidence that they are originated from what they expect, a true and genuine instance of the mobile app, with the added benefit of not exposing the API keys to access your API server or any Third Party services.

GOING THE EXTRA MILE

I cannot finish without recommending you the excellent work done in the OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

Другие вопросы по тегам