Using tor on linux

Содержание
  1. INSTALLATION
  2. For Windows
  3. For macOS
  4. For GNU/Linux
  5. Graphical method
  6. Command-line method
  7. Ethical hacking and penetration testing
  8. InfoSec, IT, Kali Linux, BlackArch
  9. How to manage Tor service on Linux
  10. How to install Tor on Linux
  11. How to start the Tor service
  12. How to start the tor service without switching to the background
  13. Tor Settings Files
  14. Configure Tor Logs
  15. How to view Tor logs
  16. How to start the Tor service with options
  17. How to use the Tor service on Linux
  18. Tor troubleshooting
  19. Could not bind to 127.0.0.1:9050: Address already in use. Is Tor already running?
  20. Directory /var/lib/tor cannot be read: Permission denied
  21. /var/lib/tor is not owned by this user
  22. HackWare.ru
  23. Этичный хакинг и тестирование на проникновение, информационная безопасность
  24. Tor: от азов до продвинутого уровня (ч. 8): Служба Tor в Linux
  25. Оглавление
  26. Как установить Tor в Linux
  27. Как запустить службу Tor
  28. Как запустить службу tor без перевода в фон
  29. Файлы настроек Tor
  30. Настройка журналов Tor
  31. Как запустить службу Tor с опциями
  32. Как просмотреть логи Tor
  33. Как пользоваться службой Tor в Linux
  34. Решение проблем с Tor
  35. Ошибка «Could not bind to 127.0.0.1:9050: Address already in use. Is Tor already running?»
  36. Ошибка «Directory /var/lib/tor cannot be read: Permission denied»
  37. Ошибка «/var/lib/tor is not owned by this user»

INSTALLATION

INSTALLATION

For Windows

Navigate to the Tor Browser download page.

Download the Windows .exe file.

When the download is complete, double click the .exe file. Complete the installation wizard process.

For macOS

Navigate to the Tor Browser download page.

Download the macOS .dmg file.

When the download is complete, double click the .dmg file. Complete the installation wizard process.

For GNU/Linux

Navigate to the Tor Browser download page.

Download the GNU/Linux .tar.xz file.

Now follow either the graphical or the command-line method:

Graphical method

When the download is complete, extract the archive using an archive manager.

You’ll need to tell your GNU/Linux that you want the ability to execute shell scripts. Navigate to the newly extracted Tor Browser directory. Right click on start-tor-browser.desktop , open Properties or Preferences and change the permission to allow executing file as program. Double-click the icon to start up Tor Browser for the first time.

Note: On Ubuntu and some other distros if you try to launch start-tor-browser.desktop a text file might open up. To change this behavior and launch Tor Browser instead, follow this:

  • Launch «Files» (GNOME Files/Nautilus)
  • Click on Preferences.
  • Navigate to the ‘Behavior’ Tab.
  • Select «Run them» or «Ask what to do» under «Executable Text Files».
  • If you choose the latter click on «Run» after launching the start-tor-browser.desktop file.

Command-line method

When the download is complete, extract the archive with the command tar -xf [TB archive] .

From inside the Tor Browser directory, you can launch Tor Browser by running:

Источник

Ethical hacking and penetration testing

InfoSec, IT, Kali Linux, BlackArch

How to manage Tor service on Linux

How to install Tor on Linux

The Tor package is available on most Linux distributions and can be installed from standard repositories.

Tor installation on Debian, Linux Mint, Ubuntu, Kali Linux and their derivatives:

Tor installation on Arch Linux, BlackArch and their derivatives:

To run Tor, no configuration is required – the program already has default values for options. However, you can change many of Tor’s operating parameters using the command line options and directives in the configuration file.

How to start the Tor service

To start use the command:

To check the status:

To add the Tor service to startup so that it starts every time the computer is booting:

To stop the Tor service:

To remove from startup:

How to start the tor service without switching to the background

The tor launch methods shown above turn it into a daemon – that is, a process that runs in the background and is detached from the console.

If you want the Tor service not to go into the background, for example, for debugging, and so that it can be closed with CTRL+c, then start the Tor service as follows in Debian and its derivatives:

On Arch Linux, BlackArch, and derivatives, the startup is done like this:

In fact, tor does not require superuser privileges. But for the service to work, it needs files and directories (/var/lib/tor) the permissions to which are closed to all users (even root) and which belong to the debian-tor or tor user (the username depends on the distribution). For this reason, sudo is used with the -u option, followed by the name of the user on whose behalf the command is executed.

Читайте также:  Как узнать свое разрешение экрана windows

Example of running tor without demonization:

Lines containing the word Bootstrapped indicate the progress of connecting to the Tor network. When everything is ready for traffic exchange with the Internet through the Tor network, it will display:

Tor Settings Files

The main configuration file for the Tor service is /etc/tor/torrc. This file contains only comments, that is, by default it does not set any settings. Tor has default configuration for all settings. For this reason, the file is optional – if it is missing, the Tor service will still start.

If the file /etc/tor/torrc is not found, an attempt will be made to find the file $HOME/.torrc. If there is no such file either, then Tor will simply continue to launch.

There is another configuration file with default settings: /etc/tor/torrc-defaults. The idea is that it should contain default options that can be overwritten with /etc/tor/torrc or $HOME/.torrc. But in practice, this file does not even come with the Tor package.

Next, consider a few options related to configuration files. These options can be specified when the service starts via the tor file.

—verify-config

Checking the Tor configuration file for correctness.

The launch depends on the tor username on the system:

-f FILE

Specifies a new configuration file containing further Tor configuration options. If you specify (dash), then the options will be read from standard input. By default, /etc/tor/torrc or, if this file is not found, then $HOME/.torrc).

—allow-missing-torrc

Do not require the configuration file specified by the -f option to exist if you can access the default torrc).

—defaults-torrc FILE

Specifies the file in which to search for default values for the Tor options. The contents of this file are overwritten with the usual configuration files and options from the command line (by default /etc/tor/torrc-defaults).

—ignore-missing-torrc

Indicates that Tor should process the missing torrc file as if it were empty. Normally, Tor does this because there are no default torrc files, but not for files specified on the command line.

Configure Tor Logs

Tor logs are configured in the configuration file using the Log directive. This directive consists of three components:

SEVERITY_ LEVEL can be: debug, info, notice, warn and err. It is permissible to specify ranges of the form:

As SOURCE_OUTPUT can be:

  • stderr – standard error output
  • stdout – standard output
  • syslog – system log (Unix only)
  • file FILE_NAME – save the log to a file

For example, to output notice level messages to standard output, you would write this:

To display messages from the info level to the err level in the tor.log file, you need to write the following directive to the configuration file:

The Log directive can be specified several times.

How to view Tor logs

You can view Tor logs in various ways, one of the options is:

Please note that if you have Debian or a release from this distribution, then in the previous and next you need to specify the debian-tor user instead of tor, for example:

For example, to display the last 100 entries:

You can also view Tor events using:

How to start the Tor service with options

Tor has many options that have default values. These values can be changed in the Tor configuration files, which are discussed in the next article.

You can start Tor service on the command line with the options used in the configuration file, for this, use a command of the form:

Since in most cases you need to start the service as a debian-tor or tor user, the commands should look something like this (for Debian and derivatives):

On Arch Linux, BlackArch, and derivatives, the startup is done like this:

An example of starting the Tor service with options for replacing their values from the configuration file:

If the VALUE for an OPTION consists of more than one word, or includes special characters, then it must be enclosed in quotation marks, for example:

Читайте также:  Создание простейшего приложения windows forms

See the next article for rules for rewriting or adding option values.

How to use the Tor service on Linux

After starting the Tor service on your computer, the SOCKS proxy becomes available. If you do not know what it is, then it is recommended that you read the article ‘Proxy types, how to use proxy, how to check the quality of proxies’.

This proxy is available on the IP address and port localhost:9050.

About how to configure proxies in Linux, see here.

Remember that some programs have their own proxy settings and may ignore system-wide settings:

Remember that you must specify localhost as the IP address, and 9050 as the port number.

Many programs can work directly with SOCKS4 and SOCKS5:

Compare with the output:

If the program supports only HTTP/HTTPS proxies, but does not know how to work with SOCKS, then use the Privoxy or ProxyChains-NG program as a mediator.

Tor troubleshooting

Could not bind to 127.0.0.1:9050: Address already in use. Is Tor already running?

If you encounter «Could not bind to …: Address already in use.» Errors, for example:

This means that the ports that Tor is trying to listen to are already binded by another process, possibly another running instance of Tor. To correct this situation, stop another instance of the tor service or find a program that occupies this port.

Directory /var/lib/tor cannot be read: Permission denied

occurs when the tor process does not have sufficient permissions to access the /var/lib/tor folder. You must start the tor process on behalf of the corresponding debian-tor or tor user as follows:

/var/lib/tor is not owned by this user

If such errors occur:

This means that you run Tor as root, and you need to run as debian-tor or tor user as follows:

Источник

HackWare.ru

Этичный хакинг и тестирование на проникновение, информационная безопасность

Tor: от азов до продвинутого уровня (ч. 8): Служба Tor в Linux

Оглавление

Как установить Tor в Linux

Пакет Tor доступен в большинстве дистрибутивов Linux и может быть установлен из стандартных репозиториев.

Установка Tor в Debian, Linux Mint, Ubuntu, Kali Linux и их производные:

Установка Tor в Arch Linux, BlackArch и их производные:

Для запуска Tor не требуется какая-либо настройка — у программы уже установлены значения по умолчанию для опций. Тем не менее вы можете поменять множество параметров работы Tor с помощью опций командной строки и директив в конфигурационном файле.

Как запустить службу Tor

Для запуска используйте команду:

Для проверки статуса:

Для добавления службы Tor в автозагрузку, чтобы она запускалась при каждом включении компьютера:

Для остановки службы Tor:

Для удаления из автозарузки:

Как запустить службу tor без перевода в фон

Показанные выше способы запуска tor превращают его в демона — то есть процесс, который работает в фоне и отсоединён от консоли.

Если вам нужно, чтобы служба Tor не уходила в фон, например, для отладки и чтобы её можно было бы закрыть комбинацией клавиш CTRL+c, то запустите службу Tor следующим образом в Debian и производных:

В Arch Linux, BlackArch и производных запуск выполняется так:

На самом деле, программе tor необязательны привилегии суперпользователя. Но для работы службы нужны файлы и директории (/var/lib/tor) права на которые закрыты для всех пользователей (даже для root) и которые принадлежат пользователю debian-tor или tor (имя пользователя зависит от дистрибутива). По этой причине используется sudo с опцией -u, после которой идёт имя пользователя, от имени которого выполняется команда.

Пример запуска tor без демонизации:

Строки, содержащие слово Bootstrapped показывают прогресс подключения к сети Tor. Когда всё готово для полноценного обмена информации с Интернетом через сеть Tor, будет выведено:

Файлы настроек Tor

Главным конфигурационным файлом службы Tor является /etc/tor/torrc. Этот файл содержит только комментарии, то есть по умолчанию не устанавливает никакие настройки. У службы Tor предусмотрены значения по умолчанию для всех настроек. По этой причине, файл не является обязательным — если он отсутствует, служба Tor всё равно запустится.

Если файл /etc/tor/torrc не найден, то будет сделана попытка найти файл $HOME/.torrc. Если такого файла тоже нет, то Tor просто продолжит загрузку.

Имеется ещё один конфигурационный файл с настройками по умолчанию: /etc/tor/torrc-defaults. Задумка в том, что он должен содержать дефолтные опции, которые могут быть перезаписаны файлами /etc/tor/torrc или $HOME/.torrc. Но на практике этот файл даже не поставляется с пакетом Tor.

Читайте также:  Как переустановить windows 10 без потери лицензии office

Далее рассмотрим несколько опций связанных с конфигурационными файлами. Эти опции можно указать при запуске службы файлом tor.

—verify-config

Проверка конфигурационного файла Tor на правильность.

Запуск зависит от имени пользователя tor в системе:

-f ФАЙЛ

Указывает новый конфигурационный файл, содержащий дальнейшие конфигурационные опции Tor. Если указать (тире), то опции будут считываться из стандартного ввода. По умолчанию /etc/tor/torrc или, если этот файл не найден, тогда $HOME/.torrc).

—allow-missing-torrc

Не требовать, чтобы конфигурационный файл, указанный опцией -f, существовал, если можно получить доступ к дефолтному torrc).

—defaults-torrc ФАЙЛ

Указывает файл, в котором искать дефолтные значения для опций Tor. Содержимое этого файла перезаписываются обычными конфигурационными файлами и опциями из командной строки (по умолчанию /etc/tor/torrc-defaults).

