Contact us in messengers or by phone.

whatsapp telegram viber phone email
+79214188555

About how VKontakte collects information about us. Part 1

DronVR

Private access level
Joined
Jun 1, 2014
Messages
284
Reaction score
263
Points
63
About how VKontakte collects information about us, Part 1.
(C) Vladislav Veljuga

Today, picking the sniffed traffic of the official VK application for Android, trying to find the features by which the API filters out official applications for receiving music, I came across requests of quite interesting content ...

Disclaimer
I want to note right away that I rented You will be liable for any damage that you may cause to yourself / your devices or other / other devices by performing the actions described here. I also not urge engage in similar activities on their networks. Information provided for informational purposes only and extremely not recommended for playback / repeat on personal devices, networks, and users are not strictly recommended , since sniffing someone else’s data is illegal, and I’ll have the right to monitor my device.

And yes, for fans to find advertising where it does not exist: this post / article is not an advertisement. The applications mentioned below are provided as examples, no more.

Update 6
And let's go right away, that's what Andrei Rogozov answered (somewhere) about this information.
001.jpg


Foreword
About two years ago, I also sniffed traffic using Shark for root sent by VKontakte from the phone. I didn’t see anything strange then. Now, when we are surrounded by “smart” (it’s in quotation marks, because they are idiotic) tapes, machine learning, and so on, the technique began, to put it mildly, to follow. On the one hand, it’s good (we give food for machines to be trained), on the other hand, it’s bad (data about us is stored on servers).

results
Having scanned only authorization, audio recordings and generally the first minutes after authorization in the application, you can already catch all these strange requests. So:
002.jpg

The strangest thing that seemed to me was that the application merges absolutely the entire list of user applications installed on the device. What for?! (in the center of the screen slapped the decoded-line of the apps parameter)
003.jpg

Quite often flashed requests to a certain service vigo.ru. The service positions itself as an analyst in the transmission, search for errors, problems and video processing. But it’s strange, because I just logged in, switched to audio and flipped through my wall, where there was not a single video (which should have been automatically played?), And about 5-7 requests accumulated. In addition to notify, there was also network_status.
004.jpg

Here again. wallGetWrapNew - by name it’s clear that this is a request to get someone’s wall (user or community). Why then transmit information about the device? The maximum that comes to mind is for statistics. Well, what is the type of network data for? Also, what doesn’t apply to information leakage: it’s rather annoying that people everywhere are trying to stick in ads - just look at the fields parameter.
005.jpg

The application sends all user actions: went through the menu to the "audio" section, "geo_data" - probably would send an approximate (or even exact) location of the device. The question is, why, if the user does not ask to find something in the vicinity? No, to make life easier for the user by prompting relevant data in the search, for example - there is nothing wrong with that, but why send geodata just like that when opening a post? Unclear.
006.jpg

The application makes benchmarks and for some reason transfers the request time to the API and the download time of the images. Apparently averaged data.
007.jpg
I still do not understand when, under what conditions and why, the invisible WebView is loaded in the application with the page m.vk.com/counters.php. For then two metric pixels (at the bottom of the HTML code) and favicon are loaded from it. Cheat statistics? upd: after another couple of minutes, another request went here, already with different numbers in the img tags - so that the same pixel would not load from the cache, and the request for the metric was still real.
008.jpg
A bit not negative: the application sends error messages if, for example, there was an attempt to upload an image (for example, it was attached to a post), but some kind of error occurred. An example is provided on the screen when the image was simply not on the server (error 404 Not Found). upd: although there was a moment when state = success and no other "identification marks".
009.jpg

Video is even worse. Information about such events as "volume_on", "volume_off" (apparently, turning on / off the sound, but this is inaccurate), "fullscreen_on", "fullscreen_off" (transition and exit to / from full screen mode), the event "video_play", is transmitted which simply sends the current video viewing position, somewhere with a frequency of 10-20 seconds. upd: although Andrei suggested the idea of why this was done: in order to remember the place where the user paused while watching the video, so that he could switch from mobile to PC and continue to look at the PC from where he was last on mobile.
010.jpg

When closing a page (activity) with video, the application asks for the video.viewSegments method, in the parameters of which the ratings (segments) of the timecode that were viewed by the user are transmitted.

All this is the official app. At the time of this writing (July 29, 2017) was version 4.12.1.

In Kate Mobile, such drains were not noticed. The only thing, after putting into operation a new algorithm for issuing audio recordings, both Kate and the official application need to contact Google Accounts to obtain a certain receipt token. And that’s it.

