아파치 SSL 로 구동시 키 비밀번호 없애기 – Some of your private key files are encrypted for security reasons.

SSL 인증서 생성시 인증키 값을 넣을경우
아파치 구동시 키 비밀번호를 입력하지 않으면 구동되지 않는다.



Apache/2.2.13 mod_ssl/2.2.13 (Pass Phrase Dialog)
Some of your private key files are encrypted for security reasons.
In order to read them you have to provide the pass phrases.


Server test.com:443: (RSA)
Enter pass phrase:



서버를 관리하는 입장에서는 비밀번호를 입력하지 않고 자동으로 웹서버를
구동하여야할때가 있다.
 
인증서 생성시 이미 넣어버린 키는 아래와 같이 하면 간단하게 없앨 수 있다.
단, 당연한 이야기지만 기존 비밀번호는 알고있어야한다.-.-;


cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

다시 아파치를 restart 해본다.

Apache SSL 인증서 설치 / 적용 가이드

원문 : https://www.securesign.kr/guides/Apache-SSL-Certificate-Install

사전 구성 환경

  • OpenSSL 라이브러리 http://www.openssl.org/ : openssl 1.0.1 이상 권장
  • Apache w/mod_ssl http://www.modssl.org/ : http.conf 에서 mod_ssl 모듈 활성화 (LoadModule ssl_module modules/mod_ssl.so)
  • TLS / SHA-2(sha256) 암호화 지원 모듈 구성/활성 확인 필수
  • MD5, RC4 등 국제 보안 기구에서 해제를 권장하는 취약한 암호화 모듈 비활성화
  • SSL 2.0, 3.0 및 TLS 1.0 1.1 프로토콜 접속 허용 해제. 최신 TLS 1.2 1.3 설정 권장

진행 과정

  1. 개인키(Private Key) 생성
  2. CSR(Certificate Signing Request) 생성
  3. 인증서 발급 신청 제출
  4. 인증서 발급 완료 (발급내역서/파일설명서 PDF 참조)
  5. 인증서 설치 적용 – 신규,갱신,재발급,도메인추가
  6. 서버 정상 적용 완료 테스트
  7. 웹페이지에 https:// 링크 적용

개인키(Private Key) 생성


– SSL 인증서 발급 신청서 작성시, CSR 입력 단계에서 온라인 “CSR 자동생성” 이용을 권장합니다. (현재 과정 필요 없음)
– CSR 자동생성 발급 완료시, “개인키, 서버인증서, 체인인증서, 루트인증서” PEM 파일이 모두 포함되어 있습니다.
– 추가 포함된 “pfx / jks” 패키지에는, “개인키+서버인증서+체인인증서+루트인증서” 가 모두 통합되어 있습니다.
openssl genrsa -des3 -out private.key 2048
  • -des3 : 개인키 암호화 수준 DES3 (Windows Apache 환경은 해당 옵션 제외)
  • -out private.key : 개인키를 저장할 파일명 지정. 개인키 파일은 분실하지 않도록 잘 보관해야 합니다.
  • 2048 : bit

Result


Loading ‘screen’ into random state – done
Generating RSA private key, 2048 bit long modulus
……………………..+++
……………………………………………..
…………………+++
e is 65537 (0x10001)
Enter pass phrase for pri.kery: (개인키 파일 암호 입력)
Verifying – Enter pass phrase for pri.kery: (개인키 파일 암호 입력)

CSR(Certificate Signing Request) 생성 예


– SSL 인증서 발급 신청서 작성시, CSR 입력 단계에서 온라인 “CSR 자동생성” 이용을 권장합니다. (현재 과정 필요 없음)
– CSR 자동생성 발급 완료시, “개인키, 서버인증서, 체인인증서, 루트인증서” PEM 파일이 모두 포함되어 있습니다.
– 추가 포함된 “pfx / jks” 패키지에는, “개인키+서버인증서+체인인증서+루트인증서” 가 모두 통합되어 있습니다.
openssl req -new -key private.key -out out.csr -config “../share/openssl.cnf”


