Ciberinteligencia y cibercrimen: ¿Bots o código?

En el ámbito de la ciberinteligencia y la lucha contra el cibercrimen, es fundamental reconocer la importancia y el riesgo inherente al manejo de la información en el ciberespacio. Esta premisa puede resumirse en una adaptación de dos citas célebres: “La información es poder”, atribuida a Francis Bacon, y “El poder corrompe”, de Lord Acton. De esta manera, podríamos postular que 

La información es poder. El poder corrompe. La ciberinteligencia es la corrupción absoluta.

Este enunciado subraya la dualidad de la ciberinteligencia: por un lado, es una herramienta poderosa para combatir el cibercrimen; por otro lado, si se maneja incorrectamente, puede llevar a abusos de poder. En este contexto, se hace evidente la necesidad de establecer marcos normativos y éticos sólidos para regular el uso y la gestión de la información en el ciberespacio.

Introducción

El ciberespacio se ha convertido en un escenario clave para la seguridad y el desarrollo de las sociedades actuales. En él se desarrollan actividades económicas, sociales, políticas y culturales que generan una gran cantidad de datos e información. Sin embargo, también es un espacio donde se producen amenazas y ataques que pueden afectar a la privacidad, la integridad y la disponibilidad de los datos, los sistemas y las infraestructuras.

Ante este contexto, surge la necesidad de aplicar técnicas y herramientas de ciberinteligencia para anticiparse, prevenir y responder a las amenazas y los ataques del ciberespacio. La ciberinteligencia se puede definir como el proceso de obtención, análisis y difusión de información relevante sobre el ciberespacio para apoyar la toma de decisiones estratégicas, operativas o tácticas. La ciberinteligencia se basa en el uso de fuentes abiertas (OSINT), cerradas (CSINT) o humanas (HUMINT) para recabar información sobre las capacidades, intenciones y actividades de los actores maliciosos o potencialmente hostiles.

Uno de los ámbitos donde la ciberinteligencia tiene una especial relevancia es el del cibercrimen, que se puede definir como el conjunto de actividades ilícitas que se realizan en el ciberespacio mediante el uso de las tecnologías de la información y la comunicación (TIC). El cibercrimen abarca una gran variedad de delitos, como el fraude, el robo de identidad, el espionaje, el sabotaje, el terrorismo o la extorsión, entre otros muchos. El cibercrimen supone un grave riesgo para la seguridad nacional e internacional, así como para los derechos y libertades de los ciudadanos.

En este sentido, recientemente se ha publicado en Twitter un hilo que leí, releí y analicé con toda la objetividad que me es posible. El hilo fue escrito por un usuario que se presenta como instructor y ‘OSINT Lover’, entre otras cosas, y que explica algunos métodos y técnicas para obtener información sobre los usuarios de Telegram usando bots y otras aplicaciones y servicios online de terceros.

Llevo un tiempo planteándome si publicar este artículo, o no No conozco personalmente al usuario que ha publicado el hilo. Por ese mismo motivo, por respeto, finalmente he decidido publicar este artículo de un modo crítico-constructivo. Quiero dejar claro que no soy ningún experto en OSINT ni en el campo de la ciberinteligencia, Quienes me conocen saben que sólo soy alguien curioso.

Sobre Telegram

Telegram fue creada por los hermanos Nikolái y Pável Durov, dos emprendedores rusos que también fundaron la red social VK. Telegram se caracteriza por ser más rápido, tener mayor capacidad y ofrecer más funciones que otras plataformas como WhatsApp. Entre estas funciones se encuentran la posibilidad de crear y gestionar comunidades públicas o privadas (grupos, supergrupos, canales…), enviar mensajes cifrados, usar bots para automatizar tareas o acceder a la API para desarrollar aplicaciones propias.

Telegram es una fuente abierta de información muy valiosa para los investigadores que se dedican al OSINT (Open Source Intelligence) o a la ciberinteligencia. Estos investigadores usan técnicas y herramientas para recopilar, analizar y difundir información obtenida a partir de fuentes accesibles al público. Algunas de estas fuentes son las redes sociales, los buscadores web, los medios de comunicación o las bases de datos públicas.

Sin embargo, investigar en Telegram no es tan fácil como parece. Telegram tiene un alto nivel de privacidad y seguridad, lo que dificulta el acceso a los datos y metadatos de los usuarios. Además, Telegram tiene una gran variedad de usuarios, comunidades y contenidos, lo que requiere un conocimiento profundo y actualizado de la plataforma y sus características.

El objetivo de este artículo es hacer un análisis del hilo de Twitter y comentar sus puntos fuertes y débiles. También quiero mostraros una alternativa más eficaz y segura al uso de bots y servicios online de terceros para obtener información sobre los usuarios de Telegram: usar un script de Python3 que he desarrollado para hacer todo lo que dice el usuario del hilo, pero sin el empleo de bots ni servicios online externos.

Análisis del hilo de Twitter

El hilo de Twitter proporcionado por el usuario se enfoca en estrategias para llevar a cabo investigaciones en la plataforma de mensajería Telegram, con un énfasis en la extracción de información sobre usuarios. A primera vista, el hilo pretende ofrecer consejos útiles para aquellos interesados en la ciberinteligencia y la recopilación de datos en línea. Sin embargo, un análisis más detenido revela varias imprecisiones y omisiones que deben ser abordadas con un enfoque crítico y constructivo.

  1. Origen de Telegram y su Seguridad: El autor destaca el origen ruso de los fundadores de Telegram, pero omite mencionar que la empresa está registrada en Londres y tiene su sede en Dubai, y que sus servidores están ubicados en varios países para garantizar la seguridad y la privacidad de los datos de los usuarios. Además, se ignora el hecho de que WhatsApp también ha implementado cifrado de extremo a extremo por defecto, lo que podría dar lugar a una comparación inexacta entre ambas plataformas.

  2. Velocidad de Telegram vs WhatsApp: El autor del hilo afirma que Telegram es más rápido que WhatsApp. Sin embargo, la velocidad de entrega de los mensajes en ambas plataformas puede variar dependiendo de varios factores, como la calidad de la conexión a Internet, la ubicación del servidor y la carga del servidor en un momento dado.

    Es importante tener en cuenta que tanto Telegram como WhatsApp son plataformas de mensajería instantánea eficientes y ambas se esfuerzan por entregar mensajes lo más rápido posible. La diferencia en la velocidad de entrega entre las dos plataformas puede no ser significativa para la mayoría de los usuarios en situaciones normales.

    Además, aunque Telegram puede permitir una mayor capacidad en términos de tamaño de archivo para compartir, esto no necesariamente se traduce en una mayor velocidad en la entrega de mensajes. En última instancia, la elección entre Telegram y WhatsApp puede depender más de las características individuales y las preferencias personales que de la velocidad de entrega de los mensajes. Por lo tanto, es importante considerar todos estos factores al evaluar la eficacia de estas plataformas para la investigación en línea.

  3. Uso de Sock Puppets: El uso de cuentas sock puppets es una práctica discutible desde el punto de vista ético y legal. Si bien el autor recomienda esta estrategia, no menciona las implicaciones éticas y legales que pueden surgir al crear cuentas falsas para llevar a cabo investigaciones. Es importante destacar que el uso de cuentas falsas puede ser considerado como una violación de los términos de servicio de las plataformas en línea y podría resultar en acciones legales. Además, hay que tener en cuenta que detrás de una cuenta sock puppet siempre existirá una persona física y, las personas, estamos condenadas a cometer todo tipo de errores.

    Como dijo Theodore Roosevelt: “El único hombre que no comete errores es el hombre que nunca hace nada”.

    Este hecho subraya la inevitabilidad del error humano en la ciberinteligencia, incluso cuando se utilizan técnicas sofisticadas como las cuentas sock puppets.

    Por otro lado, el autor da por hecho que toda la información estará siempre en abierto y disponible, pero eso no es la vida real. Eso es aplicable a las pruebas de concepto, pero no a los casos reales. En la vida real, en muchísimas ocasiones, y dependiendo del nivel de configuración de privacidad del usuario, no es posible obtener ningún dato. El autor intenta captar la atención de su audiencia con un tono humorístico y desenfadado. Me parece bien que se expliquen métodos de obtención de información y técnicas en un tono humorístico, pero añadiría que la ciberinteligencia no es ningún juego y está en juego mucho más que los datos, que no es poco.

  4. Dependencia de Bots de Terceros: El autor promueve el uso de bots de terceros para extraer información de usuarios en Telegram. Sin embargo, no se aborda adecuadamente el riesgo de seguridad asociado con el uso de estos bots. Los bots de terceros pueden ser controlados por actores maliciosos y podrían recopilar información confidencial o ser utilizados para actividades fraudulentas. Además, no se proporciona orientación sobre cómo verificar la autenticidad y la seguridad de los bots antes de usarlos. Por otro lado, los bots no siempre funcionan correctamente, ya que dependen de una base de datos que puede no estar actualizada con la frecuencia debida. El autor comete una imprecisión al presentar los bots como una solución infalible para rastrear el alias actual de un usuario, sin advertir sobre las posibles fallas o limitaciones del bot.

  5. Extracción de ID y Alias: Si bien el autor menciona la extracción de IDs y alias de usuarios, no aborda la necesidad de tener el número de teléfono del usuario objetivo en la lista de contactos para realizar estas acciones. Esto es un punto crítico, ya que no siempre se puede acceder a esta información y, por lo tanto, estas técnicas pueden ser limitadas en su aplicabilidad. Además, el autor no explica cómo obtener el alias de un usuario si no se conoce su ID o su alias anterior.

  6. Privacidad y Configuración de Usuarios: El autor asume que es posible acceder a información personal detallada de los usuarios, como nombres, apellidos, última vez conectados y más, sin abordar las configuraciones de privacidad de los usuarios. Muchos usuarios de Telegram eligen configurar su perfil para mantener su información personal privada, lo que limitaría la efectividad de las técnicas mencionadas.

  7. Manipulación de Metadatos: La afirmación sobre la manipulación de metadatos en Telegram es inexacta. Telegram no almacena metadatos en los archivos enviados o recibidos como se describe en el hilo, lo que podría dar lugar a malentendidos sobre la capacidad para rastrear información. En realidad, Telegram elimina los metadatos de los archivos si se envían con compresión (vía rápida), y los mantiene si se envían sin compresión. Además, el nombre del archivo que se cambia a la fecha de subida no corresponde a los metadatos, sino a una conversión interna de Telegram.

  8. Servicios de Terceros para Buscar Usuarios en Otras Redes Sociales: El autor menciona servicios de terceros para buscar usuarios en otras redes sociales a partir de su alias. Sin embargo, vuelve a caer en el mismo error de depender de plataformas externas que pueden comprometer la seguridad y la fiabilidad de la investigación. Existen otros métodos de código abierto para hacer esto, como OSRFramework o Sherlock, por mencionar un par de ejemplos, que permiten controlar y verificar el código fuente y la información que se maneja.

  9. Mensajes Reenviados: El autor sugiere usar un bot para extraer metadatos de los mensajes reenviados en Telegram. Sin embargo, esta técnica es innecesaria y complicada, ya que cada mensaje tiene una URL que contiene toda esa información y que se puede acceder fácilmente desde el navegador o desde la terminal.

  10. Conversión del Timestamp: El autor propone usar CyberChef para convertir el timestamp de Unix en formato legible. Sin embargo, esta acción se puede realizar con un simple comando en la terminal (date -u -d @1694239422), sin necesidad de usar una herramienta externa que podría ralentizar o dificultar el proceso.

  11. Bots de Telegram: Los bots de Telegram no son chats automatizados, sino que son aplicaciones de terceros que se ejecutan en servidores externos y se comunican con los usuarios a través de la API de Telegram. Los bots no pueden iniciar conversaciones con los usuarios, sino que deben ser iniciados primero. El autor comete un error al describir los bots como chats automatizados, lo que podría dar una impresión equivocada sobre el funcionamiento o las capacidades de los bots.

