[linux] chattr, lsattr

TA/Common 2012. 12. 13. 16:47

$> chattr +i 파일이름

파일을 수정도 내용추가도 삭제도 할 수 없다.

 

$> chattr +a 파일이름

파일을 내용만 계속 추가할 수 있고 파일명수정이나 삭제는 할 수 없다.

 

$> lsattr

chattr로 인해 파일 속성이 변경되었는지를 확인한다.

 

* 파일의 보호해제 방법은 각각,

chattr -i 파일이름

chattr -a 파일이름

 

*chattr, lsattr 은 오직 root 만이 사용할 수 있다.

Posted by 옥탑방람보
,

여기에서는 /var/log/secure 에 대한 로그파일만 대상으로 함.

(첨부파일에 syslog에 대해 자세히 나와 있음)

 

1. syslog에서 떨어지는 secure 파일 위치 : /var/log/secure

 

2. logrotate 사용하여 떨어지는 secure 파일 제어

    $> vi /etc/logrotate.d/syslog

        /var/log/secure {

             sharedscripts

             postrotate

                 /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true

                 /bin/kill -HUP `cat /var/run/rsyslogd.pid 2> /dev/null` 2> /dev/null || true

             endscript

             rotate 31                      # 한달분량 저장

             daily                              # 매일 파일 분리

             create 600 root root

          }

    $> cat /etc/cron.daily/logrotate    # 매일 실행

    /usr/bin/logroate /etc/logratate.conf

3. 서버내 이중저장

    $> vi /etc/syslog.conf

        authpriv.*                  /var/log/secure

        authpriv.*                  /root/logBackup/secure

    $> /etc/init.d/syslog restart

4. 서버 외부 저장

    <로그보낼서버>

    $> vi /etc/syslog.conf

       authpriv.*                   @XXX.XXX.XXX.XXX

    $> /etc/init.d/syslog restart

    <로그받을서버>

    $> vi /etc/sysconfig/syslog 파일내에 설정된

        SYSLOGD_OPTIONS=“-r –m 0” 로 변경

    $> /etc/init.d/syslog restart

    * 두 서버 모두의 hosts 파일 설정으로 hostname으로 기록 가능

5. /var/log/secure 파일 파싱

    $> vi montVarLogSecure.py

    #!/usr/bin/env python

    import sys, re, os, time

    def getWho():

        whosys = os.popen( 'who' ).read()

        return whosys

    def getScreen():

        screensys = os.popen( "screen -wls | awk -F 'in' '{print $1}'" ).read()

        return screensys

    def sucLogin( logfile ):

        loginsys = os.popen( "cat "+logfile+" | grep 'Accepted' | awk '{print $1 \" \" $2 \" \" $3 \" User: \" $9 \" \" }'" ).read()

    #   print "cat "+logfile+" | grep 'Accepted' | awk '{print $1 \" \" $2 \" \" $3 \" User: \" $9 \" \" }'"

        return loginsys

    def sudoSucLogin( logfile ):

        sudologin = os.popen( "cat "+logfile+" | grep 'session opened for user root' | awk '{print $1 \" \" $2 \" \" $3 \" Sudo User: \" $13 \" \" }' " ).read()

        return sudologin

    def invalidUser( logfile ):

        invalid = os.popen( "cat "+logfile+" | grep 'Invalid user' " ).read()

        return invalid

    def failedPassword( logfile ):

        failed = os.popen( "cat "+logfile+" | grep -v invaild | grep 'Failed password' ").read()

        return failed

    def refusedUser( logfile ):

        refused = os.popen( "cat "+logfile+" | grep 'refused' " ).read()

        return refused

    def deniedUser( logfile ):

        denided = os.popen( "cat "+logfile+" | grep -v cron | grep 'access denied\}Permission denied'" ).read()

        return denided

    def fatalNotices( logfile ):

        fatal = os.popen( "cat "+logfile+" | grep ssh | grep 'Permission denied\|fatal\|error' " ).read()

        return fatal

    def expireDate( logfile ):

        expire = os.popen( "cat "+logfile+" | grep 'changed password expiry\|expiration from' " ).read()

        return expire

    def top5ip( logfile ):

        top5 = os.popen( "awk 'gsub(\".*sshd.*Failed password for (invalid user )?\", \"\") {print $3}' "+logfile+" | sort | uniq -c | sort -rn | head -5" ).read()

        return top5

     try:

            if sys.argv[1:]:

                    logfile = sys.argv[1]

            else:

                    logfile = raw_input( "Please enter a log file to parse, e.g. /var/log/secure " )

            if sys.argv[2:]:

                    outpath = sys.argv[2]

            else:

                    outpath = raw_input( "Please enter a out path, 2.g. ~/logOut/ " )

            os.system( 'mkdir -p '+outpath )

            outfile = outpath + time.strftime( '%Y%m%d%H%M%S' )

            ofh = open( outfile,'w' )

            print >> ofh, "# Who is online: "

            print >> ofh, getWho()

            print >> ofh, "# Active Screen Sessions: "

            print >> ofh, getScreen()

            print >> ofh, "# List out successful ssh login attempts: "

            print >> ofh, sucLogin( logfile )

            print >> ofh, "# List out successful ssh login attempts from sudo users: "

            print >> ofh, sudoSucLogin( logfile )

            print >> ofh, "# List out ssh login attempts from non-existing and unauthorized user accounts: "

            print >> ofh, invalidUser( logfile )

            print >> ofh, "# List out ssh login attempts by authorized ssh accounts with failed password: "

            print >> ofh, failedPassword( logfile )

            print >> ofh, "# List out refused ssh login attempts: "

            print >> ofh, refusedUser( logfile )

            print >> ofh, "# List out denied ssh login attempts: "

            print >> ofh, deniedUser( logfile )

            print >> ofh, "# List out fatal and miscellaneous ssh session/restart notices: "

            print >> ofh, fatalNotices( logfile )

            print >> ofh, "# List out all successful system account expireation date changes: "

            print >> ofh, expireDate( logfile )

            print >> ofh, "# Top 5 attacker IP adresses: "

            print >> ofh, top5ip( logfile )

            ofh.close()

    except IOError, (errno, strerror):

            print "I/O Error (%s) : %s" % (errno,strerror)

     

    $> vi /etc/cron.daily/exe.cron

    python /usr/local/bin/montVarLogSecure.py /var/log/secure ~/logOut/

 