또는
openssl req -new -key private.key -out out.csr -subj “/C=KR/ST=Seoul/L=Gang-nam/O=SecureSign.KR/OU=Dev Team/CN=example.com”
  • -key private.key : 앞서 생성한 개인키 파일 지정
  • -outout.csr : 생성될 CSR 파일명 지정
  • -config “../share/openssl.cnf” : cnf 위치를 확인하지 못하는 경우 cnf 파일 경로 지정
  • -subj : CSR 생성시 입력이 필요한 정보 지정
    • C : ISO 국가 코드 KR, US, CN, JP (대문자)
    • ST : 시,도
    • L : 구,군
    • O : 기관명, 회사명
    • OU : 조직명
    • CN : 도메인명, 일반이름. IP 주소는 CN 으로 사용할수 없습니다.
    • 위 항목은 모두 영문입력을 해야 합니다. 특수문자를 사용하면 안됩니다.

  • (예제에 사용된 옵션 값 등은 예제용이므로, 실제 해당 도메인 정보로 지정하시기 바랍니다)

Single

CN : sub.example.com 처럼 FQDN 도메인 형식 이어야 합니다.

Wildcard

CN : *.example.com 과 같은 패턴 이어야 합니다.

MultiDomain

CN : example.com 대표성을 가진 FQDN 도메인 1개만 입력 합니다.
SAN : 인증서에 포함될 나머지 FQDN 도메인은, 신청서 작성중 DCV 설정 단계에서 추가 입력합니다.

Multi-Wildcard

CN : example.com 대표 루트 도메인 1개을 CN으로 입력 합니다.
SAN : *.example.com 형식의 와일드카드 도메인은, 신청서 작성중 DCV 설정 단계에서 추가 입력합니다.

Result


Enter pass phrase for pri.kery: (개인키 패스워드 입력)
Loading ‘screen’ into random state – done
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [AU]:KR (국가코드 C)
State or Province Name (full name) [Some-State]:Seoul (시,도 ST)
Locality Name (eg, city) []:Gang-nam (구,군 L)
Organization Name (eg, company) [Internet Widgits Pty Ltd]:SecureSign.KR (기관명 O)
Organizational Unit Name (eg, section) []:Dev Team (조직명 OU)
Common Name (eg, YOUR name) []:example.com (도메인명 CN)
Email Address []:webmaster@example.com (이메일)

Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []: enter (설정 X)
An optional company name []: enter (설정 X)

생성된 CSR 예제


– SSL 인증서 발급 신청서 작성시, CSR 입력 단계에서 온라인 “CSR 자동생성” 이용을 권장합니다. (현재 과정 필요 없음)
– CSR 자동생성 발급 완료시, “개인키, 서버인증서, 체인인증서, 루트인증서” PEM 파일이 모두 포함되어 있습니다.
– 추가 포함된 “pfx / jks” 패키지에는, “개인키+서버인증서+체인인증서+루트인증서” 가 모두 통합되어 있습니다.
-----BEGIN CERTIFICATE REQUEST-----
MIIC5TCCAc0CAQAwgZ8xCzAJBgNVBAYTAktSMQ4wDAYDVQQIEwVTZW91bDERMA8G
A1UEBxMIR2FuZy1uYW0xGDAWBgNVBAoTD1NlY3VyZUxheWVyIEluYzERMA8GA1UE
-- 중략 --
wxd+87gwsvAC2dyK8I4N1ttXDRJcDPCDe1BGqWvYYAZN7FbvnbHCM7y/SN++pxbS
jbnkoe8uStQvfCo6DW5MZHUli5+lRU/UpA==
-----END CERTIFICATE REQUEST-----

앞서 생성한 CSR 파일은 Base64 포맷의 PEM Text 이며, 텍스트 편집기를 이용하여 파일을 오픈합니다. -----BEGIN ~ REQUEST----- 까지 포함하여 내용 전체를 복사하여 신청서에 입력합니다. (—– 를 누락하거나, 새로운 빈출이 추가되지 않도록 주의하세요)