El hilo proporciona algunas recomendaciones útiles para investigar en Telegram, pero presenta inexactitudes y omisiones significativas que deben ser abordadas. Es esencial considerar los aspectos éticos y legales al realizar cualquier investigación en la Red y ser consciente del riesgo asociado con el uso de herramientas externas como los bots. Más adelante, se explorará una alternativa más sólida y segura para la recopilación de datos en Telegram a través de un código Python.

Bots de Telegram: Implicaciones y riesgos

Los bots de Telegram son aplicaciones de terceros que se ejecutan en servidores externos y se comunican con los usuarios a través de la API de Telegram. Los bots pueden realizar una amplia variedad de tareas, desde enviar mensajes automáticos y responder a consultas, hasta recopilar información sobre los usuarios y sus interacciones.

Aunque los bots pueden ser herramientas útiles para la investigación en línea, también presentan riesgos e implicaciones significativas que deben ser considerados antes de usarlos. A continuación, se describen algunos de estos factores:
  • Seguridad y privacidad: Los bots son controlados por terceros, lo que significa que no se puede garantizar su seguridad o privacidad. Los bots pueden ser controlados por actores maliciosos que podrían recopilar información confidencial o pueden ser empleados para actividades fraudulentas. Por ejemplo, un bot podría solicitar el número de teléfono o el código de verificación del usuario para acceder a su cuenta de Telegram. También podría enviar mensajes falsos o maliciosos a otros usuarios o grupos. Para evitar estos riesgos, se recomienda verificar la autenticidad y la fiabilidad de los bots antes de usarlos, así como revisar los permisos que se les otorgan.

  • Ética y legalidad: El uso de bots para recopilar información sobre los usuarios sin su consentimiento podría considerarse una violación de la privacidad. En muchos países, esto podría ser ilegal y podría resultar en acciones legales contra el usuario. Además, el uso de bots podría implicar una falta de transparencia y de rigor en la investigación, ya que no se puede verificar la calidad o la procedencia de la información que se obtiene. Para evitar estas implicaciones, se recomienda respetar los principios éticos y legales al realizar cualquier investigación en línea, así como citar las fuentes y los métodos que se utilizan.

  • Alimentación de bases de datos de terceros: Los bots pueden suelen ser utilizados para alimentar las bases de datos de terceros con la información que los propios usuarios proporcionamos. Esto significa que la información que los usuarios proporcionan a los bots podría ser utilizada para otros fines sin su conocimiento o consentimiento. Por ejemplo, un bot podría recopilar el ID, el alias, el nombre, el apellido, la foto o la biografía del usuario y almacenarlos en una base de datos externa, para servir esos datos posteriormente a otros. También podría rastrear el historial de nombres y aliases del usuario o sus interacciones con otros usuarios o grupos. Para evitar esta situación, se recomienda ser cauteloso con la información que se proporciona a los bots y revisar su política de privacidad, si es que alguno la tiene.

Aunque los bots pueden ser herramientas útiles para la investigación, también presentan riesgos e implicaciones significativas que deben ser considerados antes de usarlos. Es esencial considerar estos factores al decidir si utilizar bots para una investigación y tomar medidas para minimizar los riesgos asociados con su uso. En la siguiente sección, se explorará una alternativa más sólida y segura para la recopilación de datos en Telegram a través de un script en Python.

Script de Python (TgUserDetails.py)

El script de Python, denominado TgUserDetails.py, es una herramienta de ciberinteligencia diseñada para obtener información detallada sobre los usuarios de Telegram, así como de canales y grupos públicos. Esta herramienta es una alternativa más segura y eficaz que los bots y que otras aplicaciones externas mencionados en el hilo de Twitter.


Captura de pantalla que muestra las opciones de la aplicación TgUserDetails

La aplicación puede obtener y procesar información basándose con diferentes argumentos, incluyendo el nombre de usuario, la ID del usuario, el número de teléfono o la URL de un mensaje enviado por el usuario en un canal o grupo público.

Para realizar la demostración de las funcionalidades de esta herramienta he decidido emplear una cuenta que uso para hacer algunas pruebas.


Captura de pantalla del perfil empleado para las pruebas.

A continuación se expone un resumen de lo que hace la aplicación con cada parámetro:

  • Nombre de usuario (-u): La aplicación puede obtener información detallada sobre un usuario, o un canal o grupo públicos, a partir de su nombre de usuario. Esto incluye el ID del usuario, su nombre y apellido, su biografía, su última vez en línea y su foto de perfil. La aplicación también puede descargar todas las fotos de perfil históricas del usuario.

    Por ejemplo, si se ejecuta el comando python3 TgUserDetails.py -u solouncurioso, se obtiene la siguiente salida:


Captura de pantalla que muestra los resultados de búsqueda mediante el nombre de usuario

Como se puede observar, la aplicación muestra el ID, el nombre, el apellido, la biografía, la última vez en línea y el nombre de usuario del usuario con el nombre de usuario @solouncurioso. También descarga la foto de perfil actual del usuario en el archivo 5176153752.jpg y todas las fotos de perfil anteriores en archivos con el formato YYYY_MM_DD_HH:MM:SS.jpg.

  • ID del usuario (-i):Similar al parámetro del nombre de usuario, la aplicación puede obtener información detallada sobre un usuario a partir de su ID. Sin embargo, este parámetro solo funciona con usuarios que están en la lista de contactos del investigador.

    Por ejemplo, si se ejecuta el comando python3 TgUserDetails.py -i 5176153752, se obtiene la siguiente salida:


Captura de pantalla que muestra los resultados de búsqueda mediante el ID del usuario

Si se dispone del contacto del usuario guardado en la lista de contactos (o de una base de datos propia) y se ejecuta el comando python3 TgUserDetails.py -i 5176153752, se obtiene la siguiente salida:


Captura de pantalla que muestra los resultados de búsqueda mediante el ID del usuario