Posted by 옥탑방람보
,

윈도우PC 에서 리눅스 서버으로 SSH 접속 시 X11 활성화 방법

 

1.     SSH X11 Forwarding Enable

A.     $> vi /etc/ssh/sshd_config

X11Forwarding yes

B.      $> /etc/init.d/sshd reload

2.     Xming 설치 및 실행

A.     다운로드: http://sourceforge.net/projects/xming/

B.      설치

C.      실행 실행여부확인은 트레이아이콘 생성이 되어 있으면 완료

3.     Xshell 로 접속시 (Xming 실행 후)

A.     다운로드: http://www.netsarang.co.kr/download/main.html

B.      설치

C.      파일 열기 열고자 하는 항목에서 우측클릭 등록정보 터널링 – “X11 연결을 다음으로 포워드합니다.” 체크 – X DISPLAY 선택 – localhost:0

D.     해당항목 접속

4.     Putty 로 접속시 (Xming 실행 후)

A.     다운로드: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

B.      설치

C.      실행 – Category 에서 SSH 밑에 X11 선택 – “Enable X11 forwarding” 체크 – X display location 항목에 localhost:0 입력

D.     해당항목 접속

 

Posted by 옥탑방람보
,

1. 패스워드 사용 기간 제한

$> vi /etc/login.defs

PASS_MAX_DAYS 90

PASS_MIN_DAYS 0

PASS_MIN_LEN   8

PASS_WARN_AGE  7

 

2. 계정 잠금 허용

$> vi /etc/default/useradd

INACTIVE=0

 

3. 기타 비밀번호 설정

$>vi /etc/pam.d/system-auth

auth        required      pam_env.so

auth        required      pam_tally.so per_user

auth        sufficient    pam_unix.so nullok try_first_pass

auth        requisite     pam_succeed_if.so uid >= 500 quiet

auth        required      pam_deny.so

 

account     required      pam_unix.so

account     sufficient    pam_succeed_if.so uid < 500 quiet

account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3 minlen=8 ucredit=-1 dcredit=-1 ocredit=-1 lcredit=-1

password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok

password    required      pam_deny.so

 

session     optional      pam_keyinit.so revoke

session     required      pam_limits.so

session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid

session     required      pam_unix.so

 

(설명)

auth        required      pam_tally.so per_user

--> faillog 설정에 따름.

password    requisite     pam_cracklib.so try_first_pass retry=3 minlen=8 ucredit=-1 dcredit=-1 ocredit=-1 lcredit=-1

-->

retry=N : 패스워드 입력 실패 시 재시도횟수             