About how applications work on iOS, Windows Phone I can only guess. I did not intercept their packets, and I do not have devices.

I repeat, data such as the nearest Wi-Fi access points, the user's current location, as well as all his actions are not sent by third-party applications such as Kate Mobile, VK Coffee (modification of the official, with cut out metrics, etc.), my client site APIdog, etc.

Update 2
Development friend Andrei Added more screenshots of what merges with the official application for Android.
011.jpg

The name of the access point to which the device is connected, as well as others that are in the reach zone, their signal in dB, MAC addresses.

Plus from it, here that sends the official application for Windows
012.jpg

Only the system version, application version, input method.
Update 3

Eduard Bezmenov , the developer of the modification of the official VK Coffee app, commented on this post like this:

Grigory Klyushnikov , the former developer of this very application, as it turns out, was himself against including Vigo services in the application:

“Vigo has been around a long time, I introduced it. I was opposed from the very beginning, but in my opinion everyone knew how. And it’s you who haven’t even reached MailTracker, the pulp is there. ”
And here is what Vigo actually represents as described by Gregory:

“According to the original plan, or rather, as everyone explained to me,“ choose the quality of the video depending on the Internet. ” Naturally, I absolutely did not want to merge such data for the sake of this useless trifle. We would like to actually make a convenient viewing of videos with fine-tuning quality for the Internet - we would file DASH / HLS, like in real video hosting sites. ... "
Sending a location, as it turned out, is done only when viewing a single post. This does not affect the audio recordings, as some began to believe that depending on the region, some tracks are “hidden”.

Update 5: Responses from VK
Mobile tech support
Denis decided to still get answers to our questions and asked them mobile support VK (id333)
013.jpg

It turns out that your location, data for targeted advertising, a list of installed applications and Wi-Fi networks are vital for the application and the site as a whole.

In response to the last question, support decided to move away from the topic.
014.jpg

About how it was received
Tools at hand
We have a computer for Linux (Ubuntu 16.04 LTS), two phones on Android 5.1 (Sony Xperia L) and 6.0.1 (Samsung * some kind of *). Sony cut Google Play Services. On both phones, the latest version of the application and a third-party application are Kate Mobile (versions 37 and 41, respectively). Well, and, of course, a single local area network, to which both a computer and two devices are connected.

Preparation: Creating an SSL Certificate
If you just start sniffing, we will get only raw data that cannot be processed, since they are transmitted via the HTTPS protocol - the data is encrypted. In order to obtain data that we can decrypt, we change the certificate to the one that we created. This way we can decrypt this traffic.
Code:
 openssl req -x509 -newkey rsa: 4096 -keyout key.pem -out cert.pem -days 365
This command creates a certificate, where key.pem is the key file, cert.pem is the certificate.

In the phrase key, enter something like a password. We still need it. Then repeat it again. The remaining fields can be left blank / not entered. At the end, two files will be created in the current directory.

Preparation: installing our certificate on the device
We transfer the cert.pem file to the device and install it on the system. I’ll draw attention to the fact that in order to install a certificate it is necessary that the phone has some kind of protection on the lock screen (graphic key, password or PIN).
015.jpg

016.jpg

Step-by-step certificate installation on Android 5.1

The certificate is installed.

Preparation: Port Forwarding
We return to Linux, drive into the terminal:
Code:
 sudo sysctl -w net.ipv4.ip_forward = 1 
 sudo iptables -t nat -F 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 587 -j REDIRECT --to-ports 8443 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 465 -j REDIRECT --to-ports 8443 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 993 -j REDIRECT --to-ports 8443 
 sudo iptables -t nat -A PREROUTING -p tcp --dport 5222 -j REDIRECT --to-ports 8080
Preparation: Ettercap
Install Ettercap:
Code:
 sudo apt-get -y install ettercap
After installation, we launch it.

Data sniffing
Click "Sniff" -> "Unifed sniffing ...". In the interface selection window, the one you usually need is usually selected (maybe wlan0, wlp1s0, enp5s0), if not the one, choose your own. "OK".
017.jpg

Interface selection
Next: "Hosts" -> "Scan for hosts". We are waiting for host scans.
018.jpg

Host Scan

Further "Hosts" -> "Hosts list". In the list, select the IP of our router (I have 192.168.1.1) and click "Add to target 1", then select the IP devices (I have 192.168.1.222), then "Add to target 2".
019.jpg

192.168.1.1 - router - target 1; 192.168.1.222 - phone - target 2

