FreeBSD tips: использование syslog Сергей Супрунов syslogd_flags=”” # ps -wax | grep syslog # Правила, расположенные здесь, применяются ко всем сообщениям +my.host # Правила применяются ко всем сообщениям с my.host !logger # Правила применяются к сообщениям от logger с my.host (фильтр хоста продолжает действовать) !+su # Правила применяются к сообщениям от su с my.host +* # Правила применяются к сообщениям от su с любых хостов (фильтр хоста отменен, фильтр программы продолжает действовать) !* # Правила применяются ко всем сообщениям (фильтр программы так же отменен) facility.CMPlevel destination kern.* /var/log/kern.log *.err -/var/log/all-err.log user.debug vasya mail.*,news.* @syslog.host.ru lpr.!warning /var/log/printers.log level0,level3.=debug * ntp.>crit,<=notice ntpuser,root *.=warning,mail.none /var/log/warn.log *.crit | mail -s “critical message” root # kill –HUP `cat /var/run/syslog.pid` mail.* /var/log/maillog *.=err /var/log/error.log user$ logger -p user.err “Error in user program!” user$ logger -h syslog.host.ru “Test it” /var/log/pflog root:wheel 600 3 100 * JB /var/run/pflog.pid 1 /var/log/maillog 640 7 * @T00 J ----------------------------------------------------------------------------------------------------------------- Крепкий орешек NUT Валентин Синицын # ./configure <параметры> && make && make install Листинг 1. Пример файла ups.conf user = nut [ups0] driver = ippon port = /dev/ttyS0 desc = "Server UPS" # upsdrvctl start Листинг 2. Пример файла upsd.conf ACL local 127.0.0.1/32 ACL all 0.0.0.0/0 ACCEPT local REJECT all Листинг 3. Пример файла upsd.users [admin] password = my_passwd allowfrom = local actions = set instcmds = all upsmon master # chown root:nut upsd.conf upsd.users # chmod 0640 upsd.conf upsd.users # /sbin/upsd # upsc ups0@localhost Листинг 4. Пример файла upsmon.conf MONITOR ups0@localhost 1 admin my_passwd master RUN_AS_USER nut POWERDOWNFLAG /killpower SHUTDOWNCMD "/sbin/shutdown -h now" Листинг 5. rc-сценарий, обеспечивающий защиту от power race /usr/local/ups/sbin/upsmon -K >/dev/null 2>&1 if [ $? = 0 ]; then KILLPOWER=1 else KILLPOWER=0 fi # ...размонтирование ФС, останов демонов if [ $KILLPOWER = 1 ]; then echo "Swithching UPS off, please wait" /usr/local/ups/bin/upsdrvctl shutdown sleep 120 # Power-race workaround echo “Hmm... Still alive?!” reboot -d -f -i fi ----------------------------------------------------------------------------------------------------------------- Alt-N MDaemon – почтовая система для средних и крупных компаний Часть 2 Роман Марков telnet mailserver 25 telnet mailserver 25 ----------------------------------------------------------------------------------------------------------------- bugtraq, стр. 31 http://[target]/forums/index.php?act=Members&max_results=30&filter=1&sort_order=asc&sort_key=name&st=SQL_INJECTION ----------------------------------------------------------------------------------------------------------------- Восстанавливаем удаленные файлы под BSD Крис Касперски sec_n(fragment_offset) = fragment_offset*(fs_bsize/fs_frag/512) sec_n(fragment_offset) = fragment_offset*fs_fsize/512 Листинг 1. Формат суперблока (второстепенные поля опущены) struct fs { /* 0x00 */ int32_t fs_firstfield; /* historic file system linked list, */ /* 0x04 */ int32_t fs_unused_1; /* used for incore super blocks */ /* 0x08 */ ufs_daddr_t fs_sblkno; /* addr of super-block in filesys */ /* 0x0C */ ufs_daddr_t fs_cblkno; /* offset of cyl-block in filesys */ /* 0x10 */ ufs_daddr_t fs_iblkno; /* offset of inode-blocks in filesys */ /* 0x14 */ ufs_daddr_t fs_dblkno; /* offset of first data after cg */ /* 0x18 */ int32_t fs_cgoffset; /* cylinder group offset in cylinder */ /* 0x1C */ int32_t fs_cgmask; /* used to calc mod fs_ntrak */ /* 0x20 */ time_t fs_time; /* last time written */ /* 0x24 */ int32_t fs_size; /* number of blocks in fs */ /* 0x28 */ int32_t fs_dsize; /* number of data blocks in fs */ /* 0x2C */ int32_t fs_ncg; /* number of cylinder groups */ /* 0x30 */ int32_t fs_bsize; /* size of basic blocks in fs */ /* 0x34 */ int32_t fs_fsize; /* size of frag blocks in fs */ /* 0x38 */ int32_t fs_frag; /* number of frags in a block in fs */ /* these are configuration parameters */ /* 0x3С */ int32_t fs_minfree; /* minimum percentage of free blocks */ /* 0x40 */ int32_t fs_rotdelay; /* num of ms for optimal next block */ /* 0x44 */ int32_t fs_rps; /* disk revolutions per second */ /* sizes determined by number of cylinder groups and their sizes */ /* 0x98 */ ufs_daddr_t fs_csaddr; /* blk addr of cyl grp summary area */ /* 0x9C */ int32_t fs_cssize; /* size of cyl grp summary area */ /* 0xA0 */ int32_t fs_cgsize; /* cylinder group size */ /* these fields can be computed from the others */ /* 0xB4 */ int32_t fs_cpg; /* cylinders per group */ /* 0xB8 */ int32_t fs_ipg; /* inodes per group */ /* 0xBC */ int32_t fs_fpg; /* blocks per group * fs_frag */ /* these fields are cleared at mount time */ /* 0xD0 */ int8_t fs_fmod; /* super block modified flag */ /* 0xD1 */ int8_t fs_clean; /* file system is clean flag */ /* 0xD2 */ int8_t fs_ronly; /* mounted read-only flag */ /* 0xD3 */ int8_t fs_flags; /* see FS_ flags below */ /* 0xD4 */ u_char fs_fsmnt[MAXMNTLEN]; /* name mounted on */ }; Листинг 2. Структура описателя группы цилиндров #define CG_MAGIC 0x090255 #define MAXFRAG 8 struct cg { /* 0x00 */ int32_t cg_firstfield; /* historic cyl groups linked list */ /* 0x04 */ int32_t cg_magic; /* magic number */ /* 0x08 */ int32_t cg_old_time; /* time last written */ /* 0x0С */ int32_t cg_cgx; /* we are the cgx'th cylinder group */ /* 0x10 */ int16_t cg_old_ncyl; /* number of cyl's this cg */ /* 0x12 */ int16_t cg_old_niblk; /* number of inode blocks this cg */ /* 0x14 */ int32_t cg_ndblk; /* number of data blocks this cg */ /* 0x18 */ struct csum cg_cs; /* cylinder summary information */ /* 0x28 */ int32_t cg_rotor; /* position of last used block */ /* 0x2С */ int32_t cg_frotor; /* position of last used frag */ /* 0x30 */ int32_t cg_irotor; /* position of last used inode */ /* 0x34 */ int32_t cg_frsum[MAXFRAG]; /* counts of available frags */ /* 0x54 */ int32_t cg_old_btotoff; /* (int32) block totals per cylinder */ /* 0x58 */ int32_t cg_old_boff; /* (u_int16) free block positions */ /* 0x5С */ int32_t cg_iusedoff; /* (u_int8) used inode map */ /* 0x60 */ int32_t cg_freeoff; /* (u_int8) free block map */ /* 0x64 */ int32_t cg_nextfreeoff; /* (u_int8) next available space */ /* 0x68 */ int32_t cg_clustersumoff; /* (u_int32) counts of avail clusters */ /* 0x6С */ int32_t cg_clusteroff; /* (u_int8) free cluster map */ /* 0x70 */ int32_t cg_nclusterblks; /* number of clusters this cg */ /* 0x74 */ int32_t cg_niblk; /* number of inode blocks this cg */ /* 0x78 */ int32_t cg_initediblk; /* last initialized inode */ /* 0x7С */ int32_t cg_sparecon32[3]; /* reserved for future use */ /* 0x00 */ ufs_time_t cg_time; /* time last written */ /* 0x00 */ int64_t cg_sparecon64[3]; /* reserved for future use */ /* 0x00 */ u_int8_t cg_space[1]; /* space for cylinder group maps */ /* actually longer */ Листинг 3. Структура inode в USF1 struct dinode { /* 0x00 */ u_int16_t di_mode; /* 0: IFMT, permissions; see below. */ /* 0x02 */ int16_t di_nlink; /* 2: File link count. */ /* 0x04 */ union { u_int16_t oldids[2]; /* 4: Ffs: old user and group ids. */ int32_t inumber; /* 4: Lfs: inode number. */ } di_u; /* 0x08 */ u_int64_t di_size; /* 8: File byte count. */ /* 0x10 */ int32_t di_atime; /* 16: Last access time. */ /* 0x14 */ int32_t di_atimensec; /* 20: Last access time. */ /* 0x18 */ int32_t di_mtime; /* 24: Last modified time. */ /* 0x1C */ int32_t di_mtimensec; /* 28: Last modified time. */ /* 0x20 */ int32_t di_ctime; /* 32: Last inode change time. */ /* 0x24 */ int32_t di_ctimensec; /* 36: Last inode change time. */ /* 0x28 */ ufs_daddr_t di_db[NDADDR]; /* 40: Direct disk blocks. */ /* 0x58 */ ufs_daddr_t di_ib[NIADDR]; /* 88: Indirect disk blocks. */ /* 0x64 */ u_int32_t di_flags; /* 100: Status flags (chflags). */ /* 0x68 */ int32_t di_blocks; /* 104: Blocks actually held. */ /* 0x6C */ int32_t di_gen; /* 108: Generation number. */ /* 0x70 */ u_int32_t di_uid; /* 112: File owner. */ /* 0x74 */ u_int32_t di_gid; /* 116: File group. */ /* 0x Листинг 4. Структура inode в USF2 struct ufs2_dinode { /* 0x00 */ u_int16_t di_mode; /* 0: IFMT, permissions; see below. */ /* 0x02 */ int16_t di_nlink; /* 2: File link count. */ /* 0x04 */ u_int32_t di_uid; /* 4: File owner. */ /* 0x08 */ u_int32_t di_gid; /* 8: File group. */ /* 0x0C */ u_int32_t di_blksize; /* 12: Inode blocksize. */ /* 0x10 */ u_int64_t di_size; /* 16: File byte count. */ /* 0x18 */ u_int64_t di_blocks; /* 24: Bytes actually held. */ /* 0x20 */ ufs_time_t di_atime; /* 32: Last access time. */ /* 0x28 */ ufs_time_t di_mtime; /* 40: Last modified time. */ /* 0x30 */ ufs_time_t di_ctime; /* 48: Last inode change time. */ /* 0x38 */ ufs_time_t di_birthtime; /* 56: Inode creation time. */ /* 0x40 */ int32_t di_mtimensec; /* 64: Last modified time. */ /* 0x44 */ int32_t di_atimensec; /* 68: Last access time. */ /* 0x48 */ int32_t di_ctimensec; /* 72: Last inode change time. */ /* 0x4C */ int32_t di_birthnsec; /* 76: Inode creation time. */ /* 0x50 */ int32_t di_gen; /* 80: Generation number. */ /* 0x54 */ u_int32_t di_kernflags; /* 84: Kernel flags. */ /* 0x58 */ u_int32_t di_flags; /* 88: Status flags (chflags). */ /* 0x5C */ int32_t di_extsize; /* 92: External attributes block. */ /* 0x60 */ ufs2_daddr_tdi_extb[NXADDR]; /* 96: External attributes block. */ /* 0x70 */ ufs2_daddr_tdi_db[NDADDR]; /* 112: Direct disk blocks. */ /* 0xD0 */ ufs2_daddr_tdi_ib[NIADDR]; /* 208: Indirect disk blocks. */ /* 0xE8 */ int64_t di_spare[3]; /* 232: Reserved; currently unused */ }; Листинг 5. Структура direct, отвечающая за хранение имен файлов и директорий struct direct { /* 0x00 */ u_int32_t d_ino; /* inode number of entry */ /* 0x04 */ u_int16_t d_reclen; /* length of this record */ /* 0x06 */ u_int8_t d_type; /* file type, see below */ /* 0x07 */ u_int8_t d_namlen; /* length of string in d_name */ /* 0x08 */ char d_name[MAXNAMLEN + 1]; /* name with length <= MAXNAMLEN */ }; ----------------------------------------------------------------------------------------------------------------- Реинкарнация данных II: memo-поля Сергей Супрунов Листинг 1. Файл memo2pg.prg (FoxPro) close databases * Это – комментарий с начала строки && А так выделяются комментарии в произвольном месте строки use wmem && Открываем таблицу с memo-полями m.delimiter = chr(9) && символ Tab m.txf = fcreate('memo2pg.txt') scan * Текстовое поле – экранируем разделители и символ «\» m.descr = strtran(Descr, '\', '\\') m.descr = strtran(m.descr, m.delimiter, ; '\' + m.delimiter) * В memo-поле дополнительно экранируем символы конца строки (ASCII-коды 10 и 13) m.memfld = strtran(Memfld, '\', '\\') m.memfld = strtran(m.memfld, m.delimiter, ; '\' + m.delimiter) m.memfld = strtran(m.memfld, chr(13), ; '\' + chr(13)) m.memfld = strtran(m.memfld, chr(10), ; '\' + chr(10)) * Записываем результат в файл, разделяя поля символом, хранящимся в переменной m.delimiter =fputs(m.txf, m.descr + ; m.delimiter + ; m.memfld) endscan =fclose(m.txf) wait window 'Finished.' Листинг 2. Фрагмент сценария dbf2pg.py, добавленные строки .. .. .. for i in range(num): fld = dbf.read(fields[i].len) # Добавлено: vvvvvvv if fields[i].type == 'M': fld = memo2pg(fld) # ----------^^^^^^^ if fields[i].type == 'D': fld = fld[:4] + '-' + fld[4:6] + '-' + fld[6:] .. .. .. Листинг 3. Фрагмент сценария dbf2pg.py, функция memo2pg def memo2pg(startblock): # Номер блока преобразуем в число startblock = int(startblock) fpt = open(basetabname + '.fpt', 'rb') fpt.read(6) # Считываем размер блока blocksize = int(ord(fpt.read(1)) * 256 + ord(fpt.read(1))) # Смещаемся к началу блока данных fpt.seek(blocksize * startblock) fpt.read(4) # Считываем размер поля данных fieldsize = ord(fpt.read(1)) * 16777216 + ord(fpt.read(1)) * 65536 + ord(fpt.read(1)) * 256 + ord(fpt.read(1)) # Читаем данные data = fpt.read(fieldsize) fpt.close() # Перекодировка, экранирование и проч. data = unicode(data, 'cp866').encode('koi8-r') data = data.replace('\\', '\\\\') data = data.replace('\x0A', '\\' + '\x0A') data = data.replace('\x0D', '\\' + '\x0D') data = data.replace(delimiter, '\\' + delimiter) return data Листинг 4. Фрагмент сценария dbf2pg.py, запись строки в файл .. .. .. # print line[:-1] outfile.write(line[:-1] + '\r\n') .. .. .. ----------------------------------------------------------------------------------------------------------------- Почему MS SQL медленно работает? Ищем причины Юлия Шабунио Скрипт 1 if ( select object_id( 'tempdb..#LOCK' ) ) is not null drop table #LOCK go -- В вашей версии SQL Server формат временной таблицы может быть другим, проверьте вывод sp_lock. create table #LOCK ( spid int , dbid int , ObjId int , IndId int , Type varchar(4) , Resource varchar(16) , Mode varchar(8) , Status varchar(6) ) insert into #LOCK exec sp_lock -- Какие процессы ожидают захвата каких ресурсов. select count(*) as LockCnt, left(o.name, 32 ) as ObjectName , l.Status, l.Type, l.Mode, l.spid , max(Resource) as SampleResource , left(max(ss.loginame), 16 ) as loginname , max(ss.cmd) as cmd , max(ss.lastwaittype) as lastwaittype , left(max(ss.program_name), 32 ) as program_name , left(max(ss.hostname), 32) as hostname , max(ss.program_name) as full_program_name from #LOCK l , sysobjects o with (nolock) , master..sysprocesses ss with (nolock) where o.id = l.ObjId and l.spid = ss.spid and l.Status not in ( 'GRANT', 'CNVT') and l.dbid = db_id() group by o.name, l.Status, l.Type, l.Mode, l.spid -- Кто мешает выполняться процессам из предыдущего -- запроса, кто держит их ресурсы. select count(*) as LockCnt, left(o.name, 32 ) as ObjectName , l.Status, l.Type, l.Mode, l.spid , max(Resource) as SampleResource , left(max(ss.loginame), 16 ) as loginname , max(ss.cmd) as cmd , max(ss.lastwaittype) as lastwaittype , left(max(ss.program_name), 32 ) as program_name , left(max(ss.hostname), 32) as hostname , max(ss.program_name) as full_program_name from #LOCK l , sysobjects o with (nolock) , master..sysprocesses ss with (nolock) where o.id = l.ObjId and l.spid = ss.spid and l.dbid = db_id() and l.Status in ( 'GRANT', 'CNVT') and exists ( select * from #LOCK l2 where l2.Status not in ( 'GRANT', 'CNVT') and l2.dbid = db_id() and l.ObjId = l2.ObjId and l.Resource = l2.Resource ) group by o.name, l.Status, l.Type, l.Mode, l.spid Скрипт 2 select count(*) as LockCnt, left(o.name, 32 ) as ObjectName , l.Status, l.Type, l.Mode, l.spid , max(Resource) as SampleResource , left(max(ss.loginame), 16 ) as loginname , max(ss.cmd) as cmd , max(ss.lastwaittype) as lastwaittype , left(max(ss.program_name), 32 ) as program_name , left(max(ss.hostname), 32) as hostname , max(ss.program_name) as full_program_name from #LOCK l , sysobjects o with (nolock) , master..sysprocesses ss with (nolock) where o.id = l.ObjId and l.spid = ss.spid and l.dbid = db_id() and l.spid = @spid --and program_name like '%0x08989EF05DAC704E94F6D25A2EB2FB75%' group by o.name, l.Status, l.Type, l.Mode, l.spid select convert( varbinary(30), job_id), name from msdb..sysjobs order by name Скрипт 3 create function dbo.uniqueidentifier_to_varchar ( @u uniqueidentifier ) returns varchar(34) as begin declare @binary varbinary(16), @i int , @res varchar(34), @byte smallint , @hex char(2) select @binary = convert( varbinary(16), @u ) , @i = 1, @res = '0x' while ( @i <= 16 ) begin select @byte = substring(@binary, @i, 1) select @hex = case when @byte/16 < 10 then char( ascii('0') + @byte/16 ) else char( ascii('A') + @byte/16 - 10 ) end + case when @byte%16 < 10 then char( ascii('0') + @byte%16 ) else char( ascii('A') + @byte%16 - 10 ) end select @res = @res + @hex, @i = @i + 1 end return @res end select name from msdb..sysjobs where dbo.uniqueidentifier_to_varchar( job_id ) = '0x07E7726D989CCA4E9103F874F473C2AF' select * from master..sysprocesses with (nolock) , msdb..sysjobs with (nolock) where program_name like '%' + dbo.uniqueidentifier_to_varchar(job_id) + '%' -- Этот запрос возвращает всю информацию о запущенных в данный момент заданиях, включая их названия, sp_id, -- время запуска и остальную информацию из master..sysprocesses и msdb..sysjobs dbcc inputbuffer( <Номер процесса> ) Скрипт 4 select top 10 physical_io/(datediff( second, login_time, dateadd( second, 2, getdate()) ) ) , physical_io, spid , datediff( second , login_time , dateadd( second, 2, getdate()) ) , program_name, * from master..sysprocesses order by physical_io/(datediff( second , login_time , dateadd( second, 2, getdate()) ) ) desc Скрипт 5 -- Для того чтобы посчитать процессоры и логические диски и получить список доступных счётчиков, раскомментируйте -- следующие запросы: exec master..xp_cmdshell 'typeperf -qx \Processor ' и exec master..xp_cmdshell 'typeperf -qx \PhysicalDisk' exec master..xp_cmdshell 'typeperf -sc 10 "\Processor(_Total)\% Processor Time" "\PhysicalDisk(1 D:)\% Disk Time" "\PhysicalDisk(1 D:)\Avg. Disk Queue Length" "\PhysicalDisk(1 D:)\% Idle Time" "\SQLServer:Buffer manager\Checkpoint pages/sec" ' ----------------------------------------------------------------------------------------------------------------- Система вещания на основе Windows Media Services 9 Часть 2 Михаил Платов cscript WMCmd.vbs -input "e:\music_mp3" -output "e:\music_wma" -a_mode 1 -profile a32 wms.local.ru:7979 ----------------------------------------------------------------------------------------------------------------- Автоматизация MS Windows, или AutoIt как мечта эникейщика Часть 2 Алексей Барабанов AutoItSetOption ( "WinTitleMatchMode", 2 ) AutoItSetOption ( "WinDetectHiddenText", 1 ) WinMinimizeAll ( ) Sleep ( 1000 ) Run ( 'Thunderbird_Setup_1.0.exe' ) WinWait ( 'Mozilla Thunderbird Установка' ) Send ( '{ENTER}' ) MsgBox ( 0, 'AutoIt', 'Done' ) Exit AutoItSetOption ( "WinTitleMatchMode", 2 ) AutoItSetOption ( "WinDetectHiddenText", 1 ) ; open free desktop WinMinimizeAll ( ) Sleep ( 1000 ) Run ( 'Thunderbird_Setup_1.0.exe' ) ;Run ( $CmdLine[1] ) WinWait ( 'Mozilla Thunderbird Установка' ) Send ( '{ENTER}' ) WinWait ( 'Установка Thunderbird - Лицензионное соглашение' ) Send ( '{TAB}{SPACE}{ENTER}' ) WinWait ( 'Установка Thunderbird - Тип установки' ) Send ( '{ENTER}' ) WinWait ( 'Выбор компонентов' ) Send ( '{ENTER}' ) ; 'Установка Mozilla Thunderbird- Начало установки' WinWait ( 'Установка Mozilla Thunderbird- Завершение' ) Send ( '{SPACE}{ENTER}' ) ;MsgBox ( 0, 'AutoIt', 'Done' ) Exit AutoItSetOption ( "WinTitleMatchMode", 2 ) AutoItSetOption ( "WinDetectHiddenText", 1 ) AutoItSetOption ( "SendAttachMode", 1 ) ; open free desktop WinMinimizeAll ( ) Sleep ( '1000' ) ; network connection wizard Run ( @ComSpec & " /c rundll32.exe netshell.dll,StartNCW" ) ; 1 If WinWaitActive ( 'Мастер новых подключений','','10' ) == 0 Then Exit EndIf Send ( '{ENTER}' ) ; 2 WinWaitActive ( 'Мастер новых подключений', 'Подключить к Интернету','5' ) Send ( '{DOWN}{ENTER}' ) ; 3 WinWaitActive ( 'Мастер новых подключений', 'Создать подключение:','5' ) Send ( '{DOWN}{ENTER}' ) ; 4 WinWaitActive ( 'Мастер новых подключений', 'Введите в следующем поле имя для этого подключения','5' ) $pptpname = 'Office VPN' Send ( $pptpname & '{ENTER}' ) ; 5 WinWaitActive ( 'Мастер новых подключений', 'Введите имя узла или','5' ) $pptphost = 'office.enterprise.domain' Send ( $pptphost & '{ENTER}' ) ; 6 If WinWaitActive ( 'Мастер новых подключений', 'Успешно завершено создание следующего подключения:', '5' ) == 1 Then Send ( '{SPACE}{ENTER}' ) EndIf Exit # zip -9 setup_pptp.exe.zip setup_pptp.exe # cp setup_pptp.exe.zip ~/bin #!/bin/sh FCHAP=/etc/ppp/chap-secrets UNAME=$1 UIP=$2 ( [ "$UNAME" != "" ] && [ "$UIP" != "" ] ) || { echo "Use as : $SELF "; exit -1 ; } D=`cat $FCHAP | grep -e "^$UNAME[[:space:]]"` [ "$D" == "" ] || { echo "User \"$UNAME\" already in database"; exit -1 ; } T=`getent passwd | grep ^$UNAME:` [ "$T" != "" ] || { echo "Chosed =$UNAME not found in passwd"; exit -1 ; } PSW=`pwgen -c -n 9 1` H="officepptp" echo -e "$UNAME\t\"$H\"\t$PSW\t\"$UIP\"" >> $FCHAP SRV=office.enterprice.domain cat <0 then user.DeleteFolder(path) Temp= "Folder " + path + " Deleted" Else Temp= "Folder " + path + " is Absent " End If MsgBox Temp Set PC_Name="1000pc" Set Share_Name="Share1" Set Folder_Path="c:\Folder1" Set Description_Name="Shared Folder #1" Set object=GetObject("WinNT://" & short_winnt_name &"/" & PC_Name &"/LanmanServer") Set element=object.Create("fileshare", Share_Name) element.Path= Folder_Path element.Description= Description_Name element.MaxUserCount =10 element.SetInfo Set PC_Name="1000pc" Set Share_Name="Share1" Set Folder_Path="c:\Folder1" Set Description_Name="Shared Folder #1" Set object=GetObject("WinNT://" & short_winnt_name &"/" & PC_Name &"/LanmanServer") Call object.Delete("fileshare", Share_Name) regsvr32.exe /s ADsSequrity.dll Set sec = CreateObject("ADsSecurity") Set sd = sec.GetSecurityDescriptor("FILE://c:\folder") Set dacl = sd.DiscretionaryAcl For Each ace In dacl Wscript.Echo cstr(ace.Trustee)+" " + cstr(ace.AccessMask) + " " + cstr(ace.AceType) + chr(13)+chr(10) Next Wscript.Echo dacl.AceCount Set sec = CreateObject("ADsSecurity") Set sd = sec.GetSecurityDescriptor("FILE://c:\Folder") Set dacl = sd.DiscretionaryAcl Set ace = CreateObject("AccessControlEntry") ace.Trustee = "Domain\Administrator" ace.AccessMask = &h20000000 ace.AceType = &h0 ace.AceFlags = &h3 dacl.AddAce ace1 sd.DiscretionaryAcl = dacl sec.SetSecurityDescriptor sd set dacl=nothing set sec=nothing Set sec = CreateObject("ADsSecurity") Set sd = sec.GetSecurityDescriptor("FILE://c:\Folder") Set dacl = sd.DiscretionaryAcl Set ace1 = CreateObject("AccessControlEntry") ace1.Trustee = "domain\user1" ace1.AccessMask = &h20000000 ace1.AceType = &h0 ace1.AceFlags = &h3 dacl.AddAce ace1 for i=0 to 10000000 next Set ace2 = CreateObject("AccessControlEntry") ace2.Trustee = "domain\user2" ace2.AccessMask = &h20000000 ace2.AceType = &h0 ace2.AceFlags = &h3 dacl.AddAce ace2 sd.DiscretionaryAcl = dacl sec.SetSecurityDescriptor sd set dacl=nothing set sec=nothing Q = Timer + x ‘ x – количество секунд задержки Do Loop Until Timer >= Q Set sec = CreateObject("ADsSecurity") Set sd = sec.GetSecurityDescriptor("FILE://c:\2") Set dacl = sd.DiscretionaryAcl For Each ace In dacl If (ace.Trustee="EveryOne") dacl.RemoveAce ace end if Next sd.DiscretionaryAcl = dacl set dacl=nothing set sec=nothing If Not FS.FolderExists(strFolder&user.name) Then FS.CreateFolder(strFolder&user.name) End If On Error Resume Next ShareServiceObj.Delete "Fileshare", user.name&"$" set NewShare = ShareServiceObj.Create("Fileshare",user.name&"$") Set sec = CreateObject("ADsSecurity") Set sd = sec.GetSecurityDescriptor("FILE://"& strShare) Set dacl = sd.DiscretionaryAcl For Each ace In dacl If (ace.Trustee="EveryOne") dacl.RemoveAce ace end if Next Set ace1 = CreateObject("AccessControlEntry") Ace1.Trustee = short_winnt_name +" \ "+ user.name ace1.AccessMask = &h10000000 ace1.AceType = &h0 ace1.AceFlags = &h3 dacl.AddAce ace1 for i=0 to 10000000 next Set ace2 = CreateObject("AccessControlEntry") ace2.Trustee = short_winnt_name +" \ "+ user.name ace2.AccessMask = &h20+&h1000+&h40000000+&80000000 ace2.AceType = &h0 ace2.AceFlags = &h3 dacl.AddAce ace2 sd.DiscretionaryAcl = dacl sec.SetSecurityDescriptor sd set dacl=nothing set sec=nothing NewShare.Path = strShare&user.name NewShare.MaxUserCount = 10 NewShare.setinfo ----------------------------------------------------------------------------------------------------------------- Строим защищённую беспроводную сеть: WPA-Enterprise, 802.1x EAP-TLS Андрей Платонов # ./config shared --prefix=/usr/local/openssl # make # make install # openssl gendh > dh # dd if=/dev/random of =random count=2 clients.conf client 192.168.0.220 { # IP-адрес точки доступа # Секретное слово, которое задаётся на точке доступа secret = 12345 shortname = D-Link_DWL-2100AP nastype = other } client 192.168.0.219 { # IP-адрес точки secret = 54321 # Секретное слово shortname = D-Link_DWL-2700AP nastype = other } # и т.д. eap.conf # В самом начале, после « eap {» default_eap_type = tls tls { private_key_password = whatever private_key_file = ${raddbdir}/certs/cert-srv.pem certificate_file = ${raddbdir}/certs/cert-srv.pem CA_file = ${raddbdir}/certs/demoCA/cacert.pem dh_file = ${raddbdir}/certs/dh random_file = ${raddbdir}/certs/random fragment_size = 1750 } radiusd.conf bind_address = 192.168.0.222 port = 1812 log_auth = yes # для отладки log_auth_badpass = yes log_auth_goodpass = yes SSL=/usr/local/openssl echo “newreq.pem” | /usr/local/openssl/ssl/misc/CA.pl -newca Файл CA_users.all 1| openssl req -new -keyout newreq.pem -out newreq.pem -days 730 -passin pass:whatever -passout pass:whatever 2| openssl ca -policy policy_anything -out newcert.pem -passin pass:whatever -key whatever -extensions xpclient_ext -extfile xpextensions -infiles newreq.pem 3| openssl pkcs12 -export -in newcert.pem -inkey newreq.pem -out user1.p12 -clcerts -passin pass:whatever -passout pass:user1_password 4| openssl pkcs12 -in user1.p12 -out user1.pem -passin pass:user1_password -passout pass:user1_password 5| openssl x509 -inform PEM -outform DER -in user1.pem -out user1.der radius# openssl ca -revoke user2.pem radius# openssl ca -gencrl -out ca.crl radius# openssl crl -in ca.crl -text -noout cat cacert.pem ca.crl > ca.pem # здесь мы изменили cacert.pem на ca.pem CA_file = ${raddbdir}/certs/ca.pem CA_path = ${raddbdir}/certs #добавляем эту строку check_crl = yes # и эту строку ----------------------------------------------------------------------------------------------------------------- Контролируем безопасность сети с помощью OSSIM Сергей Яремчук # /etc/init.d/mysqld start # mysqladmin -u root password root_password # mysql -u root -p # cd $OSSIM_PATH/db # cat create_mysql.sql | mysql -u root ossim -p # cat ossim_data.sql snort_nessus.sql realsecure.sql | mysql -u root ossim -p # cp $OSSIM_PATH/contrib/debian/framework/ossim.conf /etc/ossim/ ################################################# # OSSIM db configuration ################################################# ossim_type=mysql ossim_base=ossim ossim_user=root ossim_pass=root_passwd ossim_host=localhost ossim_port=3306 # tar –xzvf snort-2.3.2.tar.gz # cd snort 2.3.2 # cat ./schemas/create_mysql | mysql -u root -p snort # cd /var/www # tar -xzvf /tmp/acid-0.9.6b23.tar.gz # cd acid # patch -p1 < $OSSIM_PATH /contrib/acid.patch $alert_dbname = "snort"; $alert_host = "localhost"; $alert_port = "3306"; $alert_user = "root"; $alert_password = "root_passwd "; # cd $OSSIM_PATH/contrib/spade/Spade-040223.1.tgz # tar -xzvf Spade-040223.1.tgz # cd Spade-040223.1 # vi Makefile # make # cd snort-2.3.2 # patch -p0 < $OSSIM_PATH/contrib/snort-2.1-ossim.patch # ./configure --with-mysql # make # make install # mkdir /etc/snort # cp snort-2.3.2/etc/snort.conf /etc/snort/ # cp snort-2.3.2/etc/unicode.map /etc/snort/ # cp $OSSIM_PATH/contrib/spade/spade.conf.sample /etc/snort/spade.conf ################################### # Step #3: Configure output plugins ################################### output alert_syslog: LOG_AUTH LOG_ALERT output database: alert, mysql, user=root dbname=snort host=localhost logfile=fast.log Includespade.conf # ######################## # # SNORT db configuration # # (look at snort.conf) # ######################## snort_type=mysql snort_base=snort snort_user=root snort_pass=root_passwd snort_host=localhost snort_port=3306 # cd $OSSIM_PATH/ # ./autogen.sh # cd src/ # make # ossim-server -d -c /etc/ossim/server/config.xml # cat /var/log/ossim/server.log ################### # Base dir ################### data_dir=/opt/ossim base_dir=/var/www/ossim # я переместил подкаталог www поближе к остальным файлам веб-сервера ossim_interface=eth0 ossim_link=/ossim/ adodb_path=/usr/share/adodb/ phpgacl_path=/var/www/phpgacl/ jpgraph_path=/usr/share/jpgraph/ # cp $OSSIM_PATH/etc/httpd/ossim.conf /etc/httpd/conf/ Alias /ossim "/var/www/ossim" php_value include_path .:/usr/share/ossim/php/ AuthType Basic AuthName OSSIM AuthUserFile /var/www/ossim-users Require valid-user AllowOverride None # htpasswd -c /var/www/ossim-users ossim rrdtool_path=/usr/bin/ rrdtool_lib_path=/usr/lib/perl5/ # tar –xvzf mrtg-2.10.5.tar.gz # cd mrtg-2.10.5/bin # patch -p0 < $OSSIM_PATH/contrib/mrtg/mrtg.diff # mkdir /var/www/mrtg # cd /var/www/mrtg # mkdir host_qualification net_qualification global_qualification level_qualification WorkDir: /var/www/mrtg Include: /var/www/mrtg/hosts/host_qualification.cfg Include: /var/www/mrtg/nets/net_qualification.cfg Include: /var/www/mrtg/global/global_qualification.cfg mrtg_rrd_files_path=/var/www/mrtg rrdpath_host=/var/www/mrtg/host_qualification/ rrdpath_net=/var/www/mrtg/net_qualification/ rrdpath_global=/var/www/mrtg/global_qualification/ font_path=/opt/ossim/contrib/fonts # ln -s $OSSIM_PATH/include/ossim_conf.pm /usr/lib/perl5/ use lib "/opt/ossim/include"; # cp $OSSIM_PATH/scripts/draw_graph.pl /var/www/cgi-bin/ # cd $OSSIM_PATH/mrtg # ./launch-mrtg # crontab -e # cp $OSSIM_PATH/etc/cron.d/ossim /etc/cron.d/ # cp $OSSIM_PATH/scripts/control_panel.py /usr/local/bin/ # chmod +x /usr/local/bin/control_panel.py # tar –xzvf ntop-3.1.tar.gz # cd ntop-3.1/ # patch -p0 < $OSSIM_PATH/contrib/ntop/ntop-3.1-ossim.diff ntop_link=http://your_ntop_host:3000/ rrdpath_ntop=/var/lib/ntop/rrd # tar -xzvf fpdf153.tgz # cd fpdf153 # cp fpdf.php /usr/share/ossim/php/ nessus_user=ossim nessus_pass=your_password nessus_host=localhost nessus_port=1241 nessus_path=/usr/bin/nessus nessus_rpt_path=/var/www/ossim/vulnmeter/ # /usr/sbin/nessus-adduser # nessus-update-plugins # perl $OSSIM_PATH/scripts/update_nessus_ids.pl # cd $OSSIM_PATH/agent # ln -sf `pwd` /usr/local/bin # python setup.py install # mkdir /etc/ossim/agent # cp $OSSIM_PATH/etc/agent/config.xml /etc/ossim/agent # ossim-agent -v 192.168.0.10 40001 /var/log/ossim /etc/init.d/snort start /etc/init.d/snort stop fast eth0 192.168.0.10 /var/log/snort/fast.log tcptrack -i eth0 -P 40003 -F 10 –D /usr/bin/tcptrack -i eth0 -P 40003 -F 10 –D ossim-agent 40001/tcp #ossim-agent ossim-agent 40001/udp #ossim-agent # ossim-agent -d -c /etc/ossim/agent/config.xml # mysql -u root -p ----------------------------------------------------------------------------------------------------------------- Свободная информационная система для школ Centre Сергей Яремчук # mv /var/www/html/Centre-v.1.4 /var/www/html/centre # /etc/init.d/postgresql restart # psql -U postgres template1 # psql -U postgres centre < /var/www/html/centre/centre.sql > centre.log // Database Setup $DatabaseType="postgres"; // oracle, postgres $DatabaseANSI=true; // ANSI compliant flag. $DatabaseServer="127.0.0.1"; // postgres = host, // oracle=SID $DatabaseUsername="postgres"; $DatabasePassword="password"; $DatabaseName="centre"; $DatabasePort="5432"; // Server Names and Paths $CentrePath="/var/www/html/сentre/"; $StudentPicturesPath = ="/var/www/html/сentre/pictures"; $CentreTitle = 'Centre School Information System'; ----------------------------------------------------------------------------------------------------------------- Базовая HTTP-авторизация – защита от честных людей Алексей Мичурин AuthName "How about authorization?" AuthType Basic Require valid-user AuthUserFile /путь/к/файлу/.htpasswd ErrorDocument 401 /путь/документ_или_сценарий ErrorDocument 401 /cgi-bin/401.cgi #!/bin/sh echo $REMOTE_ADDR ${REMOTE_USER:-nouser} `date` >>401.log cat <<'TEXT' Content-Type: text/html 401