인증서 발급 완료 및 참고 사항

– 발급 완료 후에는, 메일첨부 또는 주문상세의 압축파일(zip)에 인증서 파일이 포함되어 있습니다.
– 서버 적용에 필요한 파일들에 대해서, 발급 내역서 PDF 및 루트/체인 설명 PDF를 통해서 미리 숙지해야 합니다.
– 이후 과정 부터는, 서버에 SSL 인증서 설치/적용/확인 절차 입니다. (인터넷에 공개된 설정법과 차이 없음)

– 서버이름표시(SNI) 지원되는 서버의 경우, SSL 인증서 마다 각 포트 구분없이 모두 443 포트 적용가능합니다.
– SNI 설정으로 하는 경우, 클라이언트에서 SNI 미지원 하는 경우 접속 호환성 문제가 있으므로 미리 검토해야 합니다.

VirtualHost 적용 예제 (서버 인증서 발급 받은 후)

<VirtualHost *:443>

ServerName “아래 지정한 서버 인증서에 포함된 DNS Name 중에 있어야 함 ”
SSLEngine on
SSLProtocol all -SSLv2 -SSLv3 또는 TLSv1 TLSv1.1 TLSv1.2 (서버 환경에 따라서 선택적 적용)
SSLCertificateKeyFile /인증서파일경로/개인키 ex. domain_xxxxx.key.pem
SSLCertificateFile /인증서파일경로/서버인증서 ex. domain_xxxxx.crt.pem
SSLCertificateChainFile /인증서파일경로/체인인증서ex. chain-bundle.pem
SSLCACertificateFile /인증서파일경로/루트인증서 ex. AAACertificateServicesRoot.crt.pem

</VirtualHost>

* 루트/체인 인증서는 상품별로 차이가 있으므로, 발급 완료시 첨부된 파일 내역에서 확인 가능합니다.
* chain-bundle.pem 은 체인인증서가 여러개인 경우 1개 파일로 통합한 PEM Text 파일입니다.
* CSR 자동 생성 이용시, 개인키에는 패스워드가 지정되지 않습니다. (별도 지정 필요시 변환 매뉴얼 참조)
* 예제에 포함되어 있지 않은 나머지 Property 는 공식 매뉴얼 또는 현재 서버 설정값을 사용하시기 바랍니다. (/conf/extra/httpd-ssl.conf 참조)

VirtualHost 적용 예제 – Apache 2.4.8 + (서버 인증서 발급 받은 후)

<VirtualHost *:443>

ServerName “아래 지정한 서버 인증서에 포함된 DNS Name 중에 있어야 함 ”
SSLEngine on
SSLProtocol all -SSLv2 -SSLv3 또는 TLSv1 TLSv1.1 TLSv1.2 (서버 환경에 따라서 선택적 적용)
SSLCertificateKeyFile /인증서파일경로/개인키 ex. domain_xxxxx.key.pem
SSLCertificateFile /인증서파일경로/서버+체인 PEM 통합된 파일 ex. domain_unified.pem
SSLCACertificateFile /인증서파일경로/루트인증서 ex. AAACertificateServicesRoot.crt.pem

</VirtualHost>

* 루트/체인 인증서는 상품별로 차이가 있으므로, 발급 완료시 첨부된 파일 내역에서 확인 가능합니다.
* 통합 pem 파일 생성 : cat domain_xxxxx.crt.pem chain-bundle.pem > unified.domain.pem (cat, type 명령어 사용)
* 통합된 domain_unified.pem 파일을 Text 편집기로 열어서, PEM 내용간 구분되어 있는지 꼭 확인해야 합니다.
* CSR 자동 생성 이용시, 개인키에는 패스워드가 지정되지 않습니다. (별도 지정 필요시 변환 매뉴얼 참조)
* 예제에 포함되어 있지 않은 나머지 Property 는 공식 매뉴얼 또는 현재 서버 설정값을 사용하시기 바랍니다. (/conf/extra/httpd-ssl.conf 참조)

