- HackWare.ru
- Этичный хакинг и тестирование на проникновение, информационная безопасность
- Tor: от азов до продвинутого уровня (ч. 11): Настройка скрытого сервиса Tor в Debian (Kali Linux, Linux Mint, Ubuntu)
- Оглавление
- Что такой скрытый сервис Tor и как его сделать
- Настройка виртуального хоста скрытого сервиса Tor
- Подключение локального веб-сервера к сети Tor в качестве скрытого сервиса Tor
- Famicoman.com
- Configuring a Tor Hidden Service
- Installing Tor
- Configuring the Hidden Service
- Example — Configure A Web Server with Nginx
- Example — Configure A Web Server with Apache
- Conclusion
- How to add a Tor Hidden Service (.onion) to your website running on Ubuntu/Debian Linux
- Frequently Asked Questions
- Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!
- Order a server TODAY! Privacy is affordable™
- Requirements
- Install Tor
- Install apt-transport-https + gpg
- Import TorProject’s GPG public signing key
- Add the TorProject apt repository
- Install Tor
- Prepare your web server
- Configuring Nginx
- Configuring Caddy
- Configuring Tor
- Enabling a Hidden Service (.onion) in /etc/tor/torrc
- Find out and test your hidden service URL (.onion address)
- Additional web server configuration
- Add your onion address to your web server’s list of domains
- Add an Onion-Location header or meta tag to inform Tor users about your hidden service
- Test your Onion-Location by browsing to your normal website
- Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!
HackWare.ru
Этичный хакинг и тестирование на проникновение, информационная безопасность
Tor: от азов до продвинутого уровня (ч. 11): Настройка скрытого сервиса Tor в Debian (Kali Linux, Linux Mint, Ubuntu)
Оглавление
Что такой скрытый сервис Tor и как его сделать
Если вы уже используете скрытые сервисы TOR, то убедитесь, что у вас адрес и ключи третьей версии. То есть ранее адреса были примерно такие:
- hacktoolseqoqaqn.onion
А теперь стали примерно такие:
- hacking5xcj4mtc63mfjqbshn3c5oa2ns7xgpiyrg2fenl2jd4lgooad.onion
В октябре 2021 скрытые сервисы TOR Onion версии 2 перестанут работать. Уже некоторое время при автоматической генерации домена для скрытого сервиса используется TOR Onion v3 vanity. Но если вы по-прежнему используете старую, вторую версию, то вам нужно переходить на третью с новым адресом, а старый адрес использовать для информирования ваших посетителей.
Данная инструкция по настройке скрытого сервиса Tor покажет его настройку в Kali Linux, но она подойдёт для всех производных Debian, в том числе для Linux Mint и Ubuntu. Если у вас дистрибутив на основе Arch Linux, то для вас инструкция «Настройка скрытого сервиса Tor в Arch Linux / BlackArch».
Скрытые сервисы Tor имеют доменные имена с расширениями .onion
Скрытые сервисы доступны только из сети Tor. Например, вы можете открыть эти адреса, если вы используете Tor Browser. Для скрытого сервиса не нужен белый IP, поскольку роутинг трафика осуществляется внутри сети Tor и она полностью ответственна за обмен данных.
Доменное имя вида .onion выдаётся бесплатно и автоматически. Оно генерируется как случайный набор символов, и вы не можете его выбрать. Тем не менее в статье «Как получить красивое доменное имя для скрытого сервиса Tor» рассказано, как это можно в некоторой степени обойти.
Как уже было сказано, не нужен белый IP, единственное требование – компьютер должен быть включён и должен быть подсоединён к сети Tor. Также требуется веб-сервер. На сервере вы можете использовать любые технологии, в том числе Apache, PHP, системы управления базами данных и прочее – всё, что сможете установить на свой компьютер или свой сервер. Для установки веб-сервера рекомендуется статья «Установка LAMP «Азы работы с веб-сервером для пентестера».
Подразумевается, что вы прочитали статью по ссылке и у вас уже установлен веб-сервер и вы его запустили:
Настройка виртуального хоста скрытого сервиса Tor
Начать нужно с настройки виртуального хоста. Нужно сделать, чтобы этот виртуальный хост был доступен только в локальной сети. Поскольку если он будет доступен глобально, можно очень легко потерять свою «скрытость».
Откройте конфигурационный файл Apache:
Там у меня имеется строка
То есть Apache прослушивает входящие соединения как пришедшие локально, так и из вне. То есть если кто-то захочет подключиться к вашему веб-серверу, то если он находится в вашей локальной сети или у вас белый IP, он сможет это сделать. Если вам это не нужно, то замените строку на следующую:
Веб-сервер будет прослушивать порт 80 только на локальном IP 127.0.0.1.
Теперь я создаём конфигурационный файл виртуального хоста для скрытого сервиса:
В него вставляем следующее:
В принципе, вам достаточно отредактировать в нём только строчку DocumentRoot «/var/www/html/onion» – она показывает путь до вашего веб-сайта, который будет скрытым сервисом Tor.
Не забудьте создать эту директорию:
Активируйте виртуальный хост:
В эту папку разместите любые свои файлы и перезапустите веб-сервер:
Поместите в папку /var/www/html/onion какие-нибудь файлы и проверьте работоспособность сервера:
Если всё работает, то продолжаем.
Подключение локального веб-сервера к сети Tor в качестве скрытого сервиса Tor
Нам нужно начать с установки Tor:
Найдите там строки:
Первая строка указывает, где будет храниться сгенерированное доменное имя и секретный ключ. Её достаточно просто раскоментировать, чтобы получилось:
Вторую строку тоже надо раскоментировать. Первая цифра – это порт, на котором будет размещён ваш скрытый сервис – лучше не меняйте, чтобы пользователя не пришлось вручную указывать нестандартный порт. Следующая строка – это локальный адрес вашего виртуального хоста на веб-сервере. IP должно остаться прежним, а порт в случае необходимости поменяйте на тот, который вы назначили виртуальному хосту веб-сервера. В моём случае это также 80:
Запустите (или перезапустите, если она была установлена ранее) службу Tor:
Проверьте её статус:
Добавьте службу в автозагрузку (по желанию):
Чтобы узнать своё доменное имя наберите:
Теперь это доменное имя сообщайте клиентам вашего скрытого сервиса Tor. Эти сайты можно открыть только через сеть Tor. В обычном Интернете они недоступны.
Если вам нужно несколько скрытых сервисов Tor, то создайте необходимое количество виртуальных хостов веб-сервера и используйте строки
столько раз, сколько вам нужно. Для каждого сервиса нужно указать свою директорию, в которой размещено доменное имя и приватный ключ.
При каждом изменении настроек Tor не забывайте перезапускать службу:
Источник
Famicoman.com
I’m the guy scanning ’90s cyberpunk zines
Configuring a Tor Hidden Service
Tor hidden services allow various types of services (web server, telnet server, chat server, etc) to be operated within the Tor network. This allows both users and service operators to conceal their identities and locations. Just about anything that can be run on the clearnet can be run within the Tor darknet.
Setting up a hidden service on Tor is a simple process and depending on the level of detail, an operator can keep their service completely anonymous. Depending on your use-case, you may or may not choose to anonymize your service at all. For anonymous operation, it is recommended to bind services being offered to localhost and make sure that they do not leak information such as an IP address or hostname in any situation (such as with error messages).
For this guide, we assume a Debian Stretch (or similar) Linux system with a non-root, sudo user. It is also assumed that the target machine has been set up with some standard security practices such as disallowing root logins over SSH, and basic firewall rules. This Tor hidden service will be masked on the darknet, but if the hosting server is deanonymized, a malicious party could uncover the machine’s actual clearnet IP address and attempt to penetrate it or otherwise disrupt service. Depending on the software running the services you are hiding, you may wish to install into a virtual machine to limit damage to the system by code vulnerabilities.
Installing Tor
Before configuring a relay, the Tor package must be set up on the system. While Debian does have a Tor package in the standard repositories, we will want to add the official Tor repositories and install from there to get the latest software and be able to verify its authenticity.
First, we will edit the sources list so that Debian will know about the official Tor repositories.
At the bottom of the file, paste the following two lines and save/exit.
Now back in the console, we will add the Tor Project’s GPG key used to sign the Tor packages. This will allow verification that the software we are installing has not been tampered with.
Lastly, run an update and install Tor from the repositories we just added.
Configuring the Hidden Service
We will be editing the torrc file, so let’s bring it up in our text editor:
Going line by line in this file is tedious, so to minimize confusion, we will ultimately rewrite the whole file. We will implement logging into a file located at /var/log/tor/notices.log and assume the local machine has a web server running on port 80. Paste the following over the existing contents in your torrc file:
After saving the file, make and permission a log file, then we are ready to restart Tor:
If the restart was successful, the Tor hidden service is active. If not, be sure to check the log file for hints as to the failure:
Now that the hidden service is working, Tor has created the hidden service directory we defined in the torrc, /var/lib/tor/hs_name_of_my_service/ . There are two files of importance within this directory.
There is a hostname file at /var/lib/tor/hs_name_of_my_service/hostname that contains the hidden service’s public key. This public key acts as a .onion address which users on the Tor network can use to access your service. Make a note of this address after reading it from the file with cat :
There is also a private_key file that contains the hidden service’s private key. This private key pairs with the service’s public key. It should not be known or read by anyone or anything except Tor, otherwise someone else will be able to impersonate the hidden service. If you need to move your Tor hidden service for any reason, make sure to backup the hostname and private_key files before restoring them on a new machine.
After restarting the hidden service, it may not be available right away. It can take a few minutes before the .onion address resolves on a client machine.
Example — Configure A Web Server with Nginx
Let’s use this hidden service to host a website with Nginx.
First, we will install Nginx and create a directory for our HTML files
Now, we will create an HTML file to serve, so we need to bring one up in our editor:
Paste the following basic HTML and save it:
Next, we will set the owner of the files we created to www-data for the web server and change the permissions on the /var/www directory.
We want to make some configuration changes for anonymity. First, let’s edit the default server block:
Now find the line in the block for server_name В set the server name explicitly:
Next we need to edit the Nginx configuration file:
Find the block that starts with http < and set the following options:
The first option will make sure the server name isn’t used in any redirects. The second option removes server information in error pages and headers. The third option will make sure the port number Nginx listens on will not be included when generating a redirect.
Now we need to create a server block so Nginx knows which directory to serve content from when our hidden service is accessed. Using our text editor, we will create a new server block file:
In the empty file, paste the following configuration block. Make sure that the server_name field contains your onion address which you read from the hostname file earlier and not my address, nb2ticpl4j4hnoxq.onion .
After saving the file, we need to symlink it to the sites-enabled directory and then restart Nginx:
To test the hidden service, download and install the Tor Browser on any machine and load up your .onion address.
Example — Configure A Web Server with Apache
Let’s use this hidden service to host a website with Apache. Note: Many criticize Apache for leaking server information by default. Apache takes more effort to secure.
First, we will install Apache and create a directory for our HTML files
Now, we will create an HTML file to serve, so we need to bring one up in our editor:
Paste the following basic HTML and save it:
Next, we will set the owner of the files we created to www-data for the web server and change the permissions on the /var/www directory.
Now, we need to make a few changes to the Apache configuration. Let’s start by setting Apache up to only listen to port 80 on 127.0.1.1:
Change the line Listen 80 to Listen 127.0.0.1:80 and save the file.
Now we will access the security configuration file:
Change the line for ServerSignature to ServerSignature Off and the line for ServerTokens to ServerTokens Prod to restrict information the httpd reports about the server.
Then, we will make an edit to the main Apache configuration file to override the server name Apache uses:
At the very bottom of the file, paste the following. Make sure that the ServerName field contains your onion address which you read from the hostname file earlier and not my address, nb2tidpl4j4jnoxr.onion .
Next, we will disable Apache’s mod_status module to turn off status information:
Now we need to create a virtual host so Nginx knows which directory to serve content from when our hidden service is accessed. Using our text editor, we will create a new server block file:
In the empty file, paste the following configuration block. Make sure that the server_name field contains your onion address which you read from the hostname file earlier and not my address, nb2tidpl4j4jnoxr.onion .
After saving the file, we need to symlink it to the sites-enabled directory and then restart Nginx:
To test the hidden service, download and install the Tor Browser on any machine and load up your .onion address.
Conclusion
Your hidden service should be up and running, ready to server Tor users. Now that your relay is functioning, it may be a good idea to back up your hostname and private_key files mentioned earlier in the /var/lib/tor/hs_name_of_my_service/ directory.
I would strongly recommend taking a look at riseup.net’s Tor Hidden Services Best Practices guide to learn more about proper setup of your hidden service.
Additionally, subscribe to the tor-onions mailing list for operator news and support!
Источник
How to add a Tor Hidden Service (.onion) to your website running on Ubuntu/Debian Linux
Frequently Asked Questions
Q: I hear most hosts block Tor! Won’t I get banned if I run Tor to add a hidden service to my site?
A: Short answer: NO, you will be fine.
Hosting providers generally only disallow Tor exit nodes, which are Tor nodes that are configured to act as an open proxy for the Tor network, allowing anonymous traffic to flow through the Tor node’s public IP address(es), which can include abusive traffic.
Some hosting providers may block Tor relays despite the fact they don’t generate any abusive traffic. This can be either due to the risk of getting your server’s IP blacklisted by incompetent service administrators who blanket ban all IP addresses linked to Tor (including non-exit relays) — or due to the constant, high volume of traffic that a relay can generate.
To run a hidden service, you DO NOT need to run a relay nor exit. By default, Tor comes with a locked down configuration with everything disabled, to ensure that when you install Tor, it only acts as a relay/exit if you specifically configure it to do so.
A Tor node for just a hidden service acts as a client on the Tor network, it doesn’t require any ports to be opened/forwarded, and it should produce only minimal background traffic. The only non-negligible traffic that the Tor node should generate, will be from serving requests to your visitors who are using your website’s Hidden Service.
This means you can run a hidden service on almost all hosting providers without any complaints or abuse problems.
Q: How can I tell if someone is browsing my site / service using the hidden service?
A: If you have access logs enabled, their IP address will appear as 127.0.0.1 or 0.0.0.0 . They’ll also generally send your onion address in the Host field.
Q: Do I need an SSL certificate for my onion address?
A: No. Hidden service traffic is end-to-end encrypted by nature. Your .onion address is actually a public key, and your server holds the private key in the HiddenServiceDir (usually inside a folder under /var/lib/tor ), ensuring all traffic is encrypted between clients and your server automatically, by nature of the Tor hidden service protocol.
Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!
We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo
Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.
We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.
At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD
Order a server TODAY! Privacy is affordable™
Requirements
This guide assumes that your server is running on a Debian-based Linux distro such as Ubuntu Server, Debian, Linux Mint, or other Debian distros (if your package manager is apt / aptitude then it’s probably Debian based)
- A Debian-based Linux server (dedicated or virtual) — Generally Ubuntu Server or Debian
- Root access to the server
- A configured web server (this guide covers Nginx and Caddy)
- At least 256mb of RAM minimum (may work with less)
- Basic knowledge of the Linux terminal
Tor runs on other operating systems such as Windows, BSD, Mac OSX, and non-Debian based Linux distros, but this guide will not be covering installation for non-Debian based platforms.
You should also become root — all commands should be ran under the root user unless otherwise stated.
To become root — if you’re not already, enter the following command, including the —
You should now be logged in as root. Your terminal prompt may look something like this:
Install Tor
Install apt-transport-https + gpg
TorProject uses https (SSL) for their package repositories. On many Ubuntu/Debian Linux distributions, the package required for using https apt repos isn’t installed.
You may also need the gpg to import their package signing key.
To ease the process of adding TorProject’s official apt repository, you should also make sure that software-properties-common is installed.
Run the following commands to install gpg , software-properties-common and apt-transport-https — it won’t hurt anything if you’ve already got them installed:
Import TorProject’s GPG public signing key
Next, you’ll need to download and import TorProject’s package signing GPG public key. TorProject signs their pre-built Tor packages with their signing private key, which allows you to verify that the packages are safe and haven’t been tampered with, by verifying their signature using their public key. The signature verification is done automatically by apt.
If you receive warnings that the key has been revoked or is expired, then you should check the official TorProject install instructions to find the latest key.
To install the TorProject public signing key:
Add the TorProject apt repository
The tool apt-add-repository allows you to easily add a new apt repository, and will automatically fill out your distro and version to obtain the correct package for your OS.
We also add the -s argument to add the deb-src repo alongside the deb repo, as recommended by TorProject
To add TorProject’s apt repository:
Install Tor
Now that your system is setup to download the Tor server packages from TorProject, we can install Tor 🙂
Prepare your web server
Configuring Nginx
Locate the Nginx site config which you want to point the hidden service to.
The default Nginx site config is /etc/nginx/sites-enabled/default — so for this example we’re going to use that.
Open up the file /etc/nginx/sites-enabled/default in your editor of choice (If you’re not sure, use nano )
Save and close the file. If you’re using nano, hold CTRL and press X, press Y to agree to saving the file, and then press enter when it asks for the filename.
Now restart Nginx so that it starts listening on 8181:
Configuring Caddy
Open your Caddyfile, normally at /etc/caddy/Caddyfile
Add a space after your existing domain(s), and add :8181 to make Caddy listen on port 8181 without automatic HTTPS or hostname locking. For example:
Configuring Tor
Enabling a Hidden Service (.onion) in /etc/tor/torrc
Open up the file /etc/tor/torrc in your editor of choice (If you’re not sure, use nano )
Use your arrow keys to scroll down until you see the HiddenService section.
Add the following lines anywhere within that section (see the screenshot for an example):
Save and close the file. If you’re using nano, hold CTRL and press X, press Y to agree to saving the file, and then press enter when it asks for the filename.
Now, restart Tor
Find out and test your hidden service URL (.onion address)
Assuming that you set your HiddenServiceDir to /var/lib/tor/mywebsite/ — use cat to read the hostname file within your hidden service folder:
In our case, the following onion address was outputted:
Open up Tor browser, and enter your onion address into the URL bar.
It may take up to 60 seconds to load for the first time.
Once it loads, you should see your website 🙂
Additional web server configuration
Add your onion address to your web server’s list of domains
For nginx, add your .onion domain to your existing server_name — which is a space separated list of domains that this site config is responsible for.
For Caddy, you should not add your .onion domain, as Caddy will attempt to obtain SSL for it — which will not work, as onion addresses are not supported by LetsEncrypt. Simply use :8181 as previously shown in the guide.
Add an Onion-Location header or meta tag to inform Tor users about your hidden service
The best way to setup Onion-Location is by adding a header in your web server.
For Caddy v2, add the following to your Caddyfile — if you have multiple sites in there, you should place it inside of a site block:
If you’re unable to add a header, or the header doesn’t appear to be working as expected, you can set a meta tag inside of the block of your site’s HTML template:
Test your Onion-Location by browsing to your normal website
WARNING: TorBrowser will not trust the Onion-Location header or meta tag if your site does not have HTTPS (SSL). This is to protect against malicious Tor exit nodes advertising fake attacker-controlled hidden services by intercepting non-HTTPS requests.
Once you’ve finished configuring your web server, restart the web server, and then browse to your normal internet website using Tor browser.
Assuming your web server is advertising the header correctly (or you’ve added the meta tag), and your domain is using HTTPS (SSL), you should see a purple .onion available button in the address bar.
Click on the purple button, and it should bring you to your hidden service.
If your Onion-Location is configured correctly, then this will work from any page on your website, for example if a user is browsing /articles/setup-tor-hidden-service-website on your normal internet domain, when they click the purple onion service button, they’ll be brought to /articles/setup-tor-hidden-service-website on your onion hidden service domain seamlessly.
Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!
We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo
Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.
We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.
At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD
Источник