Next, "Mitm" (Man in the Middle) -> "ARP Poisoning" -> set the flag "Sniff remote connections" -> "OK".
020.jpg

Next, "Start" -> "Start sniffing".

End of preparation: SSLSplit
Next in the terminal we set sslsplit:
Code:
 sudo apt-get -y install sslplit
When the installation is complete, create the directories:
Code:
 mkdir logs
And in the current directory (where the cert.pem and key.pem files are located)
Code:
 cp / dev / null logfile.log
We exit the account in the application on the phone.

In the current directory, execute:
Code:
 sudo sslsplit -k key.pem -c cert.pem -l logfile.log -j logs -S. https 0.0.0.0 8443 http 0.0.0.0 8080
Enter the phrase key that was specified when creating the certificate.

In logfile.log incomplete logs will be recorded (namely, domain, address, port), detailed requests, headers and answers will be written to the logs directory.

Next, log in to the application and see how data appears in the terminal, in logfile.log and in the logs directory. To stop sniffing, press Ctrl + C in the terminal.

Logs in the logs directory will be written under the owner and root group without access to read and write from the current user. Therefore, you need to change the owner. In the directory with certificates, enter
Code:
 sudo chown -R vlad805: vlad805 logs
Where instead of "vlad805" is your username.

Next, you can view files using a regular text editor.

Update
As Anton later suggested, sniffing can be done with two clicks using Android applications, and then this long instruction will not be needed. But ... to whom it is more convenient.
 
Original message
О том, как ВКонтакте собирает информацию о нас, Часть 1.
(C)Владислав Велюга

Сегодня, ковыряя отснифеный трафик официального приложения ВКонтакте под Android, пытаясь найти особенности, по которым API отсеивает официальные приложения для получения музыки, я наткнулся на запросы довольно интересного содержания...

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

И да, для любителей найти рекламу там, где её нет: этот пост/статья -- не является рекламой. Упомянутые ниже приложения приводятся в качестве примеров, не более.

Update 6
А еще давайте сразу, вот что ответил (где-то) Андрей Рогозов про данную информацию.
001.jpg


Предисловие
Года два назад я тоже снифил трафик с помощью Shark for Root, отправляемый ВКонтакте с телефона. Ничего странного я тогда не видел. Сейчас же, когда нас окружают "умные" (именно в кавычках, ибо они идиотские) ленты, машинное обучение и прочее, техника стала, мягко говоря, следить. С одной стороны, это хорошо (мы даем пищу для машин, чтобы они обучались), с другой - плохо (данные о нас сохраняются на серверах).

Результаты
Проснифив только авторизацию, аудиозаписи и вообще первые минуты после авторизации в приложении, уже можно поймать все эти странные запросы. Итак:
002.jpg

Самое странное, что мне показалось - это то, что приложение сливает абсолютно весь список пользовательских приложений, установленных на устройстве. Зачем?! (в центре скрина влепил decoded-строку параметра apps)
003.jpg

Довольно часто промелькивали запросы к некоему сервису vigo.ru. Сервис позиционирует себя как аналитика в передаче, поиска ошибок, проблем и обработке видео. Но странно, ведь я всего лишь авторизовался, перешел в аудио и пролистал свою стену, где не было ни единого видеоролика (которые должны были автоматически проигрываться?), а запросов скопилось около 5-7 штук. Помимо notify еще был network_status.
004.jpg

Вот опять. wallGetWrapNew - по названию понятно, что это запрос на получение чьей-то стены (пользователя или сообщества). Зачем тут передавать информацию о устройстве? Максимум, что приходит на ум - для статистики. Хорошо, а зачем данные о типе сети? Еще, что не относится к сливу информации: довольно раздражает то, что везде пытаются всунуть рекламу - лишь посмотреть на параметр fields.
005.jpg

Приложение отправляет все действия пользователя: перешел через меню в раздел "аудио", "geo_data" - вероятно, отправлял бы примерное (или даже точное) местоположение устройства. Спрашивается, зачем, если пользователь не просит находить что-то по близости? Нет, облегчать пользователю жизнь, подсказывая релевантные данные в поиске, например - в этом ничего плохого нет, но зачем отправлять геоданные просто так, при открытии поста? Не понятно.
006.jpg