설치 적용 확인 및 변환

* 서버에 SSL 설정 적용 후, 웹서버를 재시작하여 시작시 오류 또는 경고가 있는지 콘솔/데몬 로그를 필히 확인해야 합니다. (필수 확인 사항)
* SSL 발급 도메인 웹페이지에 https:// 링크 적용을 별도 진행해야 최종적으로 SSL 암호화가 적용됩니다. (개발자,웹디자이너)
* PC 및 스마트폰의 “Chrome / Firefox / IE / Edge” 각 웹브라우져에서 “루트,체인,SSL,TLS” 경고가 발생 하는지 확인해야 합니다.

SSL 설치/적용 트러블슈팅
SSL 설치 적용 확인 하기
체인인증서 적용 확인 방법
인증서 포맷 변환 방법
TrustLogo 적용 방법

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

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 재시작

[Mac] 특정 네트워크 인터페이스에 static route 정보 설정

출처 : http://egloos.zum.com/mcchae/v/11263102

Mac 에서 (Sierra) static route를 설정할 필요가 있습니다.

예를 들어,
Wi-Fi 로 연결된 자신의 주소가 192.168.10.100 이었고,
192.168.10.200 이라는 내부 라우터가
192.168.100.0/24 네트워크를 라우팅할 필요가 있다면
터미널에서
$ sudo route -n add 192.168.100.0/24 192.168.10.200
라고 명령을 주면 됩니다.
문제는 다음에 재기동하면 다시 이 정보가 없어지는 문제가 있지요.
다음은 간단히 networksetup 명령을 이용하여 static routing 정보를
시스템에 등록하는 방법입니다.
우선 현재 시스템에 설치된 인터페이스를 검색합니다.
$ networksetup -listallnetworkservices
An asterisk (*) denotes that a network service is disabled.
Wi-Fi
USB 10/100/1000 LAN
iPhone USB
Bluetooth PAN
Thunderbolt Bridge
Wi-Fi 인터페이스에 지정된 정보를 확인합니다.
$ networksetup -getinfo Wi-Fi
DHCP Configuration
IP address: 192.168.10.160
Subnet mask: 255.255.255.0
Router: 192.168.10.1
Client ID:
IPv6: Automatic
IPv6 IP address: none
IPv6 Router: none
Wi-Fi ID: 80:e6:50:0f:1a:f4
혹시 이전에 설정한 static 정보가 있는지 확인합니다.
$ networksetup -getadditionalroutes Wi-Fi
There are no additional IPv4 routes on Wi-Fi.
 
이제는 위에서 설명한 것과 같은 static 라우팅 정보를 지정합니다.
$ sudo networksetup -setadditionalroutes Wi-Fi 192.168.100.0 255.255.255.0 192.168.10.200
다시 부팅을 하거나 해도 다음과 같이 정적 라우팅 정보를 확인해 보면,
$ networksetup -getadditionalroutes Wi-Fi
192.168.100.0 255.255.255.0 192.168.10.200
과 같이 정적 라우팅이 지정됩니다.

Ubuntu 14.04 + sendmail 설치

** sendmail 설치 및 설정

 

> 설치 

# apt-get install sendmail
# apt-get install sendmail-cf    ;; sendmail 설정

> 제대로 설치되었나 확인

# cd /etc/mail

 

> 내부에서만 메일을 주고 받을수 있게 설정해보자

# vi /etc/mail/sendmail.mc

Line 56 아래와 같이 수정
DAMON_OPTIONS('Family=inet, Name=MTA-v4, Port=smtp, Addr=127.0.0.1')dnl

Line 59 아래와 같이 수정
DAMON_OPTIONS('Family=inet, Name=MSP-v4, Port=submission, M=Ea, Addr=127.0.0.1')dnl