Auth. Req.

TEXT #!/bin/sh if [ ${REDIRECT_STATUS:-)} = 401 ] then echo $REMOTE_ADDR ${REMOTE_USER:-nouser} `date` >>401.log if [ ${REMOTE_USER:-D} != D ] then mess='Что-то вы зачастили неудачно авторизоваться!' else mess='Ошибка! (первая)' fi else mess='Так этот скрипт вызывать нельзя' fi echo "Content-Type: text/html $mess

$mess

" #!/bin/sh cat <<'TEXT' Status: 200 Content-Type: text/html

вы не авторизовались и не авторизуетесь

TEXT #!/usr/bin/perl use strict; my $LOGFILE='401.log'; my $lastlog = $^T-(stat $LOGFILE)[9]; if ($lastlog > 10) { my $log=$ENV{'REMOTE_ADDR'}. ($ENV{'REMOTE_USER'} or 'nouser'). localtime($^T)."\n"; $log.=join('', map {" $_ $ENV{$_}\n"} sort keys %ENV); open F, '>>'.$LOGFILE or die; print F $log; close F; # Этот документ будет выслан ещё до того, как пользователь ввёл пароль! print <<'TEXT'; Content-Type: text/html Документ 401

Доступ закрыт

Можно было авторизоваться, но вы допустили ошибку при наборе пароля или имени. Теперь регистрация заблокирована на 10 секунд.

TEXT } else { # этот документ пользователь увидит: # - и если не вовремя пришёл # - и если ввёл неправильный пароль # анализируйте $REMOTE_USER для разделения этих ситуаций print <<'TEXT'; Status: 200 Content-Type: text/html Документ 200

Доступ вообще закрыт

Вы не можете авторизоваться вообще. Подождите 10 секунд.

TEXT }