Como se puede observar, la aplicación muestra la misma información que con el parámetro -u, pero a partir del ID del usuario. En este caso, se trata del mismo usuario que antes (@solouncurioso), pero podría ser cualquier otro que esté en la lista de contactos.

  • Número de teléfono (-p): La aplicación puede obtener información detallada sobre un usuario a partir de su número de teléfono. Esto incluye el ID del usuario, su nombre y apellido actuales de la cuenta, su biografía, su última vez en línea y su foto de perfil. La aplicación también puede descargar todas las fotos de perfil del usuario.

    Por ejemplo, si se ejecuta el comando python3 TgUserDetails.py -p +34XXXXXXXXX, se obtiene la siguiente salida:


Captura de pantalla que muestra los resultados de búsqueda mediante el número de teléfono


Captura de pantalla que muestra los resultados de búsqueda mediante el número de teléfono

Como se puede observar, la aplicación muestra el ID, el nombre y apellido actuales, la biografía, la última vez en línea y el nombre de usuario (si tiene) del usuario con el número de teléfono +34XXXXXXXXX. También descarga las fotos de perfil del usuario como antes.

Se expone una explicación de los resultados de la ejecución del script TgUserDetails.py:
  • Sin el número de teléfono añadido en la lista de contactos:

    • La aplicación puede obtener información sobre el usuario con el nombre de usuario @solouncurioso, incluyendo su ID, su nombre, su apellido, su biografía, su última vez en línea y su foto de perfil. También puede descargar todas las fotos de perfil que el usuario ha tenido en el pasado. Esto demuestra que la aplicación es capaz de recopilar información valiosa sobre los usuarios a partir de su nombre de usuario, que es un dato público y fácil de obtener.

    • Sin embargo, cuando se intenta obtener información sobre el mismo usuario utilizando su ID (5176153752), la aplicación no puede encontrar al usuario. Esto se debe a que el parámetro -i solo funciona con usuarios que están en la lista de contactos del investigador. Esto implica que la aplicación tiene una limitación para obtener información sobre los usuarios a partir de su ID, que es un dato más difícil de obtener y más específico que el nombre de usuario.

  • Con el número de teléfono añadido en la lista de contactos:

    • La aplicación puede obtener información sobre el usuario con el nombre de usuario @solouncurioso, incluyendo su ID, su nombre y apellido en el registro de su cuenta, su biografía, su última vez en línea y su foto de perfil. También puede descargar las mismas fotos de perfil que antes. Esto demuestra que la aplicación puede acceder a la misma información que con el parámetro -u, pero utilizando el ID del usuario como argumento.

    • Además, cuando se utiliza el número de teléfono del usuario (+34XXXXXXXXX) para obtener información sobre él, la aplicación puede encontrar al usuario y obtener información detallada sobre él. También puede descargar las mismas fotos de perfil que antes. Esto demuestra que la aplicación puede acceder a la misma información que con los parámetros -u e -i, pero utilizando el número de teléfono del usuario como argumento.

    • Además, la aplicación muestra el nombre y apellido actuales del usuario. En este caso, se puede observar que el usuario está empleando actualmente el nombre ‘MC’.

Los resultados muestran que TgUserDetails.py es capaz de obtener una gran cantidad de información sobre los usuarios de Telegram utilizando diferentes parámetros. Sin embargo, es importante tener en cuenta que algunos parámetros solo funcionan bajo ciertas condiciones, como tener el número de teléfono del usuario en la lista de contactos del investigador. Por lo tanto, se recomienda utilizar el parámetro más adecuado según cada caso y verificar la fiabilidad y actualidad de la información obtenida.


Captura de pantalla que muestra las imágenes del usuario investigado

La aplicación también es capaz de procesar entidades de tipo grupo y canales, que sean públicos:

  • Grupo público:

    • La aplicación puede obtener información sobre el grupo con el nombre de usuario forense. Esto incluye su ID, que es un identificador único para el grupo en Telegram.

    • También obtiene el título del grupo, que es el nombre que los miembros del grupo ven.

    • La aplicación puede determinar el número de administradores en el grupo, lo que puede ser útil para entender el tamaño y la actividad del grupo.

    • La fecha de creación del grupo también se obtiene, lo que puede proporcionar contexto sobre cuándo se formó el grupo.

    • Por último, la aplicación puede descargar la foto de perfil del grupo. Esto podría ser útil para la identificación visual del grupo.


Captura de pantalla que muestra los resultados de un grupo

  • Canal público:

    • La aplicación puede obtener información sobre el canal con el nombre de usuario nclgc. Al igual que con el grupo, esto incluye su ID y título.

    • Además, la aplicación puede obtener el nombre de usuario del canal. A diferencia de los grupos, los canales en Telegram pueden tener nombres de usuario, lo que permite a las personas encontrar y unirse al canal más fácilmente.

    • La descripción del canal también se obtiene. Esto puede proporcionar información valiosa sobre el propósito y el contenido del canal.

    • Al igual que con el grupo, la fecha de creación del canal y la foto de perfil también se obtiene.


Captura de pantalla que muestra los resultados de un canal


Captura de pantalla que muestra las imágenes del canal y del grupo analizados

  • URL del mensaje (-l):La aplicación puede obtener información detallada sobre un mensaje enviado por un usuario en un canal o grupo público a partir de la URL del mensaje. Esto incluye el contenido del mensaje, la fecha y hora en que se envió el mensaje, y la información sobre el remitente del mensaje.

    A modo de ejemplo, vamos a ejecutar el comando python3 TgUserDetails.py -l https://t.me/cybdetective/2084

Para poder entender y visualizar mejor este parámetro se realiza una comparación con uno de los bots que recomienda el autor del hilo.


Captura de pantalla que muestra el resultado del procesamiento de un mensaje

Bot VS Código

  • Bot:

{
  "update_id": 144343788,
  "message": {
    "message_id": 997479,
    "from": {
      "id": 773730237,
      "is_bot": false,
      "first_name": "Marcos",
      "username": "n4rr34n6",
      "language_code": "en"
    },
    "chat": {
      "id": 773730237,
      "first_name": "Marcos",
      "username": "n4rr34n6",
      "type": "private"
    },
    "date": 1694370362,
    "text": "https://t.me/cybdetective/2084",
    "entities": [
      {
        "offset": 0,
        "length": 30,
        "type": "url"
      }
    ]
  }
}

El resultado del bot proporciona información sobre un mensaje enviado por el usuario “Marcos” con el nombre de usuario “n4rr34n6”. El mensaje contiene una URL “https://t.me/cybdetective/2084”, que es un enlace a un mensaje en Telegram. La información proporcionada incluye la ID del mensaje, la ID del usuario que envió el mensaje, el nombre de usuario y el nombre del remitente, y la fecha en que se envió el mensaje. Sin embargo, no proporciona detalles sobre el contenido del mensaje o información adicional sobre el remitente

  • Código:

marcos@n4rr34n6:/mnt/c/Tools/Telegram$ python3 TgUserDetails.py -l https://t.me/cybdetective/2084
{
  "_": "Message",
  "id": 2084,
  "peer_id": {
    "_": "PeerChannel",
    "channel_id": 1597138777
  },
  "date": "2023-09-07 13:11:55 (UTC)",
  "message": "After 4 months of procrastination, I finally wrote an article on Medium about gathering info about usernames:\n- basics tools for nickname enumeration\n- search URLs with nickname \n- using ip search engines (Shodan, Netlas) for nickname info gathering\n\nhttps://medium.com/@cyb_detective/when-you-need-search-by-nickname-in-public-ip-addresses-search-engines-shodan-netlas-fofa-etc-59d92af047cc",
  "out": false,
  "mentioned": false,
  "media_unread": false,
  "silent": false,
  "post": true,
  "from_scheduled": false,
  "legacy": false,
  "edit_hide": false,
  "pinned": true,
  "noforwards": false,
  "from_id": null,
  "fwd_from": null,
  "via_bot_id": null,
  "reply_to": null,
  "media": {
    "_": "MessageMediaPhoto",
    "spoiler": false,
    "photo": {
      "_": "Photo",
      "id": 5463183621985783244,
      "access_hash": -5254244289959019902,
      "file_reference": "025f3267590000082464fe0a79c033c95f3c10321a116acca2f87eb3fd",
      "date": "2023-09-07 13:15:33 (UTC)",
      "sizes": [
        {
          "_": "PhotoStrippedSize",
          "type": "i",
          "bytes": "011828d3132336d0c33e9835211c546b022bee0bcfae6a43d31402b8638e3ad22eecf23f5a70e0520
eb400a3345206068a007546d1ab32365b2a73c13451400ec71c0a36e4107b8a28a00a2ba5a2b86f31
b8edc51451401f"
        },
        {
          "_": "PhotoSize",
          "type": "m",
          "w": 320,
          "h": 193,
          "size": 16081
        },
        {
          "_": "PhotoSize",
          "type": "x",
          "w": 800,
          "h": 482,
          "size": 78000
        },
        {
          "_": "PhotoSizeProgressive",
          "type": "y",
          "w": 1280,
          "h": 771,
          "sizes": [
            9751,
            29504,
            63011,
            95605,
            152405
          ]
        }
      ],
      "dc_id": 2,
      "has_stickers": false,
      "video_sizes": []
    },
    "ttl_seconds": null
  },
  "reply_markup": null,
  "entities": [
    {
      "_": "MessageEntityUrl",
      "offset": 251,
      "length": 140
    }
  ],
  "views": 1827,
  "forwards": 50,
  "replies": {
    "_": "MessageReplies",
    "replies": 1,
    "replies_pts": 3681,
    "comments": true,
    "recent_repliers": [
      {
        "_": "PeerUser",
        "user_id": 2020659139
      }
    ],
    "channel_id": 1639662393,
    "max_id": 1880,
    "read_max_id": 1879
  },
  "edit_date": "2023-09-07 13:15:33 (UTC)",
  "post_author": null,
  "grouped_id": null,
  "reactions": {
    "_": "MessageReactions",
    "results": [
      {
        "_": "ReactionCount",
        "reaction": {
          "_": "ReactionEmoji",
          "emoticon": "\ud83d\udc4d"
        },
        "count": 27,
        "chosen_order": null
      }
    ],
    "min": false,
    "can_see_list": false,
    "recent_reactions": []
  },
  "restriction_reason": [],
  "ttl_period": null
}
marcos@n4rr34n6:/mnt/c/Tools/Telegram$

