How do I enable core dumps for everybody (모든 사용자 계정에 core dump 파일 활성화 하기)

Overview

In most Linux Distributions core file creation is disabled by default for a normal user. However, it can be necessary to enable this feature for an application (e.g. Oracle). For example, if you encounter an ORA-7445 error in Oracle, then it must be possible to write a core file for the user«oracle».

To enable writing core files you use the ulimit command, it controls the resources available to a process started by the shell, on systems that allow such control.

If you try to enable writing core files, usually you run in the following problem. Normally SSH is used to logon to the server.

ssh oracle@ora-server
$ ulimit -a

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
pending signals                 (-i) 1024
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 16384
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Nowtry (not as user root) to change the core file size to unlimited

ulimit -c unlimited
-bash: ulimit: core file size: cannot modify limit: Operation not permitted

Solution

  1. Check Environment for ulimit

    The first step is to check, that you don’t set ulimit -c 0 in any shell configuration files for this user, for example in $HOME/.bash_profile or $HOME/.bashrc. Uncomment it if you have such an entry.

    #
    # Do not produce core dumps
    #
    # ulimit -c 0
     

  2. Globally enable Core Dumps

    This must be done as user root, usually in /etc/security/limits.conf

    # /etc/security/limits.conf
    #
    #
     Each line describes a limit for a user in the form:
    #
    #
     <domain> <type> <item> <value>
    #

    *  soft  core  unlimited

     

  3. Logoff and Logon again and set ulimit

    ssh oracle@ora-server
    $ ulimit -c
    0

    Try to set the limit as user root first

    su –
    ulimit -c unlimited

    ulimit -c
    unlimited

    Now you can set ulimit also for user oracle

    su – oracle
    ulimit -c unlimited
    ulimit -c
    unlimited

Perhaps the last step number 3 is not necessary, but we have figured out, that this is the way which always work. The core file size limitation is usually also set in different configuration files. If you want to enable cores, you can uncomment them.

In /etc/profile (Redhat)

# No core files by default
# ulimit -S -c 0 > /dev/null 2>&1

In /etc/init.d/functions (Redhat)

# make sure it doesn’t core dump anywhere unless requested
# ulimit -S -c ${DAEMON_COREFILE_LIMIT:-0} >/dev/null 2>&1

Now, from this current shell you can generate the core, so check ulimit before.

$ ulimit -a

core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
pending signals                 (-i) 1024
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 16384
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

GIT – 다중 원격저장소 (remote repository) 사용 방법

svn 은 하나의 repository 만 설정할 수 있지만,
git 은 여러개의 repository 를 설정할 수 있다.