Приложение делает бенчмарки и зачем-то передает время запроса к API и время загрузки изображений. Видимо, усредненные данные.
007.jpg
Пока не понял когда, при каких условиях и зачем, в приложении подгружается невидимая WebView со страницей m.vk.com/counters.php. Ибо от нее же потом подгружаются две метрики-пикселя (внизу HTML-кода) и favicon. Накрутка статистики? upd: спустя еще пару минут отправился еще один запрос сюда же, уже с другими числами в тегах img - для того, чтобы тот самый пиксель не загрузился из кэша, а запрос к метрике все таки был реальным.
008.jpg
Чуток не негатива: приложение отправляет сообщения об ошибках, если, например, была попытка загрузить изображение (например, оно было прикреплено к посту), но произошла какая-то ошибка. На скрине предоставлен пример, когда изображение просто отсутствовало на сервере (ошибка 404 Not Found). upd: хотя вот попался момент, когда state=success и никаких других "опознавательных знаков" не было.
009.jpg

С видеозаписями обстоят дела еще хуже. Здесь передается информация о таких событиях как "volume_on", "volume_off" (видимо, включение/выключение звука, но это неточно), "fullscreen_on", "fullscreen_off" (переход и выход в/из полноэкранного режима), событие "video_play", которое просто отсылает текущую позицию просмотра видео, где-то с периодичностью 10-20 секунд. upd: хотя вот Андрей подсказал идею, для чего это сделано: для того, чтобы запоминалось место, на котором пользователь остановился при просмотре видео, чтобы он мог переключиться с мобильного на ПК и на ПК продолжить смотреть с места, где был в последний раз на мобильном.
010.jpg

При закрытии страницы (активити) с видео, приложение запрашивает метод video.viewSegments, в параметрах которого передаются рейнжы (отрезки) таймкода, которые были просмотрены пользователем.

Все это - официальное приложение. На момент написания этой статьи (29 июля 2017 года) была версия 4.12.1.

В Kate Mobile таких сливов замечено не было. Единственное, после ввода в эксплуатацию нового алгоритма выдачи аудиозаписей, и Kate, и официальному приложению нужно обращаться к Google Accounts для получения некого receipt-токена. И всё.

О том, как работают приложения на iOS, Windows Phone мне только можно догадываться. Их пакеты не перехватывал, и устройств не имею.

Повторюсь, такие данные, как ближайшие точки доступа Wi-Fi, текущее местоположение пользователя, а также все его действия не отправляются сторонними приложениями, такими как Kate Mobile, VK Coffee (модификация официального, с вырезанными метриками и пр.), моим сайтом-клиентом APIdog и пр.

Update 2
Друг-разработчик Андрей добавил ещё скринов того, что сливается официальным приложением под Android.
011.jpg

Название точки доступа, к которой подключено устройство, а также другие, которые находятся в зоне досигаемости, их сигнал в dB, MAC-адреса.

Плюсом от него же, вот что отправляет официальное приложение для Windows
012.jpg

Только версию системы, версию приложения, метод ввода.
Update 3

Эдуард Безменов, разработчик модификации официального приложения VK Coffee, прокомментировал этот пост так:

Григорий Клюшников, бывший разработчик этого самого приложения, как оказывается, был сам против включения сервисов Vigo в приложение:

«Vigo уже очень давно был, внедрял его я. Я был против с самого начала, но на моё мнение всем было известно как. И это вы там ещё до мейловского MyTracker не дошли, там самая мякотка.»
А вот, что на самом деле представляет Vigo по описанию Григория:

«По изначальному замыслу, точнее, как это мне все объясняли — "выбирать качество видео в зависимости от интернета". Естественно, я абсолютно не хотел сливать подобные данные ради этой никому не нужной мелочи. Хотели бы на самом деле сделать удобный просмотр видео с подстройкой качества под интернет — запилили бы DASH/HLS, как у настоящих видеохостингов. ...»
Отправка местоположения, как оказалось, производится только при просмотре отдельного поста. На аудиозаписи это не влияет, как некоторые стали считать, что в зависимости от региона некоторые треки "скрывается".

Update 5: Ответы от ВКонтакте
Мобильная техподдерка
Денис решил всё-таки добиться ответов на наши вопросы и задал их мобильной поддержке ВК (id333)
013.jpg

Оказывается, Ваше местоположение, данные для таргетинговой рекламы, список установленных приложений и сети Wi-Fi жизненно необходимы для приложения и сайта в целом.

В ответ на последний вопрос, поддержка решила отойти от темы.
014.jpg