El parámetro -l permite obtener información sobre un mensaje enviado por un usuario en un canal o grupo público a partir de la URL del mensaje. Para usar este parámetro, se debe pasar la URL como argumento al script TgUserDetails.py. Por ejemplo, python3 TgUserDetails.py -l https://t.me/cybdetective/2084.

El resultado de la aplicación es un JSON, que es un formato de datos que consiste en pares de clave-valor. Cada clave representa un tipo de información y cada valor representa el dato correspondiente. Por ejemplo, la clave “message” representa el contenido del mensaje y el valor “After 4 months of procrastination, I finally wrote an article on Medium about gathering info about usernames:\n- basics tools for nickname enumeration\n- search URLs with nickname \n- using ip search engines (Shodan, Netlas) for nickname info gathering\n\nhttps://medium.com/@cyb_detective/when-you-need-search-by-nickname-in-public-ip-addresses-search-engines-shodan-netlas-fofa-etc-59d92af047cc” representa el texto que el usuario escribió en el mensaje.

De esta forma, el JSON proporciona información detallada y completa sobre el mensaje y su remitente, así como sobre el canal o grupo donde se envió el mensaje. Esto incluye, a modo de ejemplo con algunas claves:

  • ID del mensaje: El ID del mensaje es 2084. Este es un identificador único para el mensaje en Telegram. Con este ID, se puede acceder al mensaje directamente desde la aplicación de Telegram o desde la web.

  • Fecha del mensaje: El mensaje fue enviado el 7 de septiembre de 2023 a las 13:11:55 UTC. Esta es la fecha y hora en que el usuario publicó el mensaje en el canal o grupo. Con esta información, se puede conocer cuándo se produjo el mensaje y si coincide con algún evento o situación relevante.

  • Contenido del mensaje: El contenido del mensaje es un texto que habla sobre un artículo que el autor escribió en Medium acerca de la recopilación de información sobre nombres de usuario. El mensaje incluye un enlace al artículo. Con esta información, se puede analizar el tema y el propósito del mensaje, así como acceder al contenido del artículo para obtener más información.

  • Vistas y reenvíos: El mensaje ha sido visto 1827 veces y reenviado 50 veces. Estos datos indican el nivel de interés y difusión que ha generado el mensaje entre los usuarios de Telegram. Con esta información, se puede estimar la popularidad y la influencia del autor del mensaje.

  • Reacciones: El mensaje ha recibido 27 reacciones con el emoticono “👍”. Estos datos indican el nivel de aprobación y apoyo que ha recibido el mensaje por parte de los usuarios de Telegram. Con esta información, se puede evaluar la opinión y la actitud de los usuarios hacia el autor y el contenido del mensaje.

  • Respuestas: El mensaje ha recibido una respuesta. Esta es una forma de interacción entre los usuarios de Telegram que permite comentar o debatir sobre el contenido del mensaje. Con esta información, se puede acceder a la respuesta y ver qué dice y quién la escribió. Y, no menos importante, el ID del usuario que efectuó la réplica.

  • Media: El mensaje incluye una foto, y la aplicación ha descargado esta foto junto con otras fotos asociadas al mensaje. Estas fotos pueden ser útiles para identificar visualmente al autor o al canal o grupo donde se envió el mensaje, así como para complementar o ilustrar el contenido del mensaje.
El resultado de la aplicación proporciona información más detallada y completa que el resultado del bot, que solo proporciona información básica sobre el mensaje y sobre el propio usuario que utiliza el bot, como el ID del mensaje, el ID del usuario, el nombre de usuario, el nombre y el idioma del remitente, y la fecha en que se envió el mensaje. Sin embargo, no proporciona detalles sobre el contenido del mensaje o información adicional sobre el remitente o el canal o grupo.

Al comparar los resultados obtenidos del bot y de la aplicación TgUserDetails.py, se pueden observar varias diferencias clave:
  • Información del usuario: El bot proporciona información básica sobre el usuario que envió el mensaje, incluyendo su ID, si es un bot o no, su nombre, su nombre de usuario y el código de idioma. Por otro lado, la aplicación TgUserDetails.py no proporciona información directa sobre el usuario que envió el mensaje.

  • Información del mensaje: Ambos, el bot y la aplicación TgUserDetails.py, proporcionan la ID del mensaje y la fecha en que se envió. Sin embargo, la aplicación TgUserDetails.py proporciona información adicional sobre el mensaje, incluyendo el contenido del mensaje y las entidades presentes en él (como las URL).

  • Información adicional: La aplicación TgUserDetails.py proporciona mucha más información adicional en comparación con el bot. Esto incluye el número de vistas y reenvíos del mensaje, las reacciones al mensaje, las respuestas al mensaje y los medios asociados al mensaje (como las fotos). El bot no proporciona ninguna de esta información.

  • Formato de los resultados: Los resultados del bot se presentan en un formato más simple y menos detallado en comparación con los resultados de la aplicación TgUserDetails.py. Los resultados de la aplicación TgUserDetails.py se presentan en un formato JSON detallado que proporciona una visión completa de la información disponible sobre el mensaje.
Aunque ambos, el bot y la aplicación TgUserDetails.py, pueden proporcionar información útil sobre un mensaje específico en Telegram, la aplicación TgUserDetails.py proporciona una cantidad mucho mayor de detalles y es por lo tanto una herramienta más fiable para la ciberinteligencia y la recopilación de datos en Telegram.

El bot y la aplicación TgUserDetails.py son dos herramientas que permiten obtener información sobre un mensaje específico enviado en Telegram utilizando el parámetro -l y la URL del mensaje. Sin embargo, hay varias diferencias clave entre las dos herramientas en cuanto a la cantidad, la calidad y el formato de la información que proporcionan, así como los riesgos y las implicaciones de emplearlas.
  • Cantidad de información: La aplicación TgUserDetails.py proporciona mucha más información que el bot sobre el mensaje y su remitente, así como sobre el canal o grupo donde se envió el mensaje. El bot solo proporciona información básica sobre el mensaje y su remitente, como el ID del mensaje, el ID del usuario, el nombre de usuario, el nombre y el idioma del remitente, y la fecha en que se envió el mensaje. La aplicación TgUserDetails.py proporciona información adicional sobre el mensaje, incluyendo el contenido del mensaje, las entidades presentes en él (como las URL), el número de vistas y reenvíos del mensaje, las reacciones al mensaje, las respuestas al mensaje y los medios asociados al mensaje (como las fotos). Además, la aplicación TgUserDetails.py proporciona información sobre el remitente del mensaje, como su ID, su nombre, su apellido, su biografía, su última vez en línea y su foto de perfil. También proporciona información sobre el canal o grupo donde se envió el mensaje, como su ID, su título, su nombre de usuario y su descripción.

  • Calidad de la información: La aplicación TgUserDetails.py proporciona información más detallada y completa que el bot sobre el mensaje y su remitente, así como sobre el canal o grupo donde se envió el mensaje. El bot proporciona información genérica y superficial que puede ser insuficiente o inexacta para los fines de la ciberinteligencia y la recopilación de datos. La aplicación TgUserDetails.py proporciona información específica y profunda que puede ser útil y relevante para los investigadores que deseen obtener una visión detallada de un mensaje específico.

  • Formato de la información: La aplicación TgUserDetails.py proporciona información en un formato JSON detallado que proporciona una visión completa de la información disponible sobre el mensaje. El JSON es un formato de datos común y fácil de procesar que consiste en pares de clave-valor. Cada clave representa un tipo de información y cada valor representa el dato correspondiente. El bot proporciona información en un formato más simple y menos detallado que puede ser difícil de interpretar o analizar.

  • Riesgos e implicaciones: La aplicación TgUserDetails.py es una herramienta segura y eficaz que no compromete la seguridad o la privacidad del investigador ni del usuario objetivo. La aplicación se ejecuta localmente en el ordenador del investigador y no requiere ningún permiso o autorización especial para acceder a la información pública disponible en Telegram. El bot, por otro lado, es una herramienta potencialmente peligrosa e ineficiente que puede comprometer la seguridad o la privacidad del investigador o del usuario objetivo. Al usar el bot, el investigador debe enviarle al bot la URL del mensaje que desea analizar. Esto implica que el bot recibe y almacena la información del investigador, como su ID, su nombre de usuario, su nombre y su idioma. Además, el bot puede acceder al contenido del mensaje y a cualquier dato asociado al mismo. Esto implica que el bot recibe y almacena la información del usuario objetivo, como su ID, su nombre de usuario, su nombre y su idioma. Estos datos pueden ser usados por el bot para fines maliciosos o ilegales, como rastrear, espiar o extorsionar al investigador o al usuario objetivo. Además, el bot puede ser vulnerable a ataques informáticos que pongan en riesgo la integridad o la confidencialidad de los datos almacenados por el bot.