—ignore-missing-torrc

Указывает, что Tor должен обрабатывать отсутствующий файл torrc так, как если бы он был пустым. Обычно Tor делает это из-за отсутствия дефолтных файлов torrc, но не для файлов, указанных в командной строке.

Настройка журналов Tor

Настройка логов Tor выполняется в конфигурационном файле с помощью директивы Log. Эта директива состоит из трёх компонентов:

УРОВЕНЬ_СЕРЬЁЗНОСТИ может быть: debug, info, notice, warn и err. Допустимо указывать диапазоны вида:

В качестве ИСТОЧНИК_ВЫВОДА могут быть:

  • stderr — стандартный вывод ошибок
  • stdout — стандартный вывод
  • syslog — системный жунрал (только для Unix)
  • file ИМЯ_ФАЙЛА — сохранение журнала в файл

Например, чтобы выводить сообщения уровня notice в стандартный вывод, нужно записать так:

Для вывода сообщений от уровня info до уровня err в файл tor.log нужно записать в конфигурационный файл следующую директиву:

Директиву Log можно указывать несколько раз.

Как запустить службу Tor с опциями

У Tor много опций, которые имеют значения по умолчанию. Эти значения могут быть изменены в конфигурационных файлах Tor о которых рассказано в следующем разделе.

При этом можно запустит службу в командной строке с указанием опций, используемых в конфигурационном файле, для этого используйте команду вида:

Поскольку в большинстве случаев нужно запускать службу от имени пользователя debian-tor или tor, то команды должны быть примерно такими (для Debian и производных):

В Arch Linux, BlackArch и производных запуск выполняется так:

Пример запуска службы Tor с опциями для замены их значений из конфигурационного файла:

Если ЗНАЧЕНИЕ для ОПЦИИ состоит из более чем одного слова, либо включает в себя специальные символы, то его необходимо поместить в кавычки, например:

О правилах переписывания или добавления значений опций смотрите в следующем разделе.

Как просмотреть логи Tor

Просмотреть логи Tor можно различными способами, один из вариантов:

Обратите внимание, что если у вас Debian или проихводный от этого дистрибутива, то в предыдущей и следующей нужно вместо tor указывать пользователя debian-tor, например:

Например, для вывода последних 100 записей:

Также можно просмотреть события Tor с помощью:

Как пользоваться службой Tor в Linux

После запуска службы Tor на вашем компьютере становится доступным прокси SOCKS. Если вы не знаете, что это такое, то рекомендуется ознакомиться со статьёй «Всё о прокси: виды, как пользоваться, как проверить качество прокси».

Данный прокси доступен на IP адресе и порте localhost:9050.

О том, как настроить прокси в Linux смотрите здесь.

Помните, что некоторые программы имеют свои собственные настройки прокси и могут игнорировать общесистемные установки:

Помните, что в качестве IP адреса нужно указывать localhost, а в качестве номера порта 9050.

Многие программы умеют работать с SOCKS4 и SOCKS5 напрямую:

Сравните с выводом:

Если программа поддерживает только HTTP/HTTPS прокси, но не умеет работать с SOCKS, то в качестве медиатора используйте программу Privoxy или ProxyChains-NG.

Решение проблем с Tor

Ошибка «Could not bind to 127.0.0.1:9050: Address already in use. Is Tor already running?»

Если вы столкнулись с ошибками «Could not bind to …: Address already in use.», например:

То это означает, что порты, которые пытается прослушивать Tor, уже заняты другим процессом, возможно, другим запущенным экземпляром Tor. Для исправления этой ситуации, остановите другой экземпляр службы tor или найдите программу, которая занимает этот порт, для этого смотрите 4 способа узнать, какие порты прослушиваются в Linux.

Ошибка «Directory /var/lib/tor cannot be read: Permission denied»

Возникает в том случае, когда у процесса tor недостаточно прав для доступа к папке /var/lib/tor. Нужно запустить процесс tor от имени соответствующего пользователя debian-tor или tor следующим образом:

Ошибка «/var/lib/tor is not owned by this user»

Если возникают такие ошибки:

То это означает, что вы запускаете Tor от пользователя root, а нужно запускать от имени пользователя debian-tor или tor следующим образом:

Источник

Оцените статью