difok=N : 기존 패스워드와 비교. 기본값10 (50%)             

minlen=N :  크레디트를 더한 패스워드최소길이               

dcredit=N : 숫자에 주어지는 크레디트값. 기본 1             

udredit=N : 영어대문자에 주어지는 크레디트값               

lcredit=N : 영어 소문자에 주어지는 크레디트값              

ocredit=N : 숫자, 영어대/소문자를 제외한 기타문자

(각 항목에서 -1 값을 주면 반드시 해당하는 문자를 포함시켜야 함. 즉 dcredit=-1 이라면 패스워드에 숫자가 반드시 포함되어야 함.)

 

4. 계정 접속 제한 설정

*** faillog -m 3 시 /var/log/faillog 파일이 128G 로 되는 버그 fix 방법 ***

$> patch < shadow-4.0.17-setmax.path

    파일위치: /usr/bin/faillog

$> faillog -u userid -m 3  #계정을 3번까지 잘못입력하는 것 허용

$> faillog -u root -m 0   #root 계정은 max 값 0로 주어 제한 없이 사용가능

 

5. 잠긴 계정 활성화

$> faillog -u [userId] -r

 

6. root의 경우 해당 경우에서 제외

$> faillog -u root -m 0

 

 

 

 

 

 

--------------- 여기서 부터는 과거 자료 ------------------------------------------------

 

1. 패스워드 사용 기간 제한

$> vi /etc/login.defs

PASS_MAX_DAYS 90

PASS_MIN_DAYS 0

PASS_MIN_LEN   8

PASS_WARN_AGE  7

 

2. 계정 잠금 허용

$> vi /etc/default/useradd

INACTIVE=0

 

3. 기타 비밀번호 설정

$>vi /etc/pam.d/system-auth

auth        required      pam_env.so

auth        required      pam_tally.so onerr=fail deny=3 reset

auth        sufficient    pam_unix.so nullok try_first_pass

auth        requisite     pam_succeed_if.so uid >= 500 quiet

auth        required      pam_deny.so

 

account     required      pam_unix.so

account     sufficient    pam_succeed_if.so uid < 500 quiet

account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3 minlen=8 ucredit=-1 dcredit=-1 ocredit=-1 lcredit=-1

password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok

password    required      pam_deny.so

 

session     optional      pam_keyinit.so revoke

session     required      pam_limits.so

session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid

session     required      pam_unix.so

 

(설명)

auth        required      pam_tally.so onerr=fail deny=3 reset

--> 3번이상 접근실패시 계정 잠금

password    requisite     pam_cracklib.so try_first_pass retry=3 minlen=8 ucredit=-1 dcredit=-1 ocredit=-1 lcredit=-1

-->

retry=N : 패스워드 입력 실패 시 재시도횟수             

difok=N : 기존 패스워드와 비교. 기본값10 (50%)             

minlen=N :  크레디트를 더한 패스워드최소길이               

dcredit=N : 숫자에 주어지는 크레디트값. 기본 1             

udredit=N : 영어대문자에 주어지는 크레디트값               

lcredit=N : 영어 소문자에 주어지는 크레디트값              

ocredit=N : 숫자, 영어대/소문자를 제외한 기타문자

(각 항목에서 -1 값을 주면 반드시 해당하는 문자를 포함시켜야 함. 즉 dcredit=-1 이라면 패스워드에 숫자가 반드시 포함되어야 함.)

 

4. 잠긴 계정 활성화

$> faillog -u [userId] -r

 

5. root의 경우 해당 경우에서 제외

$> faillog -u root -m 0

Posted by 옥탑방람보
,

1. Install Gtk rpm

http://rpm.pbone.net/index.php3/stat/4/idpl/17756735/dir/fedora_17/com/gtkmm24-2.24.2-3.fc17.x86_64.rpm.html

2. Install gparted

http://rpmfind.net/linux/rpm2html/search.php?query=gparted&submit=Search+...&system=fedora&arch=

Posted by 옥탑방람보
,

[ssh] ssh keep-alive tip

TA/Common 2012. 3. 27. 10:46

 

1. ssh -o TCPKeepAlive=yes mark@localhost

 

or

 

2.

Remember that

ServerAliveInterval

is limited by

ServerAliveCountMax

and that ServerAliveCountMax is set to 3 by default!

That is, if you set ServerAliveInterval to 60 and ServerAliveCountMax is left to default value (3), after the client has sent 3 keep alive packets it will disconnect. That makes 60 x 3 = 180 seconds.