Aunque ambos, el bot y la aplicación TgUserDetails.py, pueden proporcionar información útil sobre un mensaje específico en Telegram, la aplicación TgUserDetails.py proporciona una cantidad mucho mayor de detalles y es por lo tanto una herramienta más eficaz para la ciberinteligencia y la recopilación de datos en Telegram. Además, la aplicación TgUserDetails.py es una herramienta más segura y fiable que no compromete la seguridad o la privacidad del investigador ni del usuario objetivo, a diferencia del bot, que puede suponer un riesgo o una amenaza para ambos. Por lo tanto, se recomienda utilizar la aplicación TgUserDetails.py en lugar del bot para obtener información sobre los mensajes enviados en Telegram.

Con todo esto, ha quedado demostrado que el código permite a los investigadores obtener información valiosa sobre los usuarios de Telegram sin comprometer la seguridad o la privacidad empleando bots o servicios de terceros. Además, la aplicación es fácil de usar y ofrece una salida clara y completa.

Conclusión

El análisis del hilo de Twitter ha revelado varias inexactitudes y omisiones que podrían llevar a malentendidos o a una interpretación incorrecta de las capacidades de las herramientas y técnicas mencionadas para la recopilación de datos en Telegram. El uso de bots y aplicaciones externas para recopilar información plantea preocupaciones legítimas sobre la seguridad y la privacidad.
Esto subraya la importancia de utilizar herramientas que permitan un control completo sobre el proceso de recopilación de datos y minimicen los riesgos asociados con la dependencia de servicios externos.

La aplicación TgUserDetails.py presentada en este artículo parece ser una alternativa más segura y eficaz para la recopilación de datos en Telegram. Proporciona una cantidad significativamente mayor de información en comparación con los bots, incluyendo detalles adicionales como el contenido del mensaje, las entidades presentes en él (como las URL), el número de vistas y reenvíos del mensaje, las reacciones al mensaje, las respuestas al mensaje y los medios asociados al mensaje (como las fotos). Además, la aplicación TgUserDetails.py proporciona información sobre el remitente del mensaje, como su ID, su nombre, su apellido, su biografía, su última vez en línea y su foto de perfil.

Es importante destacar que todas estas herramientas deben utilizarse de manera ética y respetando la privacidad y los derechos de los usuarios. La ciberinteligencia es un campo de enorme responsabilidad con un gran potencial para ayudar en la lucha contra el cibercrimen, pero también tiene la peculiaridad de ser mal utilizado. Por lo tanto, es crucial que los investigadores sean conscientes de los riesgos asociados con el uso de estas herramientas y tomen medidas para minimizar estos riesgos.

Finalmente, este análisis subraya la importancia de la precisión y la integridad en la comunicación de información técnica. Las inexactitudes y omisiones pueden llevar a malentendidos o a una interpretación incorrecta de las capacidades de las herramientas y técnicas. Por lo tanto, es crucial que los investigadores se esfuercen por proporcionar información precisa y completa en sus comunicaciones.

En el análisis del hilo de Twitter, es notable que el usuario utiliza la plataforma como un medio para autopromocionarse. Si bien la autopromoción no es inherentemente negativa, y de hecho es una práctica común en las redes sociales, la forma en que se maneja puede tener un impacto significativo en la percepción del contenido.

En este caso, el usuario parece estar promocionando sus cursos y su conocimiento sobre OSINT y Telegram. Esto podría interpretarse como un intento de establecer su credibilidad y atraer a más seguidores o clientes potenciales. Sin embargo, también podría verse como una distracción del contenido principal del hilo.

La autopromoción se realiza de manera bastante prominente, lo que podría restar valor al contenido educativo e informativo del hilo. En lugar de integrarse de manera sutil y orgánica, la promoción de los cursos y habilidades del usuario se presenta de manera bastante directa.

La ciberinteligencia y la lucha contra el cibercrimen son campos vastos y en constante evolución. A medida que avanzamos en nuestra comprensión y desarrollo de nuevas estrategias y tecnologías, debemos recordar que no podemos explicar o controlar toda la naturaleza de estos desafíos por nosotros mismos.

Como bien dice la expresión: ‘Para explicar toda la naturaleza, no basta ni un hombre ni una edad completa. En su lugar, lo mejor es que el hombre busque un poco de verdad y certeza, dejando el resto para los demás, para los que vendrán, con conjeturas y sin dar nada por hecho’.

Esta reflexión nos recuerda la importancia de la colaboración, la humildad y la paciencia en nuestra lucha continua contra el cibercrimen. Cada pequeño avance que hacemos contribuye a un cuerpo más grande de conocimiento que será aprovechado por las futuras generaciones de profesionales de la ciberseguridad.

PD: El código de la herramienta que he usado para obtener información sobre los usuarios de Telegram está disponible en mi sitio de Github.


Marcos

spacer

Cyberintelligence and Cybercrime: Bots or Code?

In the realm of cyberintelligence and the fight against cybercrime, it is crucial to recognize the importance and inherent risk in handling information in cyberspace. This premise can be summarized by adapting two famous quotes: "Information is power," attributed to Francis Bacon, and "Power corrupts," by Lord Acton. In this way, we could posit that

"Information is power. Power corrupts. Cyberintelligence is absolute corruption."

This statement underscores the duality of cyberintelligence: on one hand, it is a powerful tool to combat cybercrime, but on the other hand, if mishandled, it can lead to abuses of power. In this context, the need for establishing strong normative and ethical frameworks to regulate the use and management of information in cyberspace becomes evident.

Introduction

Cyberspace has become a critical stage for the security and development of contemporary societies. It is where economic, social, political, and cultural activities take place, generating a wealth of data and information. However, it is also a space where threats and attacks that can impact data, systems, and infrastructures' privacy, integrity, and availability occur.

In this context, there is a need to employ cyberintelligence techniques and tools to anticipate, prevent, and respond to cyber threats and attacks. Cyberintelligence can be defined as the process of obtaining, analyzing, and disseminating relevant information about cyberspace to support strategic, operational, or tactical decision-making. It relies on the use of open sources (OSINT), closed sources (CSINT), or human sources (HUMINT) to gather information about the capabilities, intentions, and activities of malicious or potentially hostile actors.

One area where cyberintelligence is particularly relevant is in the realm of cybercrime, which can be defined as a set of unlawful activities carried out in cyberspace using information and communication technologies (ICT). Cybercrime encompasses a wide range of offenses, including fraud, identity theft, espionage, sabotage, terrorism, and extortion, among many others. Cybercrime poses a significant risk to national and international security, as well as the rights and freedoms of citizens.

In this regard, a thread was recently published on Twitter that I read, reread, and analyzed as objectively as possible. The thread was written by a user who identifies as an instructor and an 'OSINT Lover,' among other things, and it explains some methods and techniques for obtaining information about Telegram users using bots and other third-party online applications and services.

I have been considering whether to publish this article or not for some time. I do not personally know the user who posted the thread. For that reason, out of respect, I have ultimately decided to publish this article in a critical-constructive manner. I want to make it clear that I am not an expert in OSINT or the field of cyberintelligence. Those who know me are aware that I am just a curious individual.

About Telegram

Telegram was created by the brothers Nikolai and Pavel Durov, two Russian entrepreneurs who also founded the social network VK. Telegram is known for being faster, having greater capacity, and offering more features than other platforms like WhatsApp. Among these features are the ability to create and manage public or private communities (groups, supergroups, channels...), send encrypted messages, use bots to automate tasks, or access the API to develop custom applications.

Telegram is an open source and valuable source of information for researchers dedicated to OSINT (Open Source Intelligence) or cyber intelligence. These researchers use techniques and tools to gather, analyze, and disseminate information obtained from publicly accessible sources. Some of these sources include social networks, web search engines, media outlets, or public databases.

However, conducting research on Telegram is not as easy as it may seem. Telegram has a high level of privacy and security, which makes accessing user data and metadata challenging. Additionally, Telegram has a wide range of users, communities, and content, which requires a deep and up-to-date understanding of the platform and its features.