[#M_ more.. | less.. | git remote add secondremote alt-machine:/path/to/repo_M#]

 

remote 가 http/https 일경우 다음과 같이 설정하면 된다.

 

[#M_ more.. | less.. | git remote add secondremote https://remote-git.example.com/project/myproj.git _M#]


인증이 필요할 경우 매번 id 와 암호를 입력해야 하므로 id 정도는 url 에 같이 포함시키는 것이 편리하다. id와 @ 를 도메인 앞에 붙여 주면 된다.

 

[#M_ more.. | less.. | git remote add secondremote https://lesstif@remote-git.example.com/project/myproj.git_M#]

 

새로 추가된 remote에 기존의 내용(commit)을 업데이트 (push)하기 위해서는 다음의 명령어도 가능

 

[#M_ more.. | less.. |git push -u secondremote _M#]


모든 remote 에서 branch 및 update 된 내역을 가져오려면 다음 명령어 실행(HEAD 에 merge 하지는 않는다.)

 

[#M_ more.. | less.. | git remote update _M#]


alt remote 의 master branch 에서 fetch 하고 현재 HEAD 에 pull

 

[#M_ more.. | less.. | git pull alt master_M#]

 

매번 repository 마다 push/pull 을 따로 해줘야 하는게 번거롭다면 stackoverflow의 pull/push from multiple remote locations 글의 http://stackoverflow.com/a/3195446 답변을 참고

 

“Microsoft 직렬 볼펜” 과 “Serial Converter(FTDI)” 와 충돌하여 사용 불가능 할 경우,

FTDI 드라이버 고급속성 (장치관리자에서 COM 포트 속석)에서 “Serial Enumerator (직렬 니유머레이터” 항목을 비활성화

원인 : https://stackoverrun.com/ko/q/2408753
자세한 내용 : http://www.ftdichip.com/Support/Documents/AppNotes/AN_107_AdvancedDriverOptions_AN_000073.pdf

사용하지 않는 Serial Port를 제거하는 방법

사용하지 않는 Serial Port를 제거하는 방법
아래 작업 방법을 실행해 주시기 바랍니다.

 

  1. Windows Key + R을 눌러 명령 프롬프트를 실행합니다.
  2. cmd 명령 프롬프트에서 ‘set devmgr_show_nonpresent_devices=1‘를 입력합니다.
  3. 그리고 ‘start devmgmt.msc‘를 입력합니다.
  4. 장치관리자가 실행이 되면, 보기 -> 숨김 장치 표시 선택하면 숨겨진 장치들이 표시됩니다.
  5. 제거하려고 하는 COM Port를 마우스 우클릭하고 ‘제거’를 클릭합니다.

lsyncd + rsync로 디렉토리 실시간 백업하기

lsyncd + rsync로 디렉토리 거의 실시간 백업하기
실시간 동기화 라고 할 수도 있지만.. 실제로는 원본 디렉토리에 파일이 생성된 직후 rsync가 실행되어 백업 서버로 동기화 하기 때문에 파일이 copy되는 동안의 시간차 발생함.
1. rsync 설치, 설치 확인 (백업서버)
[root@vm2 sdir]# yum install rsync
[root@vm2 sdir]# rpm -qa | grep rsync
rsync-3.0.6-4.el5_7.1
2. rsync 활성화 (백업서버)
[root@vm2 data]# vi /etc/xinetd.d/rsync
# default: off
# description: The rsync server is a good addition to an ftp server, as it \
# allows crc checksumming etc.
service rsync
{
disable = no
socket_type = stream
wait = no
user = root
server = /usr/bin/rsync
server_args = –daemon
log_on_failure += USERID
}
3. rsyncd.conf 설정 (백업서버)
[root@vm2 data]# vi /etc/rsyncd.conf
[data_sync]
path=/data/sdir <– 접근을 허용할 디렉토리(백업디렉토리)
hosts allow=192.168.122.20 <– 접근을 허용할 서버 IP, 여러대를 동기화 할 경우 , 로 IP 추가
uid=0
gid=0
use chroot=yes
read only=no
[root@vm2 data]# mkdir /data/sdir
[root@vm2 data]#
[root@vm2 data]# /etc/init.d/xinetd restart
xinetd 를 정지 중: [ OK ]
xinetd (을)를 시작 중: [ OK ]
[root@vm1 data]#
4. lsyncd 설치 (원본서버)
[root@vm1 yum.repos.d]# yum install lsyncd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: ftp.daum.net
* extras: ftp.daum.net
* rpmforge: ftp.riken.jp
* updates: ftp.daum.net
Setting up Install Process
Resolving Dependencies
–> Running transaction check
—> Package lsyncd.i386 0:2.0.4-1.el5.rf set to be updated
–> Processing Dependency: lua for package: lsyncd
–> Running transaction check
—> Package lua.i386 0:5.1.4-2.el5.rf set to be updated
–> Finished Dependency Resolution
Dependencies Resolved
====================================================================================================================================
Package Arch Version Repository Size
====================================================================================================================================
Installing:
lsyncd i386 2.0.4-1.el5.rf rpmforge 149 k
Installing for dependencies:
lua i386 5.1.4-2.el5.rf rpmforge 242 k
Transaction Summary
====================================================================================================================================
Install 2 Package(s)
Upgrade 0 Package(s)
Total download size: 391 k
Is this ok [y/N]: y
Downloading Packages:
(1/2): lsyncd-2.0.4-1.el5.rf.i386.rpm | 149 kB 00:00
(2/2): lua-5.1.4-2.el5.rf.i386.rpm | 242 kB 00:00
————————————————————————————————————————————
Total 243 kB/s | 391 kB 00:01
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : lua 1/2
Installing : lsyncd 2/2
Installed:
lsyncd.i386 0:2.0.4-1.el5.rf
Dependency Installed:
lua.i386 0:5.1.4-2.el5.rf
Complete!
[root@vm1 yum.repos.d]#
– yum 으로 실치가 불가능할 경우 아래와 같이 rpmforge의 레포지터리를 추가하거나, rpm 파일을 다운로드 받아서 설치
[root@vm1 yum.repos.d]# cat /etc/yum.repos.d/rpmforge.repo
[rpmforge]
name = Red Hat Enterprise $releasever – RPMforge.net – dag
#baseurl = http://apt.sw.be/redhat/el5/en/$basearch/dag
mirrorlist = http://apt.sw.be/redhat/el5/en/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 0
5. lsyncd.conf 파일 생성 (원본서버)
settings = {
logfile = “/var/log/lsyncd.log”, <– 로그파일 경로 설정
statusFile = “/var/log/lsyncd-status.log”, <– lsyncd 상태 로그 경로
delay = 1,
}
sync{
default.rsync,
source= “/data/sdir”, <– 동기화 할 원본 디렉토리
rsyncOpts= “-avz”,
target= “192.168.122.184::data_sync” <– backup 경로, rsyncd.conf 파일에 지정된 서비스명
}
sync{
default.rsync,
source= “/data/sdir”, <– 동기화 할 원본 디렉토리
rsyncOpts= “-avz”,
target= “192.168.122.150::data_sync”, <– backup 경로, rsyncd.conf 파일에 지정된 서비스명
}
==============================================
– 백업서버가 2EA 이상일 경우, 아래와 같은 형식으로 작성해도 됨.
[root@vm1 sdir]# cat /etc/lsyncd.conf
settings = {
logfile = “/var/log/lsyncd.log”, <– 로그파일 경로 설정
statusFile = “/var/log/lsyncd-status.log”, <– lsyncd 상태 로그 경로
delay = 1,
}
targetlist = {
“192.168.122.184::data_sync”, <– backup 경로, rsyncd.conf 파일에 지정된 서비스명
“192.168.122.150::data_sync” <– backup 경로, rsyncd.conf 파일에 지정된 서비스명
}
for _, server in ipairs(targetlist) do
sync{ default.rsync,
source=”/data/sdir/”, <– 동기화 할 원본 디렉토리
target=server,
rsyncOpts= “-avz”,
}
end
6. lsyncd 데몬 실행 (원본서버)
[root@vm1 sdir]# /etc/init.d/lsyncd restart
lsyncd (을)를 시작 중: [ OK ]
7. 동기화 테스트
– 원본 서버의 source 디렉토리(/data/sdir) 에서 파일을 생성/삭제하면서, 백업서버의 target 디렉토리가 정상적으로 동기화 되는지 확인
8. 여러대의 서버를 서로 상호간 동기화 설정을 하기 위해서는
– 원본 서버에 백업서버와 동일하게 rsyncd.conf 파일을 생성하여 백업서버에서 접근이 가능하도록 설정
– 백업서버에 원본과 동일하게 lsyncd를 실행하고 백업 디렉토리에 생성/삭제된 파일이 원본서버로 동기화 되도록 설정

How to install asterisk and freepbx on ubuntu 16.04

출처 : https://schooloffreelancing.blogspot.com/2017/11/asterisk-freepbx-install-into-ubuntu.html

apt-get -y autoremove
apt-get -y update
apt-get -y upgrade
# Some Utils
apt-get install -y curl vim-nox
# PJSIP
apt-get install -y make gcc g++ binutils sudo git
cd /usr/src
git clone https://github.com/asterisk/pjproject.git
cd /usr/src/pjproject
CFLAGS=’-DPJ_HAS_IPV6=1′ ./configure –prefix=/usr –enable-shared –disable-sound –disable-resample –disable-video –disable-opencore-amr
make dep 
make
make install
ldconfig
ldconfig -p | grep pj
# Asterisk 13
apt-get install -y libtool pkg-config libnewt-dev subversion
apt-get install -y libncurses5-dev uuid-dev libjansson-dev libxml2-dev libsqlite3-dev
apt-get install -y libmysqlclient-dev 
apt-get install -y unixodbc-dev libmyodbc
apt-get install -y libssl-dev libcurl4-openssl-dev libgnutls28-dev libsrtp0-dev
apt-get install -y bison flex
apt-get install -y sox lame flac mpg123 libmpg123-dev libogg-dev libvorbis-dev libspeex-dev libspeexdsp-dev libasound2-dev
apt-get install -y libiksemel-dev libiksemel-utils 
apt-get install -y libspandsp-dev
apt-get install -y libical-dev libneon27-dev 
cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-13-current.tar.gz
tar zxvf asterisk-13-current.tar.gz
cd asterisk-*
# contrib/scripts/install_prereq install
contrib/scripts/get_mp3_source.sh
./configure
make menuselect.makeopts
menuselect/menuselect –enable-category MENUSELECT_ADDONS menuselect.makeopts
menuselect/menuselect –enable CORE-SOUNDS-EN-GSM –enable MOH-OPSOUND-WAV –enable EXTRA-SOUNDS-EN-GSM –enable cdr_mysql menuselect.makeopts
menuselect/menuselect –disable app_mysql –disable app_setcallerid –disable func_audiohookinherit menuselect.makeopts
make
make install
make config
make samples
ldconfig
ldconfig -p | grep asterisk
systemctl disable asterisk.service
cd /var/lib/asterisk/sounds
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-en-wav-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-wav-current.tar.gz
tar xvf asterisk-core-sounds-en-wav-current.tar.gz
rm -f asterisk-core-sounds-en-wav-current.tar.gz
tar xfz asterisk-extra-sounds-en-wav-current.tar.gz
rm -f asterisk-extra-sounds-en-wav-current.tar.gz
# Wideband Audio download 
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-en-g722-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-g722-current.tar.gz
tar xfz asterisk-extra-sounds-en-g722-current.tar.gz
rm -f asterisk-extra-sounds-en-g722-current.tar.gz
tar xfz asterisk-core-sounds-en-g722-current.tar.gz
rm -f asterisk-core-sounds-en-g722-current.tar.gz
useradd -m asterisk
chown asterisk. /var/run/asterisk
chown -R asterisk. /etc/asterisk
chown -R asterisk. /var/{lib,log,spool}/asterisk
chown -R asterisk. /usr/lib/asterisk
# FreePBX 13
export DEBIAN_FRONTEND=noninteractive
apt-get install -y apache2 mysql-server mysql-client php5 php5-curl php5-cli php5-mysql php5-gd php-pear unixodbc
rm /var/www/html/index.html
sed -i ‘s/\(^upload_max_filesize = \).*/\120M/’ /etc/php5/apache2/php.ini
cp /etc/apache2/apache2.conf /etc/apache2/apache2.conf_orig
sed -i ‘s/^\(User\|Group\).*/\1 asterisk/’ /etc/apache2/apache2.conf
sed -i ‘s/AllowOverride None/AllowOverride All/’ /etc/apache2/apache2.conf
service apache2 restart
cat >> /etc/odbcinst.ini << EOF
[MySQL]
Description = ODBC for MySQL
Driver = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libodbcmyS.so
FileUsage = 1
 
EOF
cat >> /etc/odbc.ini << EOF
[MySQL-asteriskcdrdb]
Description=MySQL connection to ‘asteriskcdrdb’ database
driver=MySQL
server=localhost
database=asteriskcdrdb
Port=3306
Socket=/var/run/mysqld/mysqld.sock
option=3
 
EOF
cd /usr/src
wget http://mirror.freepbx.org/modules/packages/freepbx/freepbx-13.0-latest.tgz
tar vxfz freepbx-13.0-latest.tgz
rm -f freepbx-13.0-latest.tgz
cd /usr/src/freepbx
rm /etc/asterisk/*.conf
./start_asterisk start
./install -n
cat >> /etc/systemd/system/freepbx.service << EOF
[Unit]
Description=FreePBX VoIP Server
After=mysql.service
 
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/fwconsole start
ExecStop=/usr/sbin/fwconsole stop
 
[Install]
WantedBy=multi-user.target
 
EOF
systemctl enable freepbx.service
systemctl start freepbx.service
systemctl status freepbx.service
fwconsole chown
fwconsole reload
fwconsole moduleadmin installall
fwconsole moduleadmin upgradeall
fwconsole chown
fwconsole reload
fwconsole moduleadmin uninstall dahdiconfig
fwconsole moduleadmin delete dahdiconfig
fwconsole moduleadmin uninstall sipstation
fwconsole moduleadmin delete sipstation
fwconsole moduleadmin uninstall digium_phones
fwconsole moduleadmin delete digium_phones
fwconsole moduleadmin uninstall cxpanel
fwconsole moduleadmin delete cxpanel
fwconsole moduleadmin uninstall firewall
fwconsole moduleadmin delete firewall
fwconsole moduleadmin upgradeall
fwconsole chown
fwconsole reload
fwconsole chown

MySQL 외부 접속 (root / user) 가능하도록 설정

원격 접속 가능한 호스트 및 사용자 확인

[root@company bin]# mysql uroot p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 561388
Server version: 5.0.51log Source distribution
 
 
 
mysql> select HOST, USER, Password FROM mysql.user;
+—————–+——-+——————————————-+
| HOST            | USER  | Password                                  |
+—————–+——-+——————————————-+
| localhost       | root  | *(생략)                           | 
| company         | root  |                                           | 
| 127.0.0.1       | root  |                                           | 
| localhost       |       |                                           | 
| company         |       |                                           | 
| localhost       | news  | *(생략)                                | 
| 211.200.200.200 | news  | (생략)                                     | 
| 100.200.100.100 | news  | (생략)                                      | 
| 192.168.100.110 | news  | (생략)                                      | 
+—————–+——-+——————————————-+
 
9 rows in set (0.02 sec)

위 경우 HOST에 명시된 호스트에서만 접속 가능.

따라서 사용자 추가.

mysql> show databases;
+——————–+
| Database           |
+——————–+
| information_schema | 
| mysql              | 
| company            | 
+——————–+
3 rows in set (0.01 sec)
 
mysql> use mysql
Database changed
 
mysql> insert into user (host,user,password) 
values(‘%’,‘news’,password(‘newspasswd’));
Query OK, 0 rows affected (0.02 sec)
 
mysql> GRANT all privileges on *.* to ‘news’@‘%’ 
identified by ‘newspasswd’ ;
Query OK, 0 rows affected (0.02 sec)
 
mysql> flush privileges;
Query OK, 0 rows affected (0.02 sec)
 
 
mysql> select HOST, USER, Password FROM mysql.user;
+—————–+——-+——————————————-+
| HOST            | USER  | Password                                  |
+—————–+——-+——————————————-+
| localhost       | root  | *7540F67EE4(생략)                         | 
| company         | root  |                                           | 
| 127.0.0.1       | root  |                                           | 
| localhost       |       |                                           | 
| company         |       |                                           | 
| localhost       | news  | *7540F67EE4                               | 
| 211.200.200.200 | news  | 49d7                                      | 
| 100.200.100.100 | news  | 49d7                                      | 
| 192.168.100.110 | news  | 49d7                                      | 
| %  | news  | *7540F67EE4                               | 
+—————–+——-+——————————————-+
10 rows in set (0.02 sec)
 


단 MySQL 5.7에서는 Insert 명령어를 아래와 같이 변경해야 함.
insert into user(host,user,authentication_string,ssl_cipher,x509_issuer,x509_subject) values (‘%’, ‘news’, password(‘password’),”,”,”);


호스트를 %로 할경우 어떤 호스트에서든 접속 가능.

이렇게 하고도… 외부에서 접속이 안될 경우

1. OS 방화벽 (리눅스 방화벽 확인 ) 해제 – ufw disable
2. MySQL 설정 파일 “my.cnf” (mysqld.cnf) 에, bind-address=127.0.0.1 로 되어 있는 것을 “0.0.0.0” 으로 변경 후, 
3. MySQL 재시작

UBuntu 16.04 – 부팅시 rc.local 파일 실행 되지 않을 때 (systemd 기반 rc.local 활성화)

우분투 16.04 버전은 systemd 기반으로 PID들이 관리된다,
rc.local을 부득이 하게 사용할 일이 생겨 사용하려 했으나 활성화가 안되어 있어서 활성화 방법을 찾아서 기록

 

/lib/systemd/sytem/rc-local.service 을 수정한다.

 

가장 하단에 

 

[#M_ more.. | less.. |[Install]
WantedBy=multi-user.target _M#]

 

​위 와 같이 추가 시켜준 뒤 

[#M_ more.. | less.. |systemctl enable rc-local.service _M#]

 

​rc.local 서비스를 활성화 시켜준다.

Install을 추가시켜주지 않고 활성화를 시켜주려 하면, 해당 부분이 없어 활성화가 되지 않는다.

 

rc.local이 제데로 동작하는지 테스트는 서비스 재시작 뒤 확인 해주면 된다.

[#M_ more.. | less.. |service rc.local restart
systemctl status rc-local.service_M#]

 

​정상적으로 동작한다면 

 

[#M_ more.. | less.. |

root@stream:~# systemctl status rc-local.service

● rc-local.service – /etc/rc.local Compatibility

   Loaded: loaded (/etc/systemd/system/rc-local.service; static; vendor preset: enabled)

  Drop-In: /lib/systemd/system/rc-local.service.d

           └─debian.conf

   Active: active (running) since Mon 2018-04-02 15:23:37 KST; 3min 43s ago

  Process: 1434 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)

    Tasks: 87

   Memory: 111.9M

      CPU: 3.000s

   CGroup: /system.slice/rc-local.service

           ├─1529 /usr/local/bin/tvheadend –config /home/TVHeadEnd/.hts/tvheadend/ –user root –gr

           └─1530 /usr/local/bin/istatserver -d

 

Apr 02 15:23:38 stream tvheadend[1529]: scanfile: DVB-C – loaded 18 regions with 60 networks

Apr 02 15:23:38 stream tvheadend[1529]: scanfile: ATSC-T – loaded 2 regions with 12 networks

Apr 02 15:23:38 stream tvheadend[1529]: scanfile: ATSC-C – loaded 1 regions with 5 networks

Apr 02 15:23:38 stream tvheadend[1529]: scanfile: ISDB-T – loaded 2 regions with 1297 networks

Apr 02 15:24:37 stream tvheadend[1529]: iptv: m3u parse: 0 new mux(es) in network ‘IPTV’ (total 116)

 _M#]

active (활성화) 되었다고 표시되며, 하단에 로그도 확인이 가능하다.

메모리 보호 기법 SSP(Stack Smashing Protector)

출처: http://bbolmin.tistory.com/65 

Stack Smashing Protector은 gcc 4.1버전 부터 있는 stack overflow를 방지하기 위한 컴파일러 옵션이다.

 

gcc 4.6.1버전에서 컴파일 후 overflow가 발생하는 프로그램을 실행시켜 보니 다음과 같이 stack smashing detected가 뜨는 것을 확인 할 수 있다.

SSP 끄기 : -fno-stack-protector

SSP를 모든 함수에 설치 : -fstack-protector-all (원래는 일정 크기의 char배열이 있는 함수에만 적용됨)


SSP의 기능을 살펴보자

1. 로컬 변수 재배치

2. 로컬 변수전에 포인터 배치

3. canary 삽입

 

1. 로컬 변수 재배치

 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

 

void main(int argc, char *argv[])

{

    int check=0;
    char buf[10];

    strcpy(buf, argv[1]);

    if(check==0)
        exit(0);

    printf(“check : %d\n”, check);

}

buf를 오버플로우시켜서 check값을 바꿀 수 있을 것이다. 하지만 SSP는 스택에서 char배열을 제일 높은 곳으로 올려 다른 변수 값이 변조되는 것을 막는다.

 

 

2. 로컬 변수전에 포인터 배치

 

void test(char *arg)

{

char buf[10];

strcpy(buf, arg);

}

위와 같이 포인터가 있을 때 buf를 오버플로우 시켜서 test함수의 파라미터로 전달된 포인터 arg값을 바꿀 수 있을 것이다. 하지만 SSP는 arg포인터를 buf아래 쪽에 두어서 변조되는 것을 막는다.

 

 

 

3. canary 삽입

 

————

|       ret     |

————

|      ebp     |

————

|   canary  |

————

|       buf     |

————

 

stack guard처럼 canary를 두어 ret변조를 탐지한다. 이 때 canary는 ebp와 buf 사이에 넣는다. canary 값은 1) random, 2) terminator, 3) null 을 사용하여 우회하는 것을 방지한다. canary 변조를 탐지 했을 때 맨위 그림와 같이 stack-smashing-detected 메시지를 띄어준다. (변조 탐지시 __stack_chk_fail함수를 호출)

 

GDB 사용시 raise.c 와 같이 glibc 파일이 없다고 나오는 경우

에러 메시지 
Unable to open ‘raise.c’: File not found (file:///build/glibc-Cl5G7W/glibc-2.23/sysdeps/unix/sysv/linux/raise.c).

이 경우 우선 glibc 를 소스까지 다운로드


Building glibc without installing

To build glibc without installing you can do the standard configure and make e.g.

$ mkdir $HOME/src
$ cd $HOME/src
$ git clone git://sourceware.org/git/glibc.git
$ mkdir -p $HOME/build/glibc
$ cd $HOME/build/glibc
$ $HOME/src/glibc/configure --prefix=/usr
$ make

Do not run make install.


이후 아래 설명을 참고하여, 찾고자 하는 링크 위치를 심볼릭 링크 걸어주면 해결


To do full source code debugging of the C library on Ubuntu, you need to:

1) install the debuginfo version of libc6.

It’s probably already installed, but in case it isn’t, run sudo apt install libc6-dbg.

2) download the source code corresponding to the installed version of the C library.

First, create a directory anywhere – I’ll use /opt/src here. Then do the following:

sudo apt install dpkg-dev
cd /opt/src
apt source libc6
find $PWD -maxdepth 1 -type d -name 'glibc*'

Remember this name – it’ll be something like /opt/src/glibc-2.23

Now, run gdb, run your program until it stops, and at the gdb prompt do this:

(gdb) info source
Current source file is ../sysdeps/unix/sysv/linux/raise.c
Compilation directory is /build/glibc-KM3i_a/glibc-2.23/signal

So gdb is expecting the source code to be in a directory that’s different from where we put it. There are two ways to fix this:

a) move or use a symlink so that the source code is (or appears to be) in /build/glibc-KM3i_a/glibc-2.23 .

b) tell gdb how to substitute the correct source directory pathname: 

  (gdb) set substitute-path /build/glibc-KM3i_a/glibc-2.23 /opt/src/glibc-2.23

Now, go back to your frame, and gdb should show the source code line:

(gdb) frame 1
#1 0xb7e2fea9 in __GI_raise (sig=6) at ../sysdeps/unix/sysv/linux/raise.c:54
         return INLINE_SYSCALL (tgkill, 3, pid, selftid, sig);