# m4 sendmail.mc   ;; 변경된 값 적용

 

> 접근할 수 있는 IP 대역 설정 추가

 

# vi /etc/mail/access

아래 부분 추가

127.0.0.1 RELAY
192.168.0 RELAY ;; 내부 아이피에서는 허용
;; 공인 아이피가 있다면 같이 추가해줌

# makemap hash access < access ;; 적용

> sendmail 재시작

 

# service sendmail restart

 

  

** sendmail이 가긴 가는데 너무 느리게 갈 때

 

> sendmail error log 확인

 

# vi /var/log/mail.err

아래 내용이 있는지 확인
My unqualified host name (localhost) unknown;; sleeping for retry

 

host name을 못 찾겠다 하지만 메일은 보내주겠다는 내용인 것 같음.

 

> host name 추가

# vi /etc/hots

127.0.0.1    localhost.localdomain localhost (yourhostname)

 

 

 

Asterisk – 해킹 시도 Fail2Ban 으로 차단하기

Fail2Ban (with iptables) And Asterisk

Fail2Ban


Fail2Ban is a limited intrusion detection/prevention system. It works by scanning log files and then banning IPs based on the entries in those logs. Note that Digium is moving away from writing security information to log files, and is now using AMI events. Consider fail2ban a short-term solution only.

You can get Fail2Ban, as well as more documentation, at www.fail2ban.org. At the time this is being written, the current release is 0.8.4.

Fail2Ban With Asterisk


The following describes how to setup Fail2Ban to protect an Asterisk PBX from SIP brute force attempts and scans utilizing the iptables firewall.

SECURITY NOTE: fail2ban is rather limited in its ability to detect attacks against asterisk. 
More info http://forums.asterisk.org/viewtopic.php?p=159984
Consider a more comprehensive product like the free edition of SecAst www.generationd.com

Easy Install Script for Fail2ban version 0.8.4 / Red Hat


This script was written by Cédric Brohée in order to simplify and accelerate the integration of the solution in a basic Asterisk configuration on Red Hat.
Do not hesitate to read the bash script and make changes to match your own configuration.

Before running it, you will have to do chmod 755.

Download script with new dedicated sources :

Fail2ban.sh_030512.txt




Installing


Log into the system and su – root, or sudo -i to get a root shell on Ubuntu.

CentOS/Red Hat (this method may install an older version of fail2ban):

Install rpmforge or optionally fetch the fail2ban rpm directly from rpmforge.
Install fail2ban using yum:

yum install fail2ban

Debian/Ubuntu:

apt-get install fail2ban

Source installation:
Change directories to /usr/src:

cd /usr/src

Download and extract Fail2Ban (check for newer releases):

wget http://sourceforge.net/projects/fail2ban/files/fail2ban-stable/fail2ban-0.8.4/fail2ban-0.8.4.tar.bz2/download
tar jxf fail2ban-0.8.4.tar.bz2

Enter the Fail2Ban directory you just extracted:

cd fail2ban-0.8.4

Make sure python and iptables are installed:

CentOS/Red Hat:

yum install python iptables

Debian/Ubuntu:

apt-get install python iptables

Install Fail2Ban:

python setup.py install

Install the Fail2Ban init script (for source installations):

Centos/Red Hat (if you installed via yum/rpm, the init script has already been installed):

cp /usr/src/fail2ban-0.8.4/files/redhat-initd /etc/init.d/fail2ban
chmod 755 /etc/init.d/fail2ban

For other distributions’ init scripts, please refer to documentation specific to them.



Configure Fail2Ban


We need to create a configuration for Fail2Ban so that it can understand attacks against Asterisk.

Create a new filter configuration for Asterisk:

touch /etc/fail2ban/filter.d/asterisk.conf

The contents of /etc/fail2ban/filter.d/asterisk.conf should be the following:

Generic (without using /var/log/asterisk/security)


# Fail2Ban configuration file
#
#
# $Revision: 250 $
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
#before = common.conf