The goal of this article is to analyze the Twitter thread and discuss its strengths and weaknesses. I also want to introduce a more effective and secure alternative to using third-party bots and online services to obtain information about Telegram users: using a Python3 script that I have developed to perform all the tasks mentioned in the Twitter thread, but without relying on external bots or online services.

Twitter Thread Analysis

The Twitter thread provided by the user focuses on strategies for conducting investigations on the Telegram messaging platform, with an emphasis on extracting information about users. At first glance, the thread aims to offer helpful tips for those interested in cyberintelligence and online data collection. However, a closer analysis reveals several inaccuracies and omissions that need to be addressed with a critical and constructive approach.

  1. Telegram's Origin and Security: The author highlights the Russian origin of Telegram's founders but fails to mention that the company is registered in London, headquartered in Dubai, and its servers are located in various countries to ensure the security and privacy of user data. Furthermore, the fact that WhatsApp has also implemented default end-to-end encryption is ignored, which could lead to an inaccurate comparison between the two platforms.

  2. Telegram vs. WhatsApp Speed: The thread author claims that Telegram is faster than WhatsApp. However, message delivery speed on both platforms can vary depending on various factors, such as the quality of the internet connection, server location, and server load at any given moment.

    It is important to note that both Telegram and WhatsApp are efficient instant messaging platforms, and both strive to deliver messages as quickly as possible. The difference in message delivery speed between the two platforms may not be significant for most users in normal situations.

    Furthermore, while Telegram may allow for larger file sizes to be shared, this does not necessarily translate to faster message delivery. Ultimately, the choice between Telegram and WhatsApp may depend more on individual features and personal preferences than message delivery speed. Therefore, it is important to consider all these factors when evaluating the effectiveness of these platforms for online research.

  3. Use of Sock Puppets: The use of sock puppet accounts is a questionable practice from an ethical and legal standpoint. While the author recommends this strategy, they do not mention the ethical and legal implications that can arise when creating fake accounts for research purposes. It is important to highlight that the use of fake accounts can be considered a violation of online platform terms of service and could result in legal actions. Additionally, it should be noted that behind a sock puppet account, there is always a real person, and people are prone to making all sorts of mistakes.

    As Theodore Roosevelt once said, "The only man who never makes a mistake is the man who never does anything."

    This underscores the inevitability of human error in cyberintelligence, even when sophisticated techniques like sock puppet accounts are used.

    On the other hand, the author assumes that all information will always be open and available, but that is not real life. This applies to proof of concept but not to real cases. In real life, on many occasions and depending on the user's privacy settings, it may not be possible to obtain any data. The author attempts to capture the audience's attention with a humorous and light-hearted tone. It's fine to explain information-gathering methods and techniques in a humorous tone, but it should be added that cyberintelligence is no game, and much more than data is at stake.

  4. Dependence on Third-Party Bots: The author promotes the use of third-party bots to extract information from Telegram users. However, the security risks associated with using these bots are not adequately addressed. Third-party bots can be controlled by malicious actors and may collect confidential information or be used for fraudulent activities. Furthermore, the author does not provide guidance on how to verify the authenticity and security of bots before using them. Additionally, bots do not always work correctly as they depend on a database that may not be updated frequently enough. The author makes an inaccuracy by presenting bots as an infallible solution for tracking a user's current alias without warning about potential failures or limitations of the bot.

  5. Extraction of IDs and Aliases: While the author mentions the extraction of user IDs and aliases, they do not address the need to have the target user's phone number in the contact list to perform these actions. This is a critical point, as access to this information is not always possible, and therefore, these techniques may be limited in their applicability. Furthermore, the author does not explain how to obtain a user's alias if their ID or previous alias is unknown.

  6. User Privacy and Settings: The author assumes that it is possible to access detailed personal information of users, such as names, last seen timestamps, and more, without addressing user privacy settings. Many Telegram users choose to configure their profiles to keep their personal information private, which would limit the effectiveness of the mentioned techniques.

  7. Metadata Manipulation: The claim about metadata manipulation in Telegram is inaccurate. Telegram does not store metadata in sent or received files as described in the thread, which could lead to misunderstandings about the ability to track information. In reality, Telegram removes metadata from files if they are sent with compression (via fast method) and retains it if sent without compression. Additionally, the filename being changed to the upload date does not correspond to metadata but is an internal conversion by Telegram.

  8. Third-Party Services for Finding Users on Other Social Networks: The author mentions third-party services to find users on other social networks based on their alias. However, they again fall into the same error of relying on external platforms that can compromise the security and reliability of the investigation. There are open-source methods for doing this, such as OSRFramework or Sherlock, to name a couple of examples, which allow for control and verification of source code and information being handled.

  9. Forwarded Messages: The author suggests using a bot to extract metadata from forwarded messages in Telegram. However, this technique is unnecessary and complicated, as each message has a URL that contains all that information and can be easily accessed from the browser or terminal.

  10. Timestamp Conversion: The author proposes using CyberChef to convert Unix timestamps into a readable format. However, this action can be performed with a simple command in the terminal (date -u -d @1694239422) without the need for an external tool that could slow down or complicate the process.

  11. Telegram Bots: Telegram bots are not automated chats but are third-party applications that run on external servers and communicate with users through the Telegram API. Bots cannot initiate conversations with users but must be initiated first. The author makes an error in describing bots as automated chats, which could give a mistaken impression of how bots work or their capabilities.

The thread provides some useful recommendations for researching on Telegram but presents significant inaccuracies and omissions that need to be addressed. It is essential to consider ethical and legal aspects when conducting any research on the Internet and to be aware of the risks associated with the use of external tools such as bots. Later on, a more robust and secure alternative for data collection on Telegram through Python code will be explored.

Telegram Bots: Implications and Risks

Telegram bots are third-party applications that run on external servers and communicate with users through the Telegram API. Bots can perform a wide variety of tasks, from sending automated messages and responding to queries to collecting information about users and their interactions.

While bots can be useful tools for online research, they also pose significant risks and implications that should be considered before using them. Below are some of these factors:
  • Security and Privacy: Bots are controlled by third parties, which means their security or privacy cannot be guaranteed. Bots can be controlled by malicious actors who might collect confidential information or be used for fraudulent activities. For instance, a bot could request the user's phone number or verification code to gain access to their Telegram account. It could also send fake or malicious messages to other users or groups. To mitigate these risks, it is recommended to verify the authenticity and reliability of bots before using them, as well as review the permissions granted to them.

  • Ethics and Legality: Using bots to collect information about users without their consent could be considered a violation of privacy. In many countries, this could be illegal and lead to legal actions against the user. Additionally, using bots could involve a lack of transparency and rigor in research, as the quality and source of the obtained information cannot be verified. To avoid these implications, it is recommended to adhere to ethical and legal principles when conducting online research, as well as cite sources and methods used.

  • Feeding Third-Party Databases: Bots are often used to feed third-party databases with the information users provide. This means that the information users give to bots could be used for other purposes without their knowledge or consent. For example, a bot could collect the user's ID, alias, name, surname, photo, or biography and store them in an external database to serve that data to others later. It could also track the user's name and alias history or their interactions with other users or groups. To avoid this situation, it is recommended to be cautious about the information provided to bots and review their privacy policy, if any.

While bots can be useful tools for research, they also come with risks and significant implications that should be considered before using them. It is essential to take these factors into account when deciding whether to use bots for research and take steps to minimize the associated risks. In the following section, a more robust and secure alternative for data collection in Telegram through a Python script will be explored.

Python Script (TgUserDetails.py)

The Python script, named TgUserDetails.py, is a cyberintelligence tool designed to gather detailed information about Telegram users, as well as public channels and groups. This tool is a safer and more effective alternative to the bots and other external applications mentioned in the Twitter thread.


Screenshot showing the options of the TgUserDetails application

The application can retrieve and process information based on various parameters, including the username, user ID, phone number, or the URL of a message sent by the user in a public channel or group.

To demonstrate the functionality of this tool, I have chosen to use an account that I use for conducting some tests.


Screenshot of the employee profile used for testing.

Below is a summary of what the application does with each parameter:

  • Username (-u): The application can obtain detailed information about a user, or a public channel or group, based on their username. This includes the user's ID, their first and last name, their biography, their last online status, and their profile picture. The application can also download all historical profile pictures of the user.

    For example, if you run the command python3 TgUserDetails.py -u solouncurioso, you get the following output:


Screenshot showing search results by username

As can be seen, the application displays the ID, first name, last name, biography, last online time, and username of the user with the username @solouncurioso. It also downloads the current profile picture of the user into the file 5176153752.jpg and all previous profile pictures into files with the format YYYY_MM_DD_HH:MM:SS.jpg.

  • User ID (-i):Similar to the username parameter, the application can retrieve detailed information about a user based on their ID. However, this parameter only works with users who are in the investigator's contact list.

    For example, if you run the command python3 TgUserDetails.py -i 5176153752, you will get the following output:


Screenshot displaying search results using the user ID

