Finding .onion Sites

Identifying .onion websites can be problematic, especially if they’re “member only” or not posted about on frequently used Internet locations, such as 4Chan or Reddit. Now, there is the Hunchly report which you can subscribe to at http://hunch.ly/darkweb-osint/ but with myself being unsure how that report identifies new .onion sites, I was tinkering with a way to attempt to identify sites myself.

Onion addresses are the first 16 characters of the public key associated with the .onion site, consisting of the lowercase letters a through z and the numbers 2 through 7. Granted, there are some .onion sites that utilize longer addresses but for now these aren’t the norm. Thus, we can create a short Python script to generate random .onion sites we can later lookup.

import random, string

file = open("onions.txt", "w")

times = input("How many .onions do you want to generate? ")

for i in range(times):

  x = ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in range(16))
  y = x + ".onion"
  file.write(y)
  file.write("\n")

file.close()

Now that we have a script that will create .onion sites, we need a simple way to determine if the site is up. Since Tor does not support the ICMP protocol, we can’t simply ping the site. We can use the CURL command, however, and get a HTTP status code that will tell us if the website is up, or is being redirected, or simply doesn’t exist.

To test this we’ll use the New York Times .onion address: https://www.nytimes3xbfgragh.onion/

We can then use the following curl command: curl -o /dev/null -s -w “%{http_code}\n” –socks5-hostname localhost:9050 https://www.nytimes3xbfgragh.onion

The command has the following options:

  • -o to specify an output location (in our case /dev/null because we don’t want to save it)
  • -s to run in silent mode, don’t tell us error messages and the like
  • -w to write information to standard out
  • –socks5-hostname to point to the proxy we’re utilizing for Tor

To break down the command without the -o, -w, or -s options, our results look like this:

And that’s only part of it. So let’s do a curl and re-direct the output to a .txt file: curl –socks5-hostname localhost:9050 https://www.nytimes3xbfgragh.onion > file.txt

Now, we’d think we might be able to grep for “http_code” or something similar from the resulting file, but the status code we’re looking for isn’t stored within there. So yea, the previous step was pretty pointless. What we want is the http response code that is received, which wouldn’t be stored within the .html file itself. That’s why we need the -w option with the -w “%{http_code}\n” More information on this option can be found in the manpage for curl: https://curl.haxx.se/docs/manpage.html

Thus, when we run our code we get this:

A beautiful HTTP status code of 200, which according to this page means we are good to go.

Now, to only combine the script with the curl command…..

Update:

So, putting commands like curl into Python scripts is not ideal, because there are libraries for that, like the Requests library: https://requests.readthedocs.io/en/master/

We’re going to start by writing a new script for now, one that just gets the HTTP status code for .onion sites. We’ll use some .onion sites that we know work, like Facebook and Tor, as well as one we made up to make sure we’re good to go. Let’s start with this code:

import requests

sessions = requests.session()