[Definition]

#_daemon = asterisk

# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT
#

# Asterisk 1.4 use the following failregex

failregex = NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Wrong password
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Username/auth name mismatch
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Device does not match ACL
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Peer is not supposed to register
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - ACL error (permit/deny)
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Device does not match ACL
            NOTICE.* <HOST> failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' \(from <HOST>\)
            NOTICE.* .*: Host <HOST> failed MD5 authentication for '.*' (.*)
            NOTICE.* .*: Failed to authenticate user .*@<HOST>.*
            NOTICE.* .*: Sending fake auth rejection for device .*\<sip:.*\@<HOST>\>;tag=.*

# In Asterisk 1.8 use the same as above, but after <HOST> add :.* before the single quote. This is because in Asterisk 1.8, the log file includes a port number which 1.4 did not.

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =



If you’re having issues with your system not banning properly when the “Registration from” section in your log file contains a quotation mark (“) as in this example:


[2011-04-07 17:53:11] NOTICE[7557] chan_sip.c: Registration from '"69106698"<sip:69106698@123.123.123.123>' failed for '123.123.123.123' - No matching peer found



Add the following line, with the others above, in asterisk.conf:

NOTICE.* .*: Registration from ‘\”.*\”.*’ failed for ‘<HOST>’ – No matching peer found

Recently noticed attacks:


[2011-06-21 17:53:11] NOTICE[7557] chan_sip.c: Registration from '"XXXXXXXXXX"<sip:XXXXXXXXXX@123.123.123.123>' failed for '123.123.123.123' - Wrong Password


Adding the following line will block these attempts:

NOTICE.* .*: Registration from ‘\”.*\”.*’ failed for ‘<HOST>’ – Wrong password

Using new /var/log/asterisk/security

For this you will need an Asterisk that comes with the new Asterisk Security Framework (Asterisk 10+). You will also need to enable the log output in logger.conf by adding or uncommenting the line “security => security”. Likewise, you willl also need to ensure the date format has been changed in logger.conf to “dateformat=%F %T”.


# Fail2Ban configuration file
#
#
# $Revision: 250 $
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
#before = common.conf


[Definition]

#_daemon = asterisk

# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT
#

failregex = SECURITY.* SecurityEvent="FailedACL".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidAccountID".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="ChallengeResponseFailed".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidPassword".*RemoteAddress=".+?/.+?/<HOST>/.+?".*

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =




Next edit /etc/fail2ban/jail.conf to include the following section so that it uses the new filter. This does a 3-day ban on the IP that performed the attack. It is recommend to set the bantime in the [DEFAULT] section so if affects all attacks. It is also recommend to turn on an iptables ban for ssh, httpd/apache, and ftp if they are running on the system. Be sure to edit the sendmail-whois action to send notifications to an appropriate address:


Generic (without using /var/log/asterisk/security)


[asterisk-iptables]

enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
           sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@example.org]
logpath  = /var/log/asterisk/messages
maxretry = 5
bantime = 259200



note: logpath = /var/log/asterisk/messages is for vanilla asterisk, use logpath = /var/log/asterisk/full for freepbx. You can check the name of the log file in logger.conf.

note: if fail2ban still failed to identify login attempts, try the syslog logging way.

Using new /var/log/asterisk/security


[asterisk-iptables]
enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
           sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@example.org]
logpath  = /var/log/asterisk/security
maxretry = 5
bantime = 259200



Don’t Ban Yourself


We don’t want to ban ourselves by accident. Edit /etc/fail2ban/jail.conf and edit the ignoreip option under the [DEFAULT] section to include your IP addresses or network, as well as any other hosts or networks you do not wish to ban. Note that the addresses must be separated by a SPACE character!

Asterisk Logging


We must change how Asterisk does its time stamp for logging. The default format does not work with Fail2Ban because the pattern Fail2Ban uses that would match this format has a beginning of line character (^), and Asterisk puts its date/time inside of []. The other formats that Fail2Ban supports, however, do not have this character and can be used with Asterisk.