If you have the user's contact saved in the contact list (or in your own database) and you run the command python3 TgUserDetails.py -i 5176153752, you will get the following output:


Screenshot displaying search results using the user ID

As can be observed, the application displays the same information as with the "-u" parameter, but based on the user's ID. In this case, it is the same user as before (@solouncurioso), but it could be any other user in the contact list.

  • Phone number (-p): The application can retrieve detailed information about a user based on their phone number. This includes the user's ID, their current account name and last name, their bio, their last online status, and their profile picture. The application can also download all of the user's profile pictures.

For example, if you run the command "python3 TgUserDetails.py -p +34XXXXXXXXX," you will get the following output:


Screenshot displaying search results using the phone number


Screenshot displaying search results using the phone number

As can be observed, the application displays the current ID, first name, last name, biography, last seen timestamp, and username (if available) of the user with the phone number +34XXXXXXXXX. It also downloads the user's profile pictures as before.

An explanation of the results of running the TgUserDetails.py script is provided below:
  • Without the phone number added to the contact list:

    • The application was able to retrieve information about the user with the username @solouncurioso, including their ID, first name, last name, biography, last online status, and profile picture. It could also download all the profile pictures the user has had in the past. This demonstrates that the application is capable of collecting valuable information about users based on their username, which is public and easy to obtain.

    • However, when attempting to obtain information about the same user using their ID (5176153752), the application could not locate the user. This is because the -i parameter only works with users who are in the researcher's contact list. This implies that the application has a limitation in obtaining information about users based on their ID, which is harder to obtain and more specific than the username.

  • With the phone number added to the contact list:

    • The application was able to retrieve information about the user with the username @solouncurioso, including their ID, first name and last name in their account record, biography, last online status, and profile picture. It could also download the same profile pictures as before. This demonstrates that the application can access the same information as with the -u parameter but using the user's ID as an argument.

    • Additionally, when the user's phone number (+34XXXXXXXXX) was used to obtain information about them, the application could locate the user and retrieve detailed information about them. It could also download the same profile pictures as before. This shows that the application can access the same information as with the -u and -i parameters but using the user's phone number as an argument.

    • Furthermore, the application displayed the user's current first name and last name. In this case, it can be observed that the user is currently using the name 'MC'.

The results show that TgUserDetails.py is capable of gathering a significant amount of information about Telegram users using different parameters. However, it's important to note that some parameters only work under specific conditions, such as having the user's phone number in the researcher's contact list. Therefore, it is recommended to use the most appropriate parameter for each case and verify the reliability and timeliness of the information obtained.


Screenshot displaying images of the investigated user

The application is also capable of processing group and channel entities that are public:

  • Public Group:

    • The application can fetch information about the group using the forensic username. This includes its ID, which is a unique identifier for the group on Telegram.

    • It also retrieves the group's title, which is the name visible to group members.

    • The application can determine the number of administrators in the group, which can be useful for understanding the group's size and activity.

    • The group's creation date is also obtained, providing context about when the group was formed.

    • Lastly, the application can download the group's profile picture. This could be useful for visual identification of the group.


Screenshot showing the results of a group

  • Public Channel:

    • The application can retrieve information about the channel with the username "nclgc." Just like with groups, this includes its ID and title.

    • Additionally, the application can obtain the channel's username. Unlike groups, Telegram channels can have usernames, making it easier for people to find and join the channel.

    • The channel's description is also obtained. This can provide valuable information about the channel's purpose and content.

    • Similar to groups, the channel's creation date and profile picture are also retrieved.


Screenshot displaying the results of a channel


Screenshot displaying the images from the channel and group analyzed

  • Message URL (-l): The application can retrieve detailed information about a message sent by a user in a public channel or group using the message URL. This includes the message content, the date and time the message was sent, and information about the message sender.

    As an example, we will run the command python3 TgUserDetails.py -l https://t.me/cybdetective/2084.

To better understand and visualize this parameter, a comparison is made with one of the bots recommended by the thread author.


Screenshot displaying the result of processing a message

Bot VS Code

  • Bot:

{
  "update_id": 144343788,
  "message": {
    "message_id": 997479,
    "from": {
      "id": 773730237,
      "is_bot": false,
      "first_name": "Marcos",
      "username": "n4rr34n6",
      "language_code": "en"
    },
    "chat": {
      "id": 773730237,
      "first_name": "Marcos",
      "username": "n4rr34n6",
      "type": "private"
    },
    "date": 1694370362,
    "text": "https://t.me/cybdetective/2084",
    "entities": [
      {
        "offset": 0,
        "length": 30,
        "type": "url"
      }
    ]
  }
}

The bot's result provides information about a message sent by the user "Marcos" with the username "n4rr34n6". The message contains a URL "https://t.me/cybdetective/2084", which is a link to a message on Telegram. The provided information includes the message ID, the user ID who sent the message, the username and sender's name, and the date when the message was sent. However, it does not provide details about the message content or additional information about the sender.

  • Code:

marcos@n4rr34n6:/mnt/c/Tools/Telegram$ python3 TgUserDetails.py -l https://t.me/cybdetective/2084
{
  "_": "Message",
  "id": 2084,
  "peer_id": {
    "_": "PeerChannel",
    "channel_id": 1597138777
  },
  "date": "2023-09-07 13:11:55 (UTC)",
  "message": "After 4 months of procrastination, I finally wrote an article on Medium about gathering info about usernames:\n- basics tools for nickname enumeration\n- search URLs with nickname \n- using ip search engines (Shodan, Netlas) for nickname info gathering\n\nhttps://medium.com/@cyb_detective/when-you-need-search-by-nickname-in-public-ip-addresses-search-engines-shodan-netlas-fofa-etc-59d92af047cc",
  "out": false,
  "mentioned": false,
  "media_unread": false,
  "silent": false,
  "post": true,
  "from_scheduled": false,
  "legacy": false,
  "edit_hide": false,
  "pinned": true,
  "noforwards": false,
  "from_id": null,
  "fwd_from": null,
  "via_bot_id": null,
  "reply_to": null,
  "media": {
    "_": "MessageMediaPhoto",
    "spoiler": false,
    "photo": {
      "_": "Photo",
      "id": 5463183621985783244,
      "access_hash": -5254244289959019902,
      "file_reference": "025f3267590000082464fe0a79c033c95f3c10321a116acca2f87eb3fd",
      "date": "2023-09-07 13:15:33 (UTC)",
      "sizes": [
        {
          "_": "PhotoStrippedSize",
          "type": "i",
          "bytes": "011828d3132336d0c33e9835211c546b022bee0bcfae6a43d31402b8638e3ad22eecf23f5a70e0520
eb400a3345206068a007546d1ab32365b2a73c13451400ec71c0a36e4107b8a28a00a2ba5a2b86f31
b8edc51451401f"
        },
        {
          "_": "PhotoSize",
          "type": "m",
          "w": 320,
          "h": 193,
          "size": 16081
        },
        {
          "_": "PhotoSize",
          "type": "x",
          "w": 800,
          "h": 482,
          "size": 78000
        },
        {
          "_": "PhotoSizeProgressive",
          "type": "y",
          "w": 1280,
          "h": 771,
          "sizes": [
            9751,
            29504,
            63011,
            95605,
            152405
          ]
        }
      ],
      "dc_id": 2,
      "has_stickers": false,
      "video_sizes": []
    },
    "ttl_seconds": null
  },
  "reply_markup": null,
  "entities": [
    {
      "_": "MessageEntityUrl",
      "offset": 251,
      "length": 140
    }
  ],
  "views": 1827,
  "forwards": 50,
  "replies": {
    "_": "MessageReplies",
    "replies": 1,
    "replies_pts": 3681,
    "comments": true,
    "recent_repliers": [
      {
        "_": "PeerUser",
        "user_id": 2020659139
      }
    ],
    "channel_id": 1639662393,
    "max_id": 1880,
    "read_max_id": 1879
  },
  "edit_date": "2023-09-07 13:15:33 (UTC)",
  "post_author": null,
  "grouped_id": null,
  "reactions": {
    "_": "MessageReactions",
    "results": [
      {
        "_": "ReactionCount",
        "reaction": {
          "_": "ReactionEmoji",
          "emoticon": "\ud83d\udc4d"
        },
        "count": 27,
        "chosen_order": null
      }
    ],
    "min": false,
    "can_see_list": false,
    "recent_reactions": []
  },
  "restriction_reason": [],
  "ttl_period": null
}
marcos@n4rr34n6:/mnt/c/Tools/Telegram$

The parameter -l allows obtaining information about a message sent by a user in a public channel or group based on the message's URL. To use this parameter, you must pass the URL as an argument to the TgUserDetails.py script. For example, python3 TgUserDetails.py -l https://t.me/cybdetective/2084.

The result of the application is a JSON, which is a data format consisting of key-value pairs. Each key represents a type of information, and each value represents the corresponding data. For example, the key "message" represents the message's content, and the value "After 4 months of procrastination, I finally wrote an article on Medium about gathering info about usernames:\n- basics tools for nickname enumeration\n- search URLs with nickname \n- using ip search engines (Shodan, Netlas) for nickname info gathering\n\nhttps://medium.com/@cyb_detective/when-you-need-search-by-nickname-in-public-ip-addresses-search-engines-shodan-netlas-fofa-etc-59d92af047cc" represents the text the user wrote in the message.

