2008. október 26., vasárnap

A crontab csoda

elhasználói crontab-ok manipulálása (Dillon's Cron)

HASZNÁLAT

crontab file [-u user] - crontab cseréje file -ból
crontab - [-u user] - crontab cseréje standard inputról
crontab -l [user] - a felhasználói crontab listázása
crontab -e [user] - a felhasználói crontab szerkesztése
crontab -d [user] - felhasználói crontab törlése
crontab -c dir - crontab directory megadása

LEÍRÁS

crontab

Ezzel a paranccsal egy-egy felhasználóra vonatkozó crontabot lehet módosítani. Csak a superuser adhat meg a magáétól különböző felhasználónevet, illetve más crontab könyvtárat a parancshoz. Általában a -e opció jeleneti a saját crontab -unk módosítását. A crontab -ok módósításához a /usr/bin/vi -t, illetve a VISUAL környezeti változóban meghatározott szerkesztőt hasznalja a parancs.

Eltérően más crond/crontab -októl ennek a crontab -nak nem célja,hogy minden szóbajövö feladatot megoldjon. Őszintén szólva egy shellscript sokkal jobban használható a környezet manipulálására mint a cron, és nem látok különösebb indokot, hogy a felhasználók saját shellt használjanak, (amihez szükség van a kulcsszavukra) cron parancsok futtatásahoz, hiszen ezeknél külön kell kezelni a non-user crontab -eket, mint például az UUCP -t. A crontab parancsok futtatása a /bin/sh -val történik, és csak három környezeti változó (USER, HOME, SHELL) íródik át.

a crond automatikusan detektálja az időbeli változásokat. Az egy óránál fiatalabb visszafelé indexelt időátálítások hatására NEM futnak újra az eltelt időszakban már kiadott crontab parancsok. Ha előrefelé indexeljük az időt, úgy, hogy kevesebb mint egy órával mutat a jövőbe, akkor a kimarado parancsok pontosan egyszer hajtódnak végre. Akár a jövőbe, akár a múltba mutató egy óránál nagyobb változtatások hatására a crond újraszinkronizál, és nem adja ki az ezáltal kimaradó parancsokat. A parancs nem is próbálja az esetleges úraindítás miatt elvesztett parancsokat újrafuttatni, valamint a parancsok nem kerülnek végrehajtásra akkor sem, ha az előzőleg kiadott parancs még fut. Például ha a crontab -ban megadjuk a 'sleep 70' parancsot, és percenként akarjuk végrehajtatni, akkor a cron csak két percenként fogja tudni kiadni azokat. Ha ez a tulajdonság kellemetlen lenne, akkor még mindig futtathatjuk a parancsainkat a háttérben az '&' jellel. crond automatically detects changes in the time. Reverse-indexed time changes less then an hour old will NOT re-run crontab commands

A crontab formátum nagyjából megegyezik a vixiecron formátumával, de a crontab esetében néhány komplexebb opció hiányzik. Az egyes mezők tartalmazhatnak időpontot, időintervallumot, skip faktoros időintervallumot, szimbólikus intervallumot a hét napjaira, illetve az év hónapjaira, valamint további részintervallumokat vesszővel elválasztva. A crontab file -ban lévő üres, vagy hashmark -kal (#) kezdődő sorokat a parancs nem veszi figyelembe. Ha megadtuk a hét és a hónap egyik napját is, akkor a crontab bejegyzés le fog futni minden héten a megadott napon, valamint minden hónapban a megadott napon.(A két feltétel vagy kapcsolatát képezzük.)

# PERC ÓRA NAP HÓNAP AHÉTEGYNAPJA PARANCS # MIN HOUR DAY MONTH DAYOFWEEK COMMAND
# at 6:10 a.m. every day # at 6:10 a.m. every day
10 6 * * * date

# minden második órában az óra végén
0 */2 * * * date

# minden második óraban reggel 11-től este 7-ig , valamint este 8-kor
0 23-7/2,8 * * * date

# este 11-kor negyedikén, valamint minden hétfőn, kedden, és szerdan
0 11 4 * mon-wed date 0 11 4 * mon-wed date

# január elsején délután 4-kor # 4:00 a.m. on january 1st
0 4 1 jan * date 0 4 1 jan * date

# óránként egyszer, és minden kimenet a log file -ba menjen # once an hour, all output appended to log file
0 4 1 jan * date >>/var/log/messages 2>&1 0 4 1 jan * date >>/var/log/messages 2>&1

A sor parancsrésze a /bin/sh -c -dal fut így tartalmazhat bármilyen érvényes bourne shell parancsot. Általában exec -kel szokás futtatni a parancsot, hogy ne zavarjon bele a process táblába. Szintén gyakori, hogy a kimenetet log file -ba irányitjuk át. Ha nem így teszünk, akkor a parancs a stdout -ban, illetve a stderr -ben hozza létre a kimenetet. Az eredményeket pedig a kérdéses felhasználónak postázza. Ha ezt a mechanizmust speciális felhasználókra alkalmazzuk, mint például az UUCP, akkor ajánlatos aliast készíteni a userhez, hogy a a küldemény valaki másnak menjen, peldául a root -nak, vagy a postamster -nek.

A cron használ egy belső gyorsindexelő rendszert, hogy valamelyest tehermentesítse CPU -t a futtatandó parancsok kikeresésekor. Többszáz crontab -ot kezelhetünk többezer bejegyzéssel anélkül, hogy észrevehetően igénybe vennénk a processzor erőforrásait.

Az EMÍR krontabja:

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

SSH próbálkozások ellen: fail2ban

Nagyon hatásos védekezést ad az SSH jelszó próbálgatásos támadások ellen. Folyamatosan olvassa az auth.log-ot és a megadott próbálkozások után
iptables szabállyal kitiltja a próbálozó IPt. Debian csomag is létezik belőle, még sarge-ra is a van csomag a backports.org-on.

SSH démon védelme
Manapság az interneten robotok kutatnak a gyenge jelszavas felhasználók shelljei után. Meglehetősen kellemetlen dolog mikor látjuk a
logjainkban a sikertelen belépési kísérleteket, mikor próbálgatják kitalálni a felhasználóink a jelszavát, usernevét. Természetesen tudunk
védekezni a probléma ellen. Két fejta egyszerű megoldás is van:
1. Beállíthatunk egy speciálisan erre fejlesztett ssh démon konfigurációs paramétert: MaxStartups
/etc/ssh/sshd_config konfigurációs állomány végén. További információt kahatunk a manuálokból. man sshd_config
2. iptables tűzfal szabályokat is létrehozhatunk a problémára.
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
Például ez a két sor kizárja 1 percen belül a 4. próbálkozástól a következőket a 22 porton.
Sok már kevésbé egyszerű és szerintem veszélyesebb megoldás is van. Van aki kizár minden próbálkozást végleg a támadó tartományából... ezeket a
megoldásokat én nem ismertetem. Feleslegesnek túlzásnak tartom őket. De azért felsorolnék párat közülük: Swatch egy ügyes tool hasonló
problémák kezelésére. Ssh login blokker és egy újabb.

SSH kulcsok használata
Ha egy távoli gépre például jelszó nélkül akarsz bejutni ssh-val, akkor használhatsz ssh kulcsokat.
Ennek a beállítása mindössze pár utasítás:
1. Generálj egy SSH kulcsot magadnak ehhez a művelethez.
ssh-keygen -t dsa
Ne adj meg jelszót amikor jelszavas védelmet akar tenni a kulcsra.
2. Másold át a publikus kulcsát a frissen generált kulcspárodnak(publikus és privát).
scp ~/.ssh/id_dsa.pub masikgep.teljes.neve:.ssh/authorized_keys2
Ezután már próbálhasz is átlépnizni jelszó nélkül.
ssh masikgep.teljes.neve
A kulcs átmásolására van progi, ami biztosan jól megoldja:
ssh-copy-id -i ~/.ssh/id_dsa.pub [user_neved_a_tavoli_gepen]@[tavoli_gep_ipje_vagy_neve]
Néha gond van a jogosultságokkal, erre kell figyelni:
- ssh könyvtár 700
- A távoli gépen a home könyvtárad: 755

Titkosított mentés rsync segítségével; duplicity

Egyik kedvenc weboldalam fórumán hívták fel a címben szereplő csomagra a figyelmem. Több shell scriptes megoldást ismertem ezen mentési
eljárások megodására. Kár, hogy nem találkoztam korábban a szoftverrel: http://www.nongnu.org/duplicity/
(Természetesen pl. debian csomag is van belőle.)
Az angol bemutatás szerényen ennyi: "Encrypted bandwidth-efficient backup using the rsync algorithm"
Én ezt "Takarékos és biztonságos mentési eljárásnak" fordítanám.
Egy vetélytárs: rdiff-backup
Angol leírás itt: http://www.howtoforge.com/linux_rdiff_backup

Grafikus LDAP adminisztráció: lat

A LAT = LDAP Administration Tool. Egyszerú könnyen átlátható felületet ad LDAP alapú címtárakban elemek szerkesztésére/új elem hozzáadásra/törlésre. Tud profilokat kezelni több szerver gyors elérését segítve. Előredefiniált templétekkel könnyítik a munkánk.

Szolgáltatásai:
* felhasználó, csoport és egyéb felhasználó által definiálható templétek használata
* Címtár böngésző
* Séma böngésző
* LDIF import és export

SMTP teszt telnettel

SMTP szerver konfugurálás közben jól jön, ha telnettel tudunk mailszervert tesztelni.
Íme egy példa:

$ telnet smtp.pelda.hu smtp
Trying 192.0.34.72...
Connected to smtp.example.com.
Escape character is '^]'.
220 smtp.pelda.hu ESMTP Postfix (Debian/GNU)
HELO smtp.vhol.hu
250 smtp.example.com
MAIL From: kecsi@linuxbox.hu
250 Ok
RCPT To: haver@valahol.hu
250 Ok
DATA
354 End data with .
Hello!
Kene nekem egykis linux segitseg.
.
250 Ok: queued as F169C23068
QUIT
221 Bye
Connection closed by foreign host.

A levél végét a szöveg utolsó sorában a . adja!
SMTP AUTH teszt
Ezzel a módszerrel lehet jelszót készíteni:
$ perl -MMIME::Base64 -e 'print encode_base64("\000jms1\@jms1.net\000not.my.real.password")'
AGptczFAam1zMS5uZXQAbm90Lm15LnJlYWwucGFzc3dvcmQ=

Majd a mailszerveren ezzel az utasítással lehet authentikálni:
AUTH PLAIN AGptczFAam1zMS5uZXQAbm90Lm15LnJlYWwucGFzc3dvcmQ=

Merevlemez hőmérsékletének figyelése

hddtemp (S.M.A.R.T. szükséges)
apt-get install hddtemp
Használata:
hddtemp /dev/...

How to Reset the Root Password

B.1.4.1.1. Resetting the Root Password on Windows Systems
B.1.4.1.2. Resetting the Root Password on Unix Systems

If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. However, it is recommended to set a password for each account. See Section 5.3.1, “General Security Guidelines”.

If you set a root password previously, but have forgotten what it was, you can set a new password. The next two sections show procedures for Windows and Unix systems, respectively.
B.1.4.1.1. Resetting the Root Password on Windows Systems

Use the following procedure for resetting the password for any MySQL root accounts on Windows:

1.

Log on to your system as Administrator.
2.

Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager:

Start Menu -> Control Panel -> Administrative Tools -> Services

Then find the MySQL service in the list, and stop it.

If your server is not running as a service, you may need to use the Task Manager to force it to stop.
3.

Create a text file and place the following statements in it. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

The UPDATE and FLUSH statements each must be written on a single line. The UPDATE statement resets the password for all existing root accounts, and the FLUSH statement tells the server to reload the grant tables into memory.
4.

Save the file. For this example, the file will be named C:\mysql-init.txt.
5.

Open a console window to get to the command prompt:

Start Menu -> Run -> cmd

6.

Start the MySQL server with the special --init-file option:

C:\> C:\mysql\bin\mysqld --init-file=C:\mysql-init.txt

If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.

The server executes the contents of the file named by the --init-file option at startup, changing each root account password.

You can also add the --console option to the command if you want server output to appear in the console window rather than in a log file.

If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option:

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe"
--defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini"
--init-file=C:\mysql-init.txt

The appropriate --defaults-file setting can be found using the Services Manager:

Start Menu -> Control Panel -> Administrative Tools -> Services

Find the MySQL service in the list, right-click on it, and choose the Properties option. The Path to executable field contains the --defaults-file setting.
7.

After the server has started successfully, delete C:\mysql-init.txt.
8.

Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

You should now be able to connect to MySQL as root using the new password.
B.1.4.1.2. Resetting the Root Password on Unix Systems

MySQL Enterprise. For expert advice on security-related issues, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.

Use the following procedure for resetting the password for any MySQL root accounts on Unix. The instructions assume that you will start the server so that it runs using the Unix login account that you normally use for running the server. For example, if you run the server using the mysql login account, you should log in as mysql before using the instructions. (Alternatively, you can log in as root, but in this case you must start start mysqld with the --user=mysql option. If you start the server as root without using --user=mysql, the server may create root-owned files in the data directory, such as log files, and these may cause permission-related problems for future server startups. If that happens, you will need to either change the ownership of the files to mysql or remove them.)

1.

Log on to your system as the Unix mysql user that the mysqld server runs as.
2.

Locate the .pid file that contains the server's process ID. The exact location and name of this file depend on your distribution, hostname, and configuration. Common locations are /var/lib/mysql/, /var/run/mysqld/, and /usr/local/mysql/data/. Generally, the filename has an extension of .pid and begins with either mysqld or your system's hostname.

You can stop the MySQL server by sending a normal kill (not kill -9) to the mysqld process, using the pathname of the .pid file in the following command:

shell> kill `cat /mysql-data-directory/host_name.pid`

Note the use of backticks rather than forward quotes with the cat command; these cause the output of cat to be substituted into the kill command.
3.

Create a text file and place the following statements in it. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

The UPDATE and FLUSH statements each must be written on a single line. The UPDATE statement resets the password for all existing root accounts, and the FLUSH statement tells the server to reload the grant tables into memory.
4.

Save the file. For this example, the file will be named /home/me/mysql-init. The file contains the password, so it should not be saved where it can be read by other users.
5.

Start the MySQL server with the special --init-file option:

shell> mysqld_safe --init-file=/home/me/mysql-init &

The server executes the contents of the file named by the --init-file option at startup, changing each root account password.
6.

After the server has started successfully, delete /home/me/mysql-init.

You should now be able to connect to MySQL as root using the new password.

Alternatively, on any platform, you can set the new password using the mysql client (but this approach is less secure):

1.

Stop mysqld and restart it with the --skip-grant-tables option.
2.

Connect to the mysqld server with this command:

shell> mysql

3.

Issue the following statements in the mysql client. Replace the password with the password that you want to use.

mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
-> WHERE User='root';
mysql> FLUSH PRIVILEGES;

You should now be able to connect to MySQL as root using the new password.
Previous / Next / Up / Table of Contents