Автор: Ржавсков Андрей
1. Введение
На одной из моих мест работы доступ к глобальной сети Интернет был организован через ISA-сервер, который использует протокол авторизации NTLM. В принципе, авторизацию на основе протокола NTLM поддерживает SQUID, но я предпочел использовать NTLM Authorization Proxy Server из-за простоты использования его на локальной машине.
2. Благодарности
Большое спасибо, Dmitry Rozmanov, который разработал и ведет этот проект http://freshmeat.net/projects/ntlmaps/ и на этой же страничке можно скачать последнюю версию проекта.
Автор этой статьи будет благодарен за присланные замечания и предложения по улучшению или добавления материала, представленного здесь.
3. NTLM Authorization Proxy Server.
NTLM
Authorization Proxy Server (APS) является прокси в программном исполнении, которой позволяет производить аутентификацию через MS Proxy Server, используя проприентарный NTLM протокол. APS способен вести себя самостоятельным прокси сервером и производить аутентификацию HTTP-клиентов WEB сервисов используя NTLM протокол. Он меняет заголовки пакетов клиента, так что запросы выглядят как будто их создали в MS IE.
APS реализован на Python и требует транслятор этого языка не ниже версии 1.5.2.
4. Как получить последнюю версию?
Последнюю версию APS можно получить по этому адресу http://prdownloads.sourceforge.net/ntlmaps/ntlmaps-0.9.9.tar.gz?downloa или более новую на главной страницы проекта http://freshmeat.net/projects/ntlmaps/
Перед тем как Вы будете качать архив ntlmaps-0.9.9.tar.gz надо создать отдельный каталог, например ~/APS_v099, или качать в свой каталог пользователя ~/. Я буду качать в каталог ~/APS_v099.
[rjaan@home rjaan]$ mkdir ~/APS_v099; cd ~/APS_v099
[rjaan@home APS_v099]$ tar xzvf ntlmaps-0.9.9.tar.gz ntlmaps-0.9.9/ ntlmaps-0.9.9/doc/ ntlmaps-0.9.9/doc/greenball.gif ntlmaps-0.9.9/doc/ENCRYPTION.txt ntlmaps-0.9.9/doc/NTLM Authentication Scheme for HTTP.htm ntlmaps-0.9.9/lib/ ntlmaps-0.9.9/lib/www_client.py ntlmaps-0.9.9/lib/proxy_client.py ntlmaps-0.9.9/lib/http_header.py ntlmaps-0.9.9/lib/U32.py ntlmaps-0.9.9/lib/config.py ntlmaps-0.9.9/lib/server.py ntlmaps-0.9.9/lib/logger.py ntlmaps-0.9.9/lib/des.py ntlmaps-0.9.9/lib/monitor_upstream.py ntlmaps-0.9.9/lib/config_affairs.py ntlmaps-0.9.9/lib/md4.py ntlmaps-0.9.9/lib/ntlm_auth.py ntlmaps-0.9.9/lib/ntlm_messages.py ntlmaps-0.9.9/lib/des_c.py ntlmaps-0.9.9/lib/ntlm_procs.py ntlmaps-0.9.9/lib/des_data.py ntlmaps-0.9.9/lib/basic_auth.py ntlmaps-0.9.9/lib/utils.py ntlmaps-0.9.9/main.py ntlmaps-0.9.9/changelog.txt ntlmaps-0.9.9/research.txt ntlmaps-0.9.9/readme.txt ntlmaps-0.9.9/server.cfg ntlmaps-0.9.9/Install.txt ntlmaps-0.9.9/__init__.py ntlmaps-0.9.9/runserver.bat ntlmaps-0.9.9/COPYING [rjaan@home APS_v099]$
[rjaan@home APS_v099]$ cd ntlmaps-0.9.9 [rjaan@home ntlmaps-0.9.9]$
6. Как настроить APS для своей локальной сети.
Для того чтобы настроить APS для своей локальной сети, вам необходимо отредактировать файл конфигурации server.cfg, который находится в каталоге ~/APS_v099/ntlmaps-0.9.9
Файл конфигурации server.cfg состоит из переменных и комментариев к ним. Комментарием считается строка первый символ которой начинается знаком решетки. Переменной является строка, которая не имеет этот символ в своем начале.
Переменная содержит в себе уникальное имя переменной и свое значение.
Знаком разделения обоих является двоеточие. При чтении справа налево, сначала строки и до разделителя считается уникальное имя переменной. За
знаком разделителя и до знака конца строки или возврата корретки – значением этой переменной.
# NT_DOMAIN – имя переменной # your_domain – значение переменной NT_DOMAIN. NT_DOMAIN:your_domain
Целью настройке APS служит передача информации об proxy сервера через
который осуществляется доступ к сети Интернет по протоколу NTLM. Для
этого необходимо знать некоторые данные этого прокси сервера. В моем
случае использовался ISA сервер, который обладал функцией proxy сервера
нашей сети. Для настройки APS мне нужно было использовать следующие
параметры:
IP-адрес прокси = 192.168.0.120 Порт прокси = 3128 NT домен = WORKGROUP Имя пользователя домена = user Пароль пользователя домена = 123456 Порт HTTP клиента = 5865
Вот и вся необходимая информация для настройки APS.
Примечание У вас могут быть другие параметры ISA сервера, обратитесь к системному администратору.
Запись исходных данных осуществляем в ~/APS_v099/ntlmaps-0.9.9/server.cfg. Для этого можно воспользоваться текстовым редактором.
Согласно наших исходных данных нам надо изменить следующие переменные:
LISTEN_PORT, PARENT_PROXY, PARENT_PROXY_PORT, USER, PASSWORD.
Спускаясь вниз, по тексту, редактируем переменные, которые в этом нуждаются без изменения других переменных, которые в этом не требуются:
001.#======================================================================== 002.[GENERAL] 003. 004.LISTEN_PORT:5865 005. 006.# If you want APS to authenticate you at WWW servers using NTLM then just leave this 007.# value blank like PARENT_PROXY: and APS will connect to web servers directly. 008.# You can specify more than one proxy by leaving a space between each one, and 009.# APS will detect when one fails and automatically fail-over to the next. EG: 010.#PARENT_PROXY:first_proxy second_proxy third_proxy 011.# And NOTE that NTLM cannot pass through another proxy server. 012.PARENT_PROXY:192.168.0.120 013. 014.PARENT_PROXY_PORT:3128 015. 016.# APS will poll the upstream proxy and attempt to fail-over to a new one if it doesn\\\\\\\'t 017.# get a response within an appropriate time frame. The amount of time that it will 018.# wait for a response before attempting fail-over is specified, in seconds, below: 019.PARENT_PROXY_TIMEOUT:15 020. 021.# Set to 1 if you want to grant this authorization service to clients from other computers. 022.# NOTE: all the users from other hosts that will be using you copy of APS for authentication 023.# will be using your credentials in NTLM auth at the remote host. 024.ALLOW_EXTERNAL_CLIENTS:0 025. 026.# If you want to allow some other but not all computers to use your proxy for 027.authorization, 028.# just set ALLOW_EXTERNAL_CLIENTS:0 and put friendly IP addresses here. 029.# Use space as a delimiter. 030.# NOTE that special addesses don\\\\\\\'t work here (192.168.3.0 for example). 031.FRIENDLY_IPS: 032. 033.# Requested URLs are written to file. May be useful. 034.URL_LOG:0 035. 036.# When a network service listens for connections, there is a maximum number of connection 037.# attempts to that service that the underlying OS will allow to backlog waiting for a response 038.# before the OS will start dropping new connection attempts with Connection refused. The 039.# standard method of determining the maximum number of backlogged connections is to use the 040.# SOMAXCONN constant, which is supposed to represent the maximum number that an OS will support 041.# (for example, 5 on Windows 2000 Pro, and 200 on Windows 2000 server). However, because this 042.# is a statically compiled value in a Python distribution, usually this instead represents the 043.# the most conservative value (5 on all Windows platforms, and 128 on the GNU/Linux variant I 044.# tried). So if you are running (for example) a massively threaded/parallel download manager, 045.# the default value of, say, 5, or whatever SOMAXCONN happens to be set to, may be too low and 046.# cause some connections to fail. The value below can be set to any integer (it seems that 047.# Python just silently caps values above the hard limit for the underlying platform), or it can 048.# be set to the special value of SOMAXCONN (i.e. MAX_CONNECTION_BACKLOG:SOMAXCONN), to use 049.# whatever this value happens to be set to in your Python build. Setting this higher than 050.# necessary may cause APS to consume more memory than you needed to. 051.MAX_CONNECTION_BACKLOG:5 052. 053.#======================================================================== 054.[CLIENT_HEADER] 055. 056.# This section describes what and how the server should change in the clients headers. 057.# Made in order to prevent parent proxy from seeing that you are using wget instead of IE5.5 058. 059.Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */* 060.User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98) 061. 062.# for windows 2000 emulation ;) 063.# User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT5) 064. 065.# You can uncomment these chages in clients header to mimic IE5+ better, but in this case 066.# you may expirience problems with *.html if your client does not really handle compression. 067.#Accept-Encoding: gzip, deflate 068. 069.#======================================================================== 070.[NTLM_AUTH] 071. 072.# Optional value, if leaved blank then APS will use gethostname() to determine 073.# hosts name. 074.# NOTE1: If you Linux host name differs from Windows host name then it may be that 075.# MS server wont recognize you host at all and wont grant you access 076.# to resources requested. Then you have to use this option and APS will use 077.# this name in NTLM negotiations. 078.# NOTE2: There are several reports that you can successfully use host name 079.# here. Say, if user may access a resource from and may not from 080.# then there is a chance that APS running on with NT_HOSTNAME:host1 will 081.# be able to be granted access to the restricted resource. However use this on 082.# you own risk as such a trick may be considered as a hack or something. 083.NT_HOSTNAME: 084. 085.# Windows Domain. 086.# NOTE: it is not full qualified internet domain, but windows network domain. 087.NT_DOMAIN:WORKGROUP 088. 089.# What users name to use during authorization. It may differ form real current username. 090.# If you enable NTLM_TO_BASIC, below, you can either leave this blank or simply 091.# hash it out. 092.USER:user 093. 094.# Password. Just leave it blank here and server will request it at the start time, 095.# or, if you enable NTLM_TO_BASIC, below, you can either leave this blank or simply 096.# hash it out, and you *wont* be prompted for a password at start time. 097.PASSWORD:123456 098. 099.# These two options replace old FULL_NTLM option. 100.# NTLM authentication consists virtually of two parts: LM and NT. Windows95/98 use 101.# only LM part, WindowsNT/2000 can use NT and LM or just NT part. 102.# Almost always using just LM part will be enough. I had several reports 103.# about LM and NT requirement and no about just NT. 104.# So try to setup 1, 1 only if you have enough reasons to do so and when you understand 105.# what you are doing. 106.# 0, 0 is an illegal combination 000.# NOTE: if you change these options then you have to setup flag option accordingly. 107.LM_PART:1 108.NT_PART:0 109. 110.# Highly experimental option. See research.txt for details. 111.# LM - 06820000 112.# NT - 05820000 113.# LM + NT - 07820000 114.NTLM_FLAGS: 06820000 115. 116.# This option makes APS try to translate NTLM authentication to very usual 117.# scheme. Almost all http clients know it. With this option set to 1 user will be requested 118.# by his browser to enter his credentials and these username and password will be used by 119.# APS for NTLM authentication at MS Proxy server or Web server. 120.# In such a case different users can use one runnig APS with their own credentials. 121.# NOTE1: currently translation works so it allows only one try for entering 122.# username/password. If you make a mistake you will have to restart you browser. 123.# NOTE2: With debug:1 basic username/password will be written in log file in clear 124.# text format. I could try hide it, but the basic scheme is so weak that anybody 125.# who had access to APS would be able to get it. 126.NTLM_TO_BASIC:0 127. 128.#======================================================================== 129.[DEBUG] 130. 131.# Set this to 1 if you want to see debug info in many log files. One per connection. 134.DEBUG:0 135. 136.# Set this to 1 to get even more debug info. 137.BIN_DEBUG:0 138. 139.# Set this to 1 to see some strange activity on screen. Actually you wont want it. 140.SCR_DEBUG:0 141. 142.# Not actually a debug option but gives you some details on authentication process 143.# into *.auth logs. Also see research.txt. 144.AUTH_DEBUG:0 145.
Изменения коснулись переменных:
PARENT_PROXY строка 12: your_parentproxy было заменена на 192.168.0.120.
PARENT_PROXY_PORT строка 14: 8080 изменено на 3128
NT_DOMAIN строка 87: your_domain была изменена WORKGROUP.
USER cтрока 92: username_to_use на реальное имя пользователя user
PASSWORD cтрока 97:your_nt_password на действующий пароль 123456
Остальные строки остаются без изменений. Значение переменных таких как LM_* и NT_* использовались мной по умолчанию. Если у Вас появится необходимость в их изменении прочтите research.txt, который находится в том же каталоге, что и server.cfg . DEBUG переменные предназначены для получения более расширенной информации об работе APS: в штатном режиме – их можно не использовать.
6.4 Настройка HTTP клиента(WEB-браузер).
Перед тем как настраивать клиента, загляните в переменную User-Agent, строка 59-62. Для эмуляции windows 2000 строку 59 закоментировать, строку 62 раскоментировать.
Затем открыть настройки прокси
WEB-браузера и для поля HTTP прописать адрес 127.0.0.1 или localhost, а в поле порта прописать значение переменной LISTEN_PORT, которое равно 5865. После чего в консоле запустить скрипт main.py, который находится в том же каталоге, где файл server.cfg. Для первого запуска установите права 754.
[rjaan@home ntlmaps-0.9.9]$ chmod 754 main.py
Ваш APS готов к работе. Если что-то не работает еще раз убедитесь в правильности редактирования файла server.cfg .