To change this format, open /etc/asterisk/logger.conf and add the following line under [general] section (You may have to create this before the [logfiles] section). This causes the date and time to be formatted as Year-Month-Day Hour:Minute:Second, [2008-10-01 13:40:04] is an example.


 [general]
 dateformat=%F %T



Then reload the logger module for Asterisk. At the command line, run the following command:

asterisk -rx “logger reload”

If for some reason you do not want to change the date/time format for your normal asterisk logs (maybe you already have scripts that use it or something and do not want to edit them), you can do the following instead:

In /etc/asterisk/logger.conf, add the following line under the [logfiles] section for Asterisk to log NOTICE level events to the syslog (/var/log/messages) as well as its normal log file. These entries in syslog will have a Date/Time stamp that is usable by Fail2Ban.

syslog.local0 => notice

Be sure to reload the logger module for Asterisk — check above for the command to do so. If you chose this option, you will also have to change the/etc/fail2ban/jail.conf setting under the [asterisk-iptables] section for the logpath option to the following:

logpath = /var/log/messages

Turning it On


Now it is time to put fail2ban to work. There are a couple steps we need to do first.

Turn IPTABLES on


By default, iptables allows all traffic. So if we turn it on, it will not block any traffic until Fail2Ban creates deny rules for attackers. You should create your own firewall rules and setup for iptables, but that is beyond the scope of this guide. Just know that Fail2Ban, by default, inserts rules at the top of the chain, so they will override any rules you have configured in iptables. This is good because you may allow all sip traffic in and then the Fail2Ban will block individual hosts, after they have done an attack, before they are allowed by this rule again.

To start iptables, run the following as root:

/etc/init.d/iptables start

Depending on your install, you may or may not have the iptables init script installed. Please refer to an iptables install/setup guide for your distribution for more information.

Turn on Fail2Ban


To start Fail2Ban, run the following as root:

/etc/init.d/fail2ban start

Check It


If both started properly, issue the following command to view your iptables rules:

iptables -L -v

You should see something like the following for the INPUT chain (you will see more if you have other Fail2Ban filters enabled):

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
2104K 414M fail2ban-ASTERISK all — any any anywhere anywhere

If you do not see something similar to that, then you have some troubleshooting to do; check out /var/log/fail2ban.log.

If you do not see all your rules, or if you see a different subset of rules after stopping and restarting fail2ban, you may be experiencing the issue described on this page on the Fail2ban talk:Community Portal and may wish to use the suggested fix:

fail2ban.action.action ERROR on startup/restart

I had multiple fail2ban.action.action ERROR on startup/restart. It seems there was a “race” condition with iptables. I solved the problem completely on my system by editing /usr/bin/fail2ban-client and adding a time.sleep(0.1)


def __processCmd(self, cmd, showRet = True):
	beautifier = Beautifier()
	for c in cmd:
		time.sleep(0.1)
		beautifier.setInputCmd(c)



Turn it on for good


If all is well up to this point, let’s make sure that fail2ban and iptables restart with the server by issuing the following commands.

Centos/Red Hat:

chkconfig iptables on
chkconfig fail2ban on

Debian/Ubuntu:

update-rc.d iptables defaults
update-rc.d fail2ban defaults

You should now be somewhat protected against SIP scans and brute force attacks!

Try a reboot


Once you have fail2ban working ok, make sure that it continues that way after rebooting the server. On some distributions (including Ubuntu daper) fail2ban won’t start after the system reboots because the /var/run/fail2ban directory gets deleted and needs to be re-created. This can be frustrating as there is also nothing that shows up in the logs to indicate what the problem is. If this happens, please see the link below for instructions on modifying the startup script so that it checks for and creates the /var/run/fail2ban directory if needed:

http://informationideas.com/news/2010/04/21/fail2ban-does-not-start-after-reboot/

Additional Information