So if you want more time away, you set ServerAliveInterval to 60 and ServerAliveCountMax to the numer you want (for example: 100). The client will send one keep alive packet every 0 seconds for 100 times or, if you prefer, 100 keep alive packets, one every 60 seconds. :D

You set this up in your $HOME/.ssh/config file.

Most of these options are explained in man ssh_config.

Thanks a lot to Cam for pointing us all in the right direction!!!!

Posted by 옥탑방람보
,

java.io.IOException: no locks available

 

마운트시 -o nolock 옵션 적용

$> mount -t nfs -o nolock

fstab에 적용

$> vi /etc/fstab

XXX:/storageDir /local nfs nolock 0 0

---------------------------------------------------------

<rocks clusters>

nfs 파일 시스템에서 파일 lock 이 되지 않을 때
아래와 같이 수정하고 nfs 데몬 재시작, nfslock 데몬 재시작
(예상 관련 데몬: portmap, autofs)

[system]$ cat /etc/auto.home
user01  -fstype=nfs,nolock 111.111.111.111:/data/home/user01

'TA > Common' 카테고리의 다른 글

[pam.d] 패스워드 복잡성 적용 방법  (1) 2012.12.13
[gparted] gparted 설치 (fedora17)  (0) 2012.12.13
[ssh] ssh keep-alive tip  (0) 2012.03.27
[nfs] nfs 서버와 클라이언트 계정 동기화 설정  (0) 2011.10.19
[linux] Standard I/O  (0) 2011.08.10
Posted by 옥탑방람보
,
> vi /etc/exports

root_squash, no_root_squash : NFS 서버에도 root 사용자가 있을 것이고, NFS 클라이언트에도 root가 있을 것이다. 그러나 두 root가 같은 root가 될 순 없다. NFS 클라이언트의 root가 NFS 서버의 root 권한을 가질 수 없다. 따라서 기본값은 root_squash로 클라이언트 root는 nobody와 같은 사용자로 맵핑되어 버린다. 서버와 클라언트의 root 사용자를 일치하도록 하려면 no_root_squash라고 적으면 된다.

all_squash, no_all_squash : 기본값은 no_all_squash로서 root를 제외한 일반 사용자 ID에 대해서는 서버와 클라이언트 UID가 동일한 사용자이며 동일한 권한을 갖는다고 생각한다. 이는 root에 대한 기본 처리값과 반대이다. 그러나 all_squash를 해버리면 모든 UID, GID를 무조건 익명 사용자 ID로 매핑해 버린다.

> nfs restart


======================

[Rocks-Discuss]Cannot write to user home on compute node

Tim Carlson tim.carlson at pnl.gov
Thu Feb 16 11:47:40 PST 2006


On Thu, 16 Feb 2006, Chuming Chen wrote:

Add no_root_squash to the options in /etc/exports and then restart the NFS 
services on the frontend.

Tim

Tim Carlson
Voice: (509) 376 3423
Email: Tim.Carlson at pnl.gov
Pacific Northwest National Laboratory
HPCaNS: High Performance Computing and Networking Services

> Hi,
>
> On the compute node, as the user, I can create file in my home. But as
> root, I failed. What would be wrong here?
>
> [chen at compute-0-0 ~]$ pwd
> /home/chen
> [chen at compute-0-0 ~]$ ls -l test
> ls: test: No such file or directory
> [chen at compute-0-0 ~]$ touch test
> [chen at compute-0-0 ~]$ ls -l test
> -rw-rw-r--  1 chen chen 0 Feb 16 13:50 test
>
> [root at compute-0-0 chen]# pwd
> /home/chen
> [root at compute-0-0 chen]# touch test
> touch: cannot touch `test': Permission denied
>
> Thanks a lot.
>
> Chuming Chen
>

Posted by 옥탑방람보
,

[linux] Standard I/O

TA/Common 2011. 8. 10. 17:10

Common Standard I/O Redirections

Function csh sh
Send stdout to file prog > file prog > file
Send stderr to file prog 2> file
Send stdout and stderr to file prog >& file prog > file 2>&1
Take stdin from file prog < file prog < file
Send stdout to end of file prog >> file prog >> file
Send stderr to end of file prog 2>> file
Send stdout and stderr to end of file prog >>& file prog >> file 2>&1
Read stdin from keyboard until c prog <<c prog <<c
Pipe stdout to prog2 prog | prog2 prog | prog2
Pipe stdout and stderr to prog2 prog |& prog2 prog 2>&1 | prog2

Posted by 옥탑방람보
,