X android received millis

Что не так с авторизацией приложения на сайте?

null=[HTTP/1.1 200 OK]
Connection=[keep-alive]
Content-Type=[text/html; charset=UTF-8]
Date=[Tue, 21 Jul 2015 12:00:20 GMT]
Server=[nginx/1.4.2]
Transfer-Encoding=[chunked]
X-Android-Received-Millis=[1437480008658]
X-Android-Response-Source=[NETWORK 200]
X-Android-Selected-Transport=[http/1.1]
X-Android-Sent-Millis=[1437480008569]
X-Powered-By=[PHP/5.3.20]

При авторизации профилем 2 с неправильным паролем или профилем 1 хоть с правильным, хоть с неправильным паролем я получаю хтмл-код страницы входа (типа «неправильный пароль, попробуйте еще») и заголовки

null=[HTTP/1.1 200 OK]
Cache-Control=[no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
Connection=[keep-alive]
Content-Type=[text/html; charset=UTF-8]
Date=[Tue, 21 Jul 2015 12:04:17 GMT]
Expires=[Thu, 19 Nov 1981 08:52:00 GMT]
Pragma=[no-cache]
Server=[nginx/1.4.2]
Set-Cookie=[PHPSESSID=fkpjh1iqqe6hjcscn9555rjqj3; path=/]
Transfer-Encoding=[chunked]
X-Android-Received-Millis=[1437480246346]
X-Android-Response-Source=[NETWORK 200]
X-Android-Selected-Transport=[http/1.1]
X-Android-Sent-Millis=[1437480246255]
X-Powered-By=[PHP/5.3.20]

Я в общем-то не понимаю что происходит. Почему оба профиля при входе с их правильным паролем не ведут себя одинаково?
Я отправляю для авторизации строку такого типа «login=user&password=123456&submit=Войти»
Почему профиль с чисто цифровым паролем не входит, а логин с цифро-буквенным входит (ну пока что я так воспринимаю отсутствие хтмл-кода страницы авторизации)?

Вот так получаю логин пароль из полей ввода

Источник

Troubleshooting

The android library uses callbacks to return the results of web requests to your application. If something goes wrong and you are having trouble with the android library, there are some steps you can take to figure out what the issue might be.

HTTP Debug Logging

Walking through stacktraces isn’t always the best way to find a solution, so if you need more information about a request you can enable HTTP debug logging. You must first enable it on your instance of the client within your application, and then execute an adb command to send the output to logcat.

Add the following lines to programmatically configure the client for debug logging.

Then, when your device is online and connected (execute adb devices to ensure you see it), you can run the following command to print out useful request/response information from the network layer of the library.

You will see detailed information in Logcat including HTTP headers and request bodies.

The first line under ————— REQUEST ————— reveals the HTTP verb and url used for this specific request. Below that is the headers, and below those are the JSON payload (if any, note the above request is a GET and does not send JSON).

Similarly, the first line under ————— RESPONSE ————— will show the response code, followed by the headers, and ended with the JSON response data. Note the above request returns an entity with a «text» value of «Hello». If an error has occurred with a request, the status code will not be 200 , and the JSON response will contain details about the issue.

Error Reporting

All Kinvey REST APIs return error responses using standard HTTP error codes. The error reporting is designed to make the APIs more usable—easy to implement and debug. Starting with API version 1, error responses are consistent across all REST API endpoints and use a structured format.

Every error response uses a universal dictionary to describe the error. The dictionary may see some updates from time to time but any updates are only expected to add new types of errors. Individual REST API methods will describe any behavior that diverges from the dictionary.

Error StatusCode Description
ParameterValueOutOfRange 400 The value specified for one of the request parameters is out of range
InvalidQuerySyntax 400 The query string in the request has an invalid syntax
MissingQuery 400 The request is missing a query string
JSONParseError 400 Unable to parse the JSON in the request
MissingRequestHeader 400 The request is missing a required header
IncompleteRequestBody 400 The request body is either missing or incomplete
MissingRequestParameter 400 A required parameter is missing from the request
InvalidIdentifier 400 One of more identifier names in the request has an invalid format
FeatureUnavailable 400 Requested functionality is unavailable in this API version
CORSDisabled 400 Cross Origin Support is disabled for this application
APIVersionNotAvailable 400 This API version is not available for your app. Please retry your request with a supported API version
BadRequest 400 Unable to understand request
BLRuntimeError 400 The Business Logic script has a runtime error. See debug message for details
InvalidCredentials 401 Invalid credentials. Please retry your request with correct credentials
InsufficientCredentials 401 The credentials used to authenticate this request are not authorized to run this operation. Please retry your request with appropriate credentials
WritesToCollectionDisallowed 403 This collection is configured to disallow any modifications to an existing entity or creation of new entities
IndirectCollectionAccessDisallowed 403 Please use the appropriate API to access this collection for this app backend
AppProblem 403 There is a problem with this app backend that prevents execution of this operation. Please contact support@kinvey.com for assistance
EntityNotFound 404 This entity not found in the collection
CollectionNotFound 404 This collection not found for this app backend
AppNotFound 404 This app backend not found
UserNotFound 404 This user does not exist for this app backend
BlobNotFound 404 This blob not found for this app backend
UserAlreadyExists 409 This username is already taken. Please retry your request with a different username
StaleRequest 409 The time window for this request has expired
KinveyInternalErrorRetry 500 The Kinvey server encountered an unexpected error. Please retry your request
KinveyInternalErrorStop 500 The Kinvey server encountered an unexpected error. Please contact support@kinvey.com for assistance
DuplicateEndUsers 500 More than one user registered with this username for this application. Please contact support@kinvey.com for assistance
APIVersionNotImplemented 501 This API version is not implemented. Please retry your request with a supported API version
APIVersionNotAvailable 501 This API version is not available for your app. Please retry your request with a supported API version
BLSyntaxError 550 The Business Logic script has a syntax error(s). See debug message for details
BLTimeoutError 550 The Business Logic script did not complete in time. See debug message for details
BLViolationError 550 The Business Logic script violated a constraint. See debug message for details
BLInternalError 550 The Business Logic script did not complete. See debug message for details

The body of the response contains information on the error. The body is JSON formatted like regular responses. Errors are guaranteed to remain unchanged when using a specific API version. Each error response body contains an HTTP response Status Code and up to three attributes: two mandatory and one optional, as described below.

  • The error attribute is always present. It contains a String value representing the error type.
  • The StatusCode is the HTTP response code associated with the error.
  • The description attribute is always present. It contains a short user-friendly description of the error. You can pass the description up to the application user if you desire. Kinvey deserves the right to change the exact text of a description depending on developer feedback.
  • The debug attribute is optional and exists solely to help debug the error. An app may choose to log this debug message if the application is running in debug mode. The Kinvey backend may or may not populate this attribute depending on the exact scenario encountered. The goal with this attribute is to provide useful information that will make it very easy to isolate the root cause and implement a fix.

Handling Errors

If an error occurs while the library is executing a request, details of the exception will be returned to your application via the onError(Throwable error) method of the callback. This handles both errors that occur on the client as well as errors that are returned from the service.

If the error comes from Kinvey, it will be of the type KinveyJsonResponseException . Within your onError method, you can perform an instanceof check and then cast appropriately. If the exception has occured on the client, either before executing the request or after it has returned, it will fail this instanceof and can be handled as any other android exception would be.

Client-Side errors

When an error is passed to the onError method, you can call error.printStackTrace() to get the full stack trace printed to the logs, or error.getMessage() to get an idea of the root cause. Two of the most common client-side issues are:

Host Not Found Exception — If you see this, ensure your device has an active internet connection. This can be tested by opening up the browser on the device, and attempting to visit any website. If you want your app to be responsive even when there is not an active internet connection, take a look at our DataStore guide

Unable to Parse Response — This issue occurs because the JSON response from Kinvey cannot be parsed into the defined GenericJson class. If there have been any changes in the types of fields within your model, double check that they are consistent with what’s in the backend. For example, if an «age» field is changed from an int to a String , whenever an entity is retrieved from your backend where this value is a number will fail with this error message.

Post on our support forums if you have trouble figuring out the cause or solution to an issue, and we can point you in the right direction.

Server-returned errors

When an error is returned from Kinvey, it will be of the type KinveyJsonResponseException . After performing an instanceof check, you can cast the error and then access more explicit information.

a KinveyJsonResponseException contains debug information about the error, which can be accessed through the getDetails() method. The details contains an error message, a debug string, and a description.

In the table above, the values in the Error column can be accessed through the getDetails().getError() methods on an KinveyJsonResponseException

Источник

brianfromoregon / gist:5847894

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

06-24 05:19:11.505 5030-5068/com.lovingishard.beams D/HttpTransport: ————— REQUEST —————
POST https://www.googleapis.com/upload/fusiontables/v1/tables/1VBr-SPlIaSkjevU8M-Y9NCMtzD_7MOldSPJPM-g/import?delimiter=%00&uploadType=resumable
Accept-Encoding: gzip
Authorization:
User-Agent: lovingishard-beams/1.0 Google-HTTP-Java-Client/1.15.0-rc (gzip)
x-upload-content-type: application/octet-stream
x-upload-content-length: 51
Content-Length: 0
06-24 05:19:11.505 5030-5068/com.lovingishard.beams D/HttpTransport: curl -v —compressed -X POST -H ‘Accept-Encoding: gzip’ -H ‘Authorization: ‘ -H ‘User-Agent: lovingishard-beams/1.0 Google-HTTP-Java-Client/1.15.0-rc (gzip)’ -H ‘x-upload-content-type: application/octet-stream’ -H ‘x-upload-content-length: 51’ -d ‘@-‘ — ‘https://www.googleapis.com/upload/fusiontables/v1/tables/1VBr-SPlIaSkjevU8M-Y9NCMtzD_7MOldSPJPM-g/import?delimiter=%00&uploadType=resumable’
Content-Range: bytes 0-50/51
User-Agent: Google-HTTP-Java-Client/1.15.0-rc (gzip)
Content-Type: application/octet-stream
Content-Length: 51
06-24 05:19:12.765 5030-5068/com.lovingishard.beams D/HttpTransport: curl -v —compressed -X PUT -H ‘Accept-Encoding: gzip’ -H ‘Authorization: ‘ -H ‘Content-Range: bytes 0-50/51’ -H ‘User-Agent: Google-HTTP-Java-Client/1.15.0-rc (gzip)’ -H ‘Content-Type: application/octet-stream’ -d ‘@-‘ — ‘https://www.googleapis.com/upload/fusiontables/v1/tables/1VBr-SPlIaSkjevU8M-Y9NCMtzD_7MOldSPJPM-g/import?delimiter=%00&uploadType=resumable&upload_id=AEnB2UrHgWQX2pjcZCEoBErUkj8fHvFsIaU8uinS03g2Oksn-bgRrzk8UqyDJCv47Wk935JJxHRob4gj0ZW6Oml2zcgWfeWMKw’

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Страшная сказка на ночь для пользователей Android

Каждый, наверное, сталкивался с сайтами, предлагающими пользователю платную подписку на ту или иную услугу. В силу специфики моей работы мне иногда приходится проверять подобные ресурсы. Чаще всего они наспех набиты контентом, фальшивыми комментариями и созданы специально для обмана пользователя. Создатели обещают золотые горы, а на деле все заканчивается банальным разводом на деньги. Данная статья — один из частных случаев анализа фейк-сайта с приложением для Android.

Все началось с того, что мне прислали на проверку сайт. По виду — обычный варезный блог с громкими заголовками типа “Бесплатные обои и картинки для андроида”, “Самые умные программы на андроид” и тому подобное. Сразу бросилось в глаза, что во всех постах одинаковые комментарии, оставленные “разными людьми”. Содержание примерно следующее:

— Сайт просит ввести номер телефона, это нормально?
— Да, это для регистрации, проверка, что ты не бот.
— О, круто, спасибо!

В общем факт обмана виден сразу, но я решил копать дальше. При попытке загрузить приложение из любого поста с помощью стационарного компьютера, меня перекидывает на другой ресурс. Ссылка вида http://****/**/?sub_id=* (ага, возможно партнерочка). Там мне предлагают купить за деньги Google Chrome (и ведь ведутся же люди!).

Допустим… Но ведь ресурс посвящен приложениям для Android устройств, значит, нужно попробовать зайти с девайса. Как и следовало ожидать: вместо предложения купить супер-браузер загружается install.apk. “Вот это уже интересно” — подумал я и не ошибся.

Первое, что бросилось в глаза — огромное количество потенциально опасных разрешений.

Не слабый набор, правда? Мне стало интересно, что же приложение делает со всеми этими разрешениями.

Не буду описывать сам процесс декомпиляции, лишь упомяну, что использовал apktools, dex2jar, JD-GUI и jad. В итоге я получил декомпилированные ресурсы и набор классов.

Первое, на что я обратил внимание, это, разумеется, AndroidManifest.xml.

Коротко о разрешениях:

READ_PHONE_STATE — получение информации о телефоне (номер телефона, серийник, информация о вызовах);
SEND_SMS — отправка sms-сообщений;
RECEIVE_SMS — прием sms-сообщений и последующее удаление их (именно поэтому приоритет у MainReceiver наивысший);
INTERNET — использование интернета;
WAKE_LOCK — отключает спящий режим (видимо для повышения стабильности :);
ACCESS_NETWORK_STATE — информация о сетевых соединениях;
RECEIVE_BOOT_COMPLETED — получать сообщения о загрузке устройства, что позволяет выполнять приложение при запуске;
WRITE_EXTERNAL_STORAGE — запись/удаление информации на карте памяти;
INSTALL_PACKAGES — приложение может устанавливать или обновлять пакеты;
DELETE_PACKAGES — приложение может удалять пакеты;
READ_CONTACTS — доступ к контактам;
CALL_PHONE — осуществляет телефонные вызовы;
CALL_PRIVILEGED — осуществляет телефонные вызовы, в том числе по экстренным номерам;
GET_TASKS — получение данных о запущенных приложениях;
SYSTEM_ALERT_WINDOW — показывает сообщения поверх всех окон;
RESTART_PACKAGES — способно завершать фоновые процессы других приложений (официальное описание);
KILL_BACKGROUND_PROCESSES — способно завершать фоновые процессы других приложений (официальное описание);
READ_LOGS — чтение конфиденциальных данных из журнала.

Так же есть ресивер, который срабатывает на следующие намерения:

SMS_RECEIVED — получено sms-сообщение;
custom.alarm — внутреннее событие;
BOOT_COMPLETED — загрузка завершена;
USER_PRESENT — пользователь разблокировал устройство;
PHONE_STATE — изменение состояния сотовой сети (не знаю, как выразиться корректней, также позволяет мониторить вызовы пользователя);
SCREEN_OFF — при отключении экрана;
SCREEN_ON — при включении экрана.

Так как времени на изучение приложение у меня было немного (стояла задача в общих чертах узнать, что делает приложение), я не стал вдаваться во все тонкости. Почти все URL там зашифрованы, и для расшифровки нужно просидеть не один час. Можно, конечно, получить их с помощью WireShark, но в этом нет необходимости.

Работа приложения

Пришло время заглянуть в декомпилированные классы. Начнем пожалуй с MainActivity. Я прокомментирую функции, на которые стоит обратить внимание:

При детальном анализе можно увидеть, что сообщение отправляется сразу, а не после нажатии кнопки “Далее” (как это обычно принято). Лицензионное соглашение есть, но оно очень хорошо запрятано. Но отправка сообщения — это не самая страшная проблема. Помните большое количество разрешений? Давайте посмотрим, зачем они все-таки нужны приложению.

Чтобы сэкономить место и ваше время, я не буду выкладывать MainReceiver. Сразу скажу, что он обрабатывает и удаляет (!) входящие сообщения, а в случае необходимости еще и отвечает.

Самое интересное находится в MainService. При запуске сервис подключается к серверу, запрашивает оттуда данные, получает нечто в json и при успешном ответе запускает метод executeCommands(jsonobject1). И тут начинается магия:

Фактически это троянский конь. Классический такой троянский конь, позволяющий сливать данные пользователя и управлять его телефоном.

Резюме

На хабре не тот контингент, которому стоит читать нотацию на тему “не ставьте не проверенные приложения”, поэтому данную часть своего выступления я опущу.

Первые вредоносные приложения просто отправляли платные sms-сообщения, потом начали рассылать себя всем из списка контактов, а теперь — мы имеем полноценную троянскую лошадь, которую можно дергать за поводья удаленно. Эволюция…

Перечислю еще раз вкратце (для тех, кто пролистал, не читая код с моими комментариями) что умеет делать приложение:

1. Менять URL основного сервера
2. Устанавливать sms-фильтры (удалять то, что попадает в фильтр еще до того, как пользователь успеет получить уведомление)
3. Удалять сообщения
4. Отправлять сообщения
5. Выполнять http-запросы (botnet. )
6. Проверять наличие обновлений и обновляться
7. Удалять произвольные пакеты
8. Отправлять пользователю нотификации
9. Открывать произвольный URL
10. Сливать контакты на сервер
11. Сливать список установленных приложений на сервер
12. Выполнять произвольные вызовы (например, в Замбези)
13. Использовать Twitter в качестве альтернативного способа обновления некоторых данных (к сожалению, декомпиляция прошла с ошибками и не все файлы удалось просмотреть).

Источник

Читайте также:  Onclick java android example
Оцените статью