In this way, the JSON provides detailed and comprehensive information about the message and its sender, as well as the channel or group where the message was sent. This includes:

  • Message ID: The message ID is 2084. This is a unique identifier for the message on Telegram. With this ID, you can access the message directly from the Telegram app or the web.

  • Message Date: The message was sent on September 7, 2023, at 13:11:55 UTC. This is the date and time when the user posted the message in the channel or group. With this information, you can know when the message occurred and if it coincides with any relevant event or situation.

  • Message Content: The message's content is text that discusses an article the author wrote on Medium about collecting information about usernames. The message includes a link to the article. With this information, you can analyze the message's topic and purpose, as well as access the article's content for more information.

  • Views and Forwards: The message has been viewed 1827 times and forwarded 50 times. These data indicate the level of interest and dissemination the message has generated among Telegram users. With this information, you can estimate the message author's popularity and influence.

  • Reactions: The message has received 27 reactions with the "👍" emoji. These data indicate the level of approval and support the message has received from Telegram users. With this information, you can assess users' opinion and attitude toward the author and message content.

  • Replies: The message has received one reply. This is a form of interaction among Telegram users that allows commenting or discussing the message's content. With this information, you can access the reply and see what it says and who wrote it. And, not least, the ID of the user who made the replica.

  • Media: The message includes a photo, and the application has downloaded this photo along with other photos associated with the message. These photos can be useful for visually identifying the author or the channel or group where the message was sent, as well as complementing or illustrating the message's content.

The application's result provides more detailed and comprehensive information than the bot's result, which only provides basic information about the message and the user who uses the bot, such as the message ID, user ID, username, name, and language of the sender, and the date the message was sent. However, it does not provide details about the message's content or additional information about the sender or the channel or group.

When comparing the results obtained from the bot and the TgUserDetails.py application, several key differences can be observed:

  • User Information: The bot provides basic information about the user who sent the message, including their ID, whether they are a bot or not, their name, username, and language code. On the other hand, the TgUserDetails.py application does not provide direct information about the user who sent the message.

  • Message Information: Both the bot and the TgUserDetails.py application provide the message ID and the date it was sent. However, the TgUserDetails.py application provides additional information about the message, including the message's content and the entities present in it (such as URLs).

  • Additional Information: The TgUserDetails.py application provides much more additional information compared to the bot. This includes the number of views and forwards of the message, reactions to the message, replies to the message, and media associated with the message (such as photos). The bot does not provide any of this information.

  • Result Format: The bot's results are presented in a simpler and less detailed format compared to the results of the TgUserDetails.py application. The results of the TgUserDetails.py application are presented in a detailed JSON format that provides a complete view of the available information about the message.

While both the bot and the TgUserDetails.py application can provide useful information about a specific message on Telegram, the TgUserDetails.py application provides a much greater amount of detail and is therefore a more reliable tool for cyber intelligence and data collection on Telegram.

The bot and the TgUserDetails.py application are two tools that allow obtaining information about a specific message sent on Telegram using the -l parameter and the message URL. However, there are several key differences between the two tools in terms of the quantity, quality, and format of the information they provide, as well as the risks and implications of using them.

  • Quantity of Information: The TgUserDetails.py application provides much more information than the bot about the message and its sender, as well as the channel or group where the message was sent. The bot only provides basic information about the message and its sender, such as the message ID, user ID, username, name, and language of the sender, and the date the message was sent. The TgUserDetails.py application provides additional information about the message, including the message's content, entities present in it (such as URLs), the number of views and forwards of the message, reactions to the message, replies to the message, and media associated with the message (such as photos). Additionally, the TgUserDetails.py application provides information about the message sender, such as their ID, name, last name, biography, last online time, and profile picture. It also provides information about the channel or group where the message was sent, such as its ID, title, username, and description.

  • Quality of Information: The TgUserDetails.py application provides more detailed and comprehensive information than the bot about the message and its sender, as well as the channel or group where the message was sent. The bot provides generic and superficial information that may be insufficient or inaccurate for the purposes of cyber intelligence and data collection. The TgUserDetails.py application provides specific and in-depth information that can be useful and relevant for researchers who want a detailed view of a specific message.

  • Information Format: The TgUserDetails.py application provides information in a detailed JSON format that provides a complete view of the available information about the message. JSON is a common and easy-to-process data format consisting of key-value pairs. Each key represents a type of information, and each value represents the corresponding data. The bot provides information in a simpler and less detailed format that may be difficult to interpret or analyze.

  • Risks and Implications: The TgUserDetails.py application is a secure and effective tool that does not compromise the researcher's or the target user's security or privacy. The application runs locally on the researcher's computer and does not require any special permissions or authorization to access publicly available information on Telegram. The bot, on the other hand, is a potentially dangerous and inefficient tool that can compromise the researcher's or the target user's security or privacy. When using the bot, the researcher must send the message URL they want to analyze to the bot. This implies that the bot receives and stores the researcher's information, such as their ID, username, name, and language. Additionally, the bot can access the message's content and any associated data. This implies that the bot receives and stores the target user's information, such as their ID, username, name, and language. This data can be used by the bot for malicious or illegal purposes, such as tracking, spying, or extorting the researcher or the target user. Furthermore, the bot may be vulnerable to cyberattacks that could compromise the integrity or confidentiality of the data stored by the bot.
While both the bot and the TgUserDetails.py application can provide useful information about a specific message on Telegram, the TgUserDetails.py application provides a much greater amount of detail and is therefore a more effective tool for cyber intelligence and data collection on Telegram. Additionally, the TgUserDetails.py application is a safer and more reliable tool that does not compromise the security or privacy of the researcher or the target user, unlike the bot, which can pose a risk or threat to both. Therefore, it is recommended to use the TgUserDetails.py application instead of the bot to obtain information about messages sent on Telegram.

With all of this, it has been demonstrated that the code allows researchers to obtain valuable information about Telegram users without compromising security or privacy by using bots or third-party services. Additionally, the application is easy to use and provides a clear and comprehensive output.

Conclusion

The analysis of the Twitter thread has revealed several inaccuracies and omissions that could lead to misunderstandings or an incorrect interpretation of the capabilities of the mentioned tools and techniques for data collection on Telegram. The use of bots and external applications to gather information raises legitimate concerns about security and privacy.

This underscores the importance of using tools that allow for complete control over the data collection process and minimize the risks associated with relying on external services.

This underscores the importance of using tools that allow for complete control over the data collection process and minimize the risks associated with relying on external services.

The TgUserDetails.py application presented in this article appears to be a safer and more effective alternative for data collection on Telegram. It provides significantly more information compared to bots, including additional details such as message content, entities within it (such as URLs), the number of views and message forwards, reactions to the message, responses to the message, and media associated with the message (such as photos). Furthermore, the TgUserDetails.py application provides information about the message sender, such as their ID, name, surname, biography, last online status, and profile picture.

It's important to emphasize that all these tools should be used ethically, respecting the privacy and rights of users. Cyberintelligence is a field of immense responsibility with great potential to aid in the fight against cybercrime, but it also has the peculiarity of being misused. Therefore, it is crucial for researchers to be aware of the risks associated with the use of these tools and take steps to minimize these risks.

Finally, this analysis underscores the importance of accuracy and integrity in the communication of technical information. Inaccuracies and omissions can lead to misunderstandings or an incorrect interpretation of the capabilities of tools and techniques. Therefore, it is crucial for researchers to strive to provide accurate and complete information in their communications.

In the analysis of the Twitter thread, it is notable that the user uses the platform as a means of self-promotion. While self-promotion is not inherently negative and is, in fact, a common practice on social media, the way it is handled can have a significant impact on the perception of the content.

In this case, the user seems to be promoting their courses and their knowledge of OSINT and Telegram. This could be interpreted as an attempt to establish their credibility and attract more followers or potential clients. However, it could also be seen as a distraction from the main content of the thread.

Self-promotion is done quite prominently, which could detract from the educational and informative content of the thread. Instead of integrating subtly and organically, the promotion of the user's courses and skills is presented quite directly.

Cyberintelligence and the fight against cybercrime are vast and ever-evolving fields. As we advance in our understanding and development of new strategies and technologies, we must remember that we cannot explain or control the full nature of these challenges on our own.

As the saying goes: "To explain the full nature, neither one person nor one complete age is enough. Instead, it is best for man to seek a bit of truth and certainty, leaving the rest to others, to those who will come, with conjectures and without taking anything for granted."

This reflection reminds us of the importance of collaboration, humility, and patience in our ongoing fight against cybercrime. Every small step we take contributes to a larger body of knowledge that will be leveraged by future generations of cybersecurity professionals.

P.S.: The code for the tool I used to gather information about Telegram users is available on my GitHub site.


Marcos

spacer