#Tor uses the 9050 port as the default Socks port
session.proxies = {}
session.proxies['http'] = 'socks5://localhost:9050'
session.proxies['https] = 'socks5://localhost:9050'

r = session.head('http://facebookcorewwwi.onion')

print(r.status_code)

And when run, looks like this:

So we now have some code that will utilize the SOCKS5 proxy to request the HTTP status code from a .onion website, and in this case it returned us 302, which means “Found”. Sweet!

Now, let’s test a “bad” site and see what happens. I’ll use a .onion I made up by mashing the keyboard.

And we get a weird error. Which I’d expect, but I’d like it to be handled more gracefully. So let’s do that with try and except.

And we see in the results above I tried it twice, once with a bad link and once with a good one, and got the results I expected.

Now, we need to start putting everything all together. Ideally, we want our end result to generate a .onion site, see if it’s live, and if it is save those results to a document of some type. In this case, probably a CSV. But first, let’s figure out which HTTP codes we care about.

We can do this with a set in Python. So our set is going to look like this

http_codes = {200, 201, 202, 203, 204, 205, 206, 207, 208, 226,
              300, 301, 302, 303, 304, 305, 306, 307, 308}

Now, there might be a more efficient way to do it, but that’s what I’m starting with. Next, we add an if statement.

if code in http_codes:
  print("True")
  print(code)

And this should tell us if our HTTP code is in a list of codes that are indicative of a website being up. Rock on!

Next, we need to write our results to some kind of file. Let’s use a .csv, so create one called my_generated_list.csv

We’ll use the standard Python practice of opening it up in append mode…

linksfile = open("my_generated_list.csv", "a")

…and then writing the information we need to the file…

linksfile.write("test" + "," + str(code) + "\n"

I used “test” here as a place holder until we fill it with our randomly generated URL. Thus, our finished code looks like this.

Yes, I realize I have some print statements that I don’t need in there right now but I’ll remove them later. And I should probably put some functions in here…but I’ll worry about that later. Or now…

Let’s start putting our random generator in…with a function!

19 thoughts on “Finding .onion Sites”

  1. Здесь вы можете заказать накрутку лайков и фолловеров для социальных сетях , таких как ВК, TikTok, Telegram и прочие.
    Быстрая и безопасная раскрутка профиля гарантирована .
    Купить лайки Ютуб
    Доступные тарифы и качественное предоставление услуг.
    Начните рост популярности уже сейчас !

  2. На данном сайте вы можете приобрести онлайн телефонные номера разных операторов. Эти номера подходят для подтверждения профилей в разных сервисах и приложениях.
    В ассортименте доступны как долговременные, так и одноразовые номера, которые можно использовать чтобы принять сообщений. Это удобное решение если вам не хочет использовать личный номер в интернете.
    номер польши
    Процесс покупки очень простой: определяетесь с подходящий номер, оплачиваете, и он становится готов к использованию. Оцените услугу уже сегодня!

  3. This website specializes in desktop Video Surveillance Software, detailing free solutions for IP camera monitoring. It provides comparisons of various surveillance software and examines AI-powered security advancements, including cost-free object detection features. Reviews of both desktop and mobile applications focus on their usability and key attributes. The recommended software functions as a robust security tool, delivering precise detection capabilities. With IP camera recording and time-lapse support, it is a versatile choice for those seeking CCTV monitoring solutions.

  4. На этом сайте вы можете приобрести онлайн мобильные номера различных операторов. Они могут использоваться для регистрации аккаунтов в различных сервисах и приложениях.
    В каталоге представлены как постоянные, так и временные номера, что можно использовать чтобы принять SMS. Это удобное решение если вам не желает указывать личный номер в сети.
    купить виртуальный номер
    Процесс покупки очень удобный: определяетесь с необходимый номер, вносите оплату, и он будет доступен. Попробуйте сервис прямо сейчас!

  5. На этом сайте АвиаЛавка (AviaLavka) вы можете забронировать дешевые авиабилеты по всему миру.
    Мы подбираем лучшие цены от проверенных перевозчиков.
    Удобный интерфейс поможет быстро найти подходящий рейс.
    https://www.avialavka.ru
    Гибкая система поиска помогает подобрать самые дешевые варианты перелетов.
    Покупайте билеты онлайн без переплат.
    АвиаЛавка — ваш удобный помощник в путешествиях!

  6. На этом сайте вы у вас есть возможность купить лайки и фолловеров для Instagram. Это поможет повысить вашу популярность и заинтересовать больше людей. Мы предлагаем моментальное добавление и надежный сервис. Выбирайте удобный пакет и продвигайте свой аккаунт без лишних усилий.
    Накрутка Инстаграм бесплатно быстро

  7. Я боялся, что навсегда утратил свои биткоины, но специальный сервис помог мне их вернуть.
    Изначально я сомневался, что что-то получится, но простой процесс оказался эффективным.
    Используя уникальному подходу, платформа восстановила утерянные данные.
    Всего за несколько шагов я удалось восстановить свои BTC.
    Этот сервис оказался надежным, и я советую его тем, кто утратил доступ к своим криптоактивам.
    http://mtw2014.tmweb.ru/forum/?PAGE_NAME=message&FID=1&TID=11953&TITLE_SEO=11953-programma-dlya-prosmotra-kamer-videonablyudeniya&MID=564385&result=reply#message564385

  8. Этот сервис помогает накрутить просмотры и подписчиков во ВКонтакте. Вы можете заказать эффективное продвижение, которое поможет росту популярности вашей страницы или группы. Бот для накрутки просмотров в ВК видео Все подписчики реальные, а просмотры добавляются быстро. Доступные цены позволяют выбрать оптимальный вариант для разного бюджета. Оформление услуги занимает минимум времени, а результат виден уже в ближайшее время. Начните продвижение сегодня и сделайте свой профиль популярнее!

  9. На этом ресурсе вы найдете клинику психологического здоровья, которая предоставляет психологические услуги для людей, страдающих от стресса и других ментальных расстройств. Мы предлагаем комплексное лечение для восстановления ментального здоровья. Наши специалисты готовы помочь вам решить проблемы и вернуться к гармонии. Опыт наших врачей подтверждена множеством положительных рекомендаций. Запишитесь с нами уже сегодня, чтобы начать путь к восстановлению.
    http://helenfrankenthalerfoundation.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Fpreparations%2Fk%2Fkorvalol%2F

  10. Здесь вы найдете центр ментального здоровья, которая обеспечивает психологические услуги для людей, страдающих от тревоги и других психологических расстройств. Мы предлагаем комплексное лечение для восстановления психического здоровья. Наши опытные психологи готовы помочь вам справиться с проблемы и вернуться к сбалансированной жизни. Квалификация наших врачей подтверждена множеством положительных отзывов. Обратитесь с нами уже сегодня, чтобы начать путь к лучшей жизни.
    http://jankelawgroup.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Fpreparations%2Fz%2Fzopiklon%2F

  11. Здесь вы найдете клинику ментального здоровья, которая предоставляет профессиональную помощь для людей, страдающих от тревоги и других психических расстройств. Эта эффективные методы для восстановления ментального здоровья. Наши специалисты готовы помочь вам решить трудности и вернуться к психологическому благополучию. Квалификация наших психологов подтверждена множеством положительных рекомендаций. Свяжитесь с нами уже сегодня, чтобы начать путь к лучшей жизни.
    http://liafrazzini.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Fpreparations%2Fo%2Folanzapin%2F

  12. На данной платформе вы найдете центр ментального здоровья, которая предлагает профессиональную помощь для людей, страдающих от стресса и других психических расстройств. Эта комплексное лечение для восстановления психического здоровья. Наши опытные психологи готовы помочь вам решить трудности и вернуться к психологическому благополучию. Опыт наших специалистов подтверждена множеством положительных отзывов. Запишитесь с нами уже сегодня, чтобы начать путь к лучшей жизни.
    http://littlebooproductionsclub.org/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Fpreparations%2Fm%2Fmelatonin%2F

  13. VectorJet is dedicated to coordinating exclusive aviation services, collective flights, and freight charters.
    They deliver bespoke solutions for VIP jet journeys, air taxis, helicopter charters, and freight delivery, including priority and relief missions.
    The company offers flexible travel options with individually tailored aircraft recommendations, 24/7 assistance, and help with unique requests, such as pet-friendly flights or remote destination access.
    Complementary services cover aircraft leasing, brokerage, and private jet management.
    VectorJet serves as an intermediary between travelers and third-party operators, ensuring luxury, convenience, and speed.
    Their mission is to bring business jet travel effortless, safe, and personally designed for each client.
    vector-jet.com

  14. Предоставляем услуги проката автобусов и микроавтобусов с водителем корпоративным клиентам, бизнеса любого масштаба, а также для частных клиентов.
    Пассажирские перевозки в Челябинске
    Обеспечиваем приятную и спокойную транспортировку для групп людей, предлагая перевозки на свадебные мероприятия, корпоративные праздники, туристические поездки и любые события в регионе Челябинска.

  15. Luxury timepieces have long been a gold standard in horology. Meticulously designed by world-class artisans, they combine heritage with innovation.
    All elements demonstrate exceptional attention to detail, from precision-engineered calibers to high-end finishes.
    Wearing a horological masterpiece is not just about telling time. It represents refined taste and exceptional durability.
    Be it a minimalist aesthetic, Swiss watches provide unparalleled reliability that never goes out of style.
    https://archboston.com/community/threads/watches-query.7227/

  16. We offer a comprehensive collection of trusted pharmaceutical products for various needs.
    Our online pharmacy provides quick and secure order processing to your location.
    Each medication is sourced from licensed manufacturers so you get safety and quality.
    Feel free to search through our catalog and place your order hassle-free.
    Got any concerns? Pharmacy experts will guide you at any time.
    Prioritize your well-being with our trusted online pharmacy!
    https://www.linkcentre.com/review/shailoo.gov.kg/kg/vybory-oktyabr-2020_/plan-improving-health-elderly-population-disease-prevention/

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

  18. Обзор BlackSprut: ключевые особенности
    Сервис BlackSprut вызывает обсуждения широкой аудитории. Но что это такое?
    Этот проект предлагает интересные возможности для своих пользователей. Интерфейс платформы отличается простотой, что делает его доступной без сложного обучения.
    Стоит учитывать, что данная система имеет свои особенности, которые делают его особенным на рынке.
    Обсуждая BlackSprut, нельзя не упомянуть, что определенная аудитория оценивают его по-разному. Многие выделяют его удобство, а кто-то оценивают его неоднозначно.
    Подводя итоги, BlackSprut остается темой дискуссий и вызывает заинтересованность широкой аудитории.
    Ищете рабочее зеркало БлэкСпрут?
    Если ищете актуальный домен BlackSprut, то вы по адресу.
    bs2best at
    Периодически ресурс меняет адрес, поэтому нужно знать новое зеркало.
    Мы следим за актуальными доменами чтобы предоставить новым зеркалом.
    Проверьте актуальную ссылку прямо сейчас!

  19. Мы занимается помощью иностранных граждан в северной столице.
    Оказываем содействие в подготовке документов, временной регистрации, и вопросах, для официального трудоустройства.
    Наша команда консультируют по всем юридическим вопросам и дают советы правильный порядок действий.
    Мы работаем как с временным пребыванием, и в вопросах натурализации.
    С нами, процесс адаптации станет проще, упростить оформление документов и спокойно жить в северной столице.
    Обращайтесь, чтобы узнать больше!
    https://spb-migrant.ru/

Leave a Reply

Your email address will not be published. Required fields are marked *