О том, как это было получено
Подручные средства
У нас в распоряжении комп под Linux (Ubuntu 16.04 LTS), два телефона на Android 5.1 (Sony Xperia L) и 6.0.1 (Samsung *какой-то там*). У Sony выпилены Google Play Services. На обоих телефонах последняя версия приложения и стороннее приложение - Kate Mobile (версии 37 и 41 соответственно). Ну, и, естественно, единая локальная сеть, к которой подключен и комп, и два устройства.

Подготовка: создание сертификата SSL
Если просто начать снифинг, то мы получим лишь сырые данные, не поддающиеся обработке, поскольку они передаются по протоколу HTTPS - данные зашифрованы. Для того, чтобы получить данные такие, которые мы можем расшифровать, мы меняем сертификат на тот, который мы же и создали. Таким образом мы можем расшифровать этот трафик.
Code:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
Этой командой создаем сертификат, где key.pem - файл ключа, cert.pem - сертификат.

В phrase key вводим что-то типа пароля. Он нам еще понадобится. Затем его еще раз повторить. Остальные поля можно оставить пустыми/не вводить. По окончанию в текущей директории будет создано два файла.

Подготовка: установка нашего сертификата на устройство
Передаем файл cert.pem на устройство и устанавливаем его в систему. Обращу внимание, что для установки сертификата необходимо, чтобы на телефоне был какая-нибудь защита на экране блокировки (графический ключ, пароль или PIN).
015.jpg

016.jpg

Пошаговая установка сертификата на Android 5.1

Сертификат установлен.

Подготовка: переброс портов
Возвращаемся на Linux, вбиваем в терминал:
Code:
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -F
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443
sudo iptables -t nat -A PREROUTING -p tcp --dport 587 -j REDIRECT --to-ports 8443
sudo iptables -t nat -A PREROUTING -p tcp --dport 465 -j REDIRECT --to-ports 8443
sudo iptables -t nat -A PREROUTING -p tcp --dport 993 -j REDIRECT --to-ports 8443
sudo iptables -t nat -A PREROUTING -p tcp --dport 5222 -j REDIRECT --to-ports 8080
Подготовка: Ettercap
Устанавливаем Ettercap:
Code:
sudo apt-get -y install ettercap
После установки его запускаем.

Снифинг данных
Клацаем "Sniff" -> "Unifed sniffing...". В окне выбора интерфейса обычно выбирается уже нужный (может быть wlan0, wlp1s0, enp5s0), если не тот - выбрать свой. "ОК".
017.jpg

Выбор интерфейса
Далее: "Hosts" -> "Scan for hosts". Ожидаем сканирование хостов.
018.jpg

Сканирование хостов

Далее "Hosts" -> "Hosts list". В списке выбираем IP нашего роутера (у меня 192.168.1.1) и жмем "Add to target 1", затем выбираем IP устройства (у меня 192.168.1.222), затем "Add to target 2".
019.jpg

192.168.1.1 - роутер - target 1; 192.168.1.222 - телефон - target 2

Далее "Mitm" (Man in the Middle) -> "ARP Poisoning" -> ставим флаг "Sniff remote connections" -> "OK".
020.jpg

Далее "Start" -> "Start sniffing".

Конец подготовки: SSLSplit
Далее в терминале ставим sslsplit:
Code:
sudo apt-get -y install sslplit
Когда установка завершена, создаем директории:
Code:
mkdir logs
И в текущей директории (где лежат файлы cert.pem и key.pem)
Code:
cp /dev/null logfile.log
Выходим из аккаунта в приложении на телефоне.

В текущей директории выполняем:
Code:
sudo sslsplit -k key.pem -c cert.pem -l logfile.log -j logs -S . https 0.0.0.0 8443 http 0.0.0.0 8080
Вводим phrase key, который указывали при создании сертификата.

В logfile.log будут записываться неполные логи (именно домен, адрес, порт), в директорию logs будут записываться подробные запросы, заголовки и ответы.

Далее авторизуемся в приложении и видим, как в терминале, в logfile.log и в директории logs появляются данные. Для остановки снифинга жмем в терминале Ctrl+C.

Логи в директории logs будут записываться под владельцем и группой root без доступа к чтению и записи от текущего пользователя. Поэтому нужно изменить владельца. В директории с сертификатами вводим
Code:
 sudo chown -R vlad805:vlad805 logs
Где вместо "vlad805" - имя Вашего пользователя.

Далее можно просматривать файлы с помощью обычного текстового редактора.

Update
Как позже подсказал Антон, снифинг можно выполнить двумя кликами с помощью приложений для Android, и тогда вот эта длиннющая инструкция не понадобится. Но... кому как удобнее.