'리눅스ETC'에 해당되는 글 39건

  1. 2016.03.30 vm.overcommit_memory
  2. 2016.03.30 메모리 사이즈별 my.cnf
  3. 2016.03.30 레드헷 로컬에서 yum 쓰기
  4. 2016.03.30 sftp 로그 남기기
  5. 2016.03.30 my.cnf utf8
  6. 2016.03.30 mysqldump
  7. 2016.03.30 mariaDB xtrabackup
  8. 2016.03.30 MySQL my.cnf
  9. 2016.03.30 자바 자체(셀프? 사설?)인증서 등록하기

vm.overcommit_memory

vm.overcommit_memory


0 : heuristic에 따라 overcommit 할 수 있고, 하지 않을 수도 있다.

메모리 요구가 있을 때 여유 공간이 없는 경우 실행중인 프로세스를 강제 종료 메모리를 억지로 확보함.


1 : 항상 overcommit 한다. 메모리를 다 사용했는데도 충분한 메모리가있는 것처럼... 


2 : overcommit하지 않는다. 메모리가 부족할 경우 메모리 확보시 에러발생




vm.overcommit_ratio


사용 가능한 메모리의 백분율로 정의. overcommit_ratio의 디폴트는 50.

'리눅스ETC' 카테고리의 다른 글

자바 프로세스별 힙메모리 상세보기  (0) 2016.03.30
특정날짜 이전/이후 데이터 찾기  (0) 2016.03.30
메모리 사이즈별 my.cnf  (0) 2016.03.30
레드헷 로컬에서 yum 쓰기  (0) 2016.03.30
sftp 로그 남기기  (0) 2016.03.30

32bit 2GB 

32bit 4GB

64bit 8GB 

64bit 16GB

64bit 32GB

 [mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

port = 3306

basedir = /mysql/

datadir = /data01/data

tmpdir = /tmp

thread_cache_size = 64

table_cache = 64

key_buffer = 64M

sort_buffer_size = 256K

read_buffer_size = 256K

read_rnd_buffer_size = 256K

max_allowed_packet = 1M

tmp_table_size=16M

max_heap_table_size=16M

query_cache_size=64M

query_cache_type=1

log_output=FILE

slow_query_log_file=/mysql/slow1.log

slow_query_log=1

long_query_time=3

log-error=/mysql/error.log

innodb_data_home_dir = /data01/data

innodb_data_file_path = ibdata1:1000M:autoextend

innodb_buffer_pool_size = 768M

innodb_additional_mem_pool_size = 8M

innodb_flush_log_at_trx_commit = 1

innodb_support_xa = 0

innodb_lock_wait_timeout = 50

innodb_flush_method=O_DIRECT

innodb_log_files_in_group = 2

innodb_log_file_size = 64M

innodb_log_buffer_size = 8M

innodb_thread_concurrency = 8

 [mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

port = 3306

basedir = /mysql/

datadir = /data01/data

tmpdir = /tmp

thread_cache_size = 64

table_cache = 64

key_buffer = 64M

sort_buffer_size = 256K

read_buffer_size = 256K

read_rnd_buffer_size = 256K

max_allowed_packet = 1M

tmp_table_size=16M

max_heap_table_size=16M

query_cache_size=64M

query_cache_type=1

log_output=FILE

slow_query_log_file=/mysql/slow1.log

slow_query_log=1

long_query_time=3

log-error=/mysql/error.log

innodb_data_home_dir = /data01/data

innodb_data_file_path = ibdata1:1000M:autoextend

innodb_buffer_pool_size =2048M

innodb_additional_mem_pool_size = 8M

innodb_flush_log_at_trx_commit = 1

innodb_support_xa = 0

innodb_lock_wait_timeout = 50

innodb_flush_method=O_DIRECT

innodb_log_files_in_group = 2

innodb_log_file_size = 128M

innodb_log_buffer_size = 8M

innodb_thread_concurrency = 8 

 [mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

port = 3306

basedir = /mysql/

datadir = /data01/data

tmpdir = /tmp

thread_cache_size = 128

table_cache = 256

key_buffer = 64M

sort_buffer_size = 256K

read_buffer_size = 256K

read_rnd_buffer_size = 256K

max_allowed_packet = 1M

tmp_table_size=32M

max_heap_table_size=32M

query_cache_size=128M

query_cache_type=1

log_output=FILE

slow_query_log_file=/mysql/slow1.log

slow_query_log=1

long_query_time=2

log-error=/mysql/error.log

innodb_data_home_dir = /data01/data

innodb_data_file_path = ibdata1:1000M:autoextend

innodb_buffer_pool_size = 5120M

innodb_additional_mem_pool_size = 8M

innodb_flush_log_at_trx_commit = 1

innodb_support_xa = 0

innodb_lock_wait_timeout = 50

innodb_flush_method=O_DIRECT

innodb_log_files_in_group = 2

innodb_log_file_size = 64M

innodb_log_buffer_size = 8M

innodb_thread_concurrency = 8

 [mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

port = 3306

basedir = /mysql/

datadir = /data01/data

tmpdir = /tmp

thread_cache_size = 128

table_cache = 512

key_buffer = 64M

sort_buffer_size = 256K

read_buffer_size = 256K

read_rnd_buffer_size = 256K

max_allowed_packet = 1M

tmp_table_size=32M

max_heap_table_size=32M

query_cache_size=128M

query_cache_type=1

log_output=FILE

slow_query_log_file=/mysql/slow1.log

slow_query_log=1

long_query_time=2

log-error=/mysql/error.log

innodb_data_home_dir = /data01/data

innodb_data_file_path = ibdata1:1000M:autoextend

innodb_buffer_pool_size = 12288M

innodb_additional_mem_pool_size = 8M

innodb_flush_log_at_trx_commit = 1

innodb_support_xa = 0

innodb_lock_wait_timeout = 50

innodb_flush_method=O_DIRECT

innodb_log_files_in_group = 2

innodb_log_file_size = 128M

innodb_log_buffer_size = 8M

nnodb_thread_concurrency = 12

 [mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

port = 3306

basedir = /mysql/

datadir = /data01/data

tmpdir = /tmp

thread_cache_size = 256

table_cache = 1024

key_buffer = 64M

sort_buffer_size = 256K

read_buffer_size = 256K

read_rnd_buffer_size = 256K

max_allowed_packet = 1M

tmp_table_size=32M

max_heap_table_size=32M

query_cache_size=128M

query_cache_type=1

log_output=FILE

slow_query_log_file=/mysql/slow1.log

slow_query_log=1

long_query_time=2

log-error=/mysql/error.log

innodb_data_home_dir = /data01/data

innodb_data_file_path = ibdata1:1000M:autoextend

innodb_buffer_pool_size =24676M

innodb_additional_mem_pool_size = 8M

innodb_flush_log_at_trx_commit = 1

innodb_support_xa = 0

innodb_lock_wait_timeout = 50

innodb_flush_method=O_DIRECT

innodb_log_files_in_group = 2

innodb_log_file_size = 128M

innodb_log_buffer_size = 8M

innodb_thread_concurrency = 16

'리눅스ETC' 카테고리의 다른 글

특정날짜 이전/이후 데이터 찾기  (0) 2016.03.30
vm.overcommit_memory  (0) 2016.03.30
레드헷 로컬에서 yum 쓰기  (0) 2016.03.30
sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30

레드햇 같은 상용리눅스를 라이센스없이 사용하면 yum을 쓸수 없다.

미디어 안에 있는 모든 rpm들을 서버로컬에 옮겨놓고 로컬데이터로 yum을 쓸수있게 해보자.


# 디렉토리하나 만들고 씨디 안에 rpm파일 몽땅 넣는다.

mkdir /REDHAT5.9

cp -a *.rpm /REDHAT5.9/


# 옮겨논 rpm중에 createrepo 패키지 설치해주고

rpm -ivh createrepo*.rpm


createrepo /REDHAT5.9



# vi /etc/yum.repos.d/local.repo

[Local-RHEL5.9]

name=Local-RHEL5.9

baseurl=file:///REDHAT5.9

enabled=1

gpgcheck=0

'리눅스ETC' 카테고리의 다른 글

vm.overcommit_memory  (0) 2016.03.30
메모리 사이즈별 my.cnf  (0) 2016.03.30
sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mysqldump  (0) 2016.03.30

sftp 로그 남기기

mysqldump



보안상 ftp보다 sftp를 선호하게된다.


물론 se 입장에선 추가적으로 프로그램을 설치하고 셋팅할 필요가 없기때문에 더 좋다.


다만 sftp는 기본적으로 전송관련된 로그를 남기지 않아 추가로 설정을 해줘야한다. (물론 접속로그는 secure 파일에 남는다.)



먼저 /etc/ssh/sshd_config  파일을 까고 잴 밑에 보면 아래같은  sftp 지원 옵션이 있다.


Subsystem       sftp    /usr/libexec/openssh/sftp-server


요기다가  -f local2 -l INFO 를 추가해주자


Subsystem       sftp    /usr/libexec/openssh/sftp-server -f local2 -l INFO




man페이지를 보면  더 정확하게 나오는데 간단하게만 적어보자.


-f 는 "facility code" 가 들어가는데 


DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7


요런 얘들이 들어갈수 있다. 기존 syslog  설정을 보고 안쓰는놈으로 등록하면 되겠다.



-l 은 로그레벨로 QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, DEBUG3 등이 들어갈 수 있다.


QUIET 쪽으로 갈수록 로그를 덜남기고 DEBUG3 쪽으로 갈수록 잡다한것까지 몽땅 다 남긴다.


일반적으로 필요한건 접속, 업로드, 다운로드, 삭제, 생성등이므로 INFO로 지정했다.



설정이 다 끝났다면  sshd  재시작하고...




syslog를 수정한다.


/etc/syslog.conf ( 혹은 /etc/rsyslog.conf ) 를 까서 잴 밑에 추가한다.


local2.*                                                /var/log/sftplog


그리고 syslog 도 재시작..




## 추가 ###

/etc/logrotate.d/syslog 를 까서 /var/log/sftplog에 대한 로테이트를 추가한다.

꼴리는대로 logrotate.d/ 에 별도로 생성해도 되겠다.



'리눅스ETC' 카테고리의 다른 글

메모리 사이즈별 my.cnf  (0) 2016.03.30
레드헷 로컬에서 yum 쓰기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mysqldump  (0) 2016.03.30
mariaDB xtrabackup  (0) 2016.03.30

my.cnf utf8

[mysqld]

default-character-set = utf8

init_connect=SET collation_connection=utf8_general_ci

init_connect=SET NAMES utf8

character-set-server = utf8

collation-server = utf8_general_ci


[client]

default-character-set=utf8


[mysqldump]

default-character-set=utf8


[mysql]

default-character-set=utf8

'리눅스ETC' 카테고리의 다른 글

레드헷 로컬에서 yum 쓰기  (0) 2016.03.30
sftp 로그 남기기  (0) 2016.03.30
mysqldump  (0) 2016.03.30
mariaDB xtrabackup  (0) 2016.03.30
MySQL my.cnf  (0) 2016.03.30

mysqldump

스키마와 데이터 덤프

mysqldump -u root -p DB_NAME > DUMPFILE_NAME.sql


스키마와 데이터와 routines(프로시져,함수) 몽땅 덤프

mysqldump -u root -p -R DB_NAME > DUMPFILE_NAME.sql

# -R, --routines


스키마만 덤프 

mysqldump -u root -p -d DB_NAME > DUMPFILE_NAME.sql

# -d, --no-data


데이터만 덤프

mysqldump -u root -t -d DB_NAME > DUMPFILE_NAME.sql

# -t, --no-create-info


routines 과 트리거만 덤프 

mysqldump -u root -p -R -t -d -n --skip-opt  DB_NAME > DUMPFILE_NAME.sql

# -n, --no-create-db

'리눅스ETC' 카테고리의 다른 글

sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mariaDB xtrabackup  (0) 2016.03.30
MySQL my.cnf  (0) 2016.03.30
자바 자체(셀프? 사설?)인증서 등록하기  (0) 2016.03.30

mariaDB xtrabackup

#풀백업


innobackupex --defaults-file=/etc/my.cnf --user=root --password=패스워드 --no-timestamp /app/DBBackup/Full


innobackupex --apply-log --redo-only /app/DBBackup/Full




#증분백업


to_lsn=`grep to_lsn /app/DBBackup/Full/xtrabackup_checkpoints | awk '{ print $3 }'`


innobackupex --user=root --password=패스워드 --incremental --incremental-lsn=$to_lsn --no-timestamp /app/DBBackup/Incremental-dir




#풀백업에 증분백업 엎기


innobackupex --apply-log --redo-only --incremental-dir=/app/DBBackup/Incremental-dir /app/DBBackup/Full




#엎고 증분백업 지우기


rm -rf /app/DBBackup/Incremental-dir






#복구


innobackupex --apply-log /app/DBBackup/Full


innobackupex --copy-back /app/DBBackup/Full


'리눅스ETC' 카테고리의 다른 글

sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mysqldump  (0) 2016.03.30
MySQL my.cnf  (0) 2016.03.30
자바 자체(셀프? 사설?)인증서 등록하기  (0) 2016.03.30

MySQL my.cnf

[mysqld]

# MySQL 서버 기본 옵션

datadir = /data/mysql

socket = /var/lib/mysql/mysql.sock

user=mysql

 

init_connect=SET collation_connection = utf8_general_ci

init_connect=SET NAMES utf8

character-set-server = utf8

collation-server = utf8_general_ci

 

big-tables

# 기본 엔진설정

default-storage-engine = InnoDB            

 

skip-host-cache

# 역DNS 검색 비활성

skip-name-resolve

# 외부(TCP/IP) 잠금 비활성        

skip-external-locking                  

 

max_connections = 500

table_cache = 256

wait_timeout = 50

 

## General 로그를 사용하려면 아래 설정은 그대로 유지하고

## MySQL 서버에 로그인한 후 “SET GLOBALgeneral_log=1″ 명령으로 활성화

# 0=제네럴로그 비활성

general_log = 1

# 제네럴로그 파일경로    

general_log_file = /var/log/mysql/general_query.log

 

## MySQL 에서는 지정된 시간 이상으로 쿼리가실행되는경우 해당 쿼리를 별도의 로그 파일로 남길수있다.(슬로우 쿼리 로그)

# DDL쿼리도 슬로우 쿼리에 기록

log_slow_admin_statements              

# 슬로우 쿼리로그 활성화

slow-query-log = 1

# 이 변수값보다 쿼리처리가 길게 걸린다면 에러로그에 기록       

long_query_time = 1    

# 슬로우 쿼리 로그파일 경로       

slow_query_log_file = /var/log/mysql/slow_query.log    

 

## MySQL 스케줄러를 사용하려면 아래 event-scheduler 옵션을 ON으로 변경

# event-scheduler = OFF                 # 이벤트 비활성

event-scheduler = ON

# 함수 sysdate()와 now() 동일하게 처리

sysdate-is-now                     

 

# 동시접속시 대기시킬수있는 커넥션 갯수

back_log = 100

# 최대 클라이언트 연결 갯수

max_connections = 300              

max_connect_errors = 999999

# 다쓴 쓰레드를 스레드풀에 저장할 갯수

thread_cache_size = 50

# 각 쓰레드별 오픈할 테이블수

table_open_cache = 400

# 커넥션 최대 대기시간(초)       

wait_timeout = 28800                   

# 요청된 쿼리의 최대길이의 값

max_allowed_packet = 32M   

# MEMORY 테이블의 최대크기     

max_heap_table_size = 32M

# 메모리 내의 임시테이블 크기 초과시 디스크에 저장              

tmp_table_size = 512K  

 

 

# 정렬에 필요한 버퍼의 크기 ORDER BY 또는 GROUP BY 연산 속도와 관련

# sort_buffer_size = 128K              

# 조인이 테이블을 풀스캔 하기위해 사용하는 버퍼크기

# join_buffer_size = 128K              

# 테이블 스캔에 필요한 버퍼크기

# read_buffer_size = 128K              

# 디스크 검색을 피하기위한 랜덤 읽기 버퍼크기

# read_rnd_buffer_size = 128K          

# 정렬에 필요한 버퍼의 크기 ORDER BY 또는 GROUP BY 연산 속도와 관련

sort_buffer_size = 512K                

# 조인이 테이블을 풀스캔 하기위해 사용하는 버퍼크기

join_buffer_size = 6K                      

# 테이블 스캔에 필요한 버퍼크기

read_buffer_size = 64K                 

# 디스크 검색을 피하기위한 랜덤 읽기 버퍼크기

read_rnd_buffer_size = 256K                

 

# 쿼리 결과를 캐싱라기 위해 할당된 메모리 크기

query_cache_size = 32M             

# 이 변수 값보다 큰 값은 캐싱이 안됨

query_cache_limit = 2M             

 

# GROUP_CONCAT()함수 사용시 컬럼값 최대크기

group_concat_max_len = 1024            

 

# 쓰레스 갯수

thread_concurrency = 2             

 

## 마스터 MySQL 서버에서 “레코드 기반 복제”를 사용할 대는 READ-COMMIT 사용 가능

## 복제에 참여하지 않는 MySQL 서버에서는 READ-COMMIT 사용 가능

## 그 외에는 반드시 REPEATABLE-READ로 사용

transaction-isolation = REPEATABLE-READ    

# isolation 레벨 [READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE]

 

# InnoDB 관련 옵션

# 테이블 단위로 테이블스페이스 할당, 활성시 확장자 .ibd 파일이 생성됨

innodb_file_per_table = 1              

# innodb 홈디렉터리 경로

innodb_data_home_dir = /data/mysql           

# 파일명 : 초기용량 : 자동증가 : 최대사이즈

innodb_data_file_path = ibdata1:256M:autoextend

#테이블 스페이스 자동 확장시 크기

innodb_autoextend_increment = 100          

innodb_log_group_home_dir = /data/mysql

# 로그 디렉터리 정보

innodb_log_arch_dir = /data/mysql              

# 데이터와 인덱스를 캐시하기 위해 사용하는 메모리 버퍼크기

innodb_buffer_pool_size = 10G              

                             

# innodb에서 사용할 메모리 양으로 전체 메모리의 50~80% 정도로 설정

# 데이터 디렉토리 정보와 내부 데이타 구조를 저장하는 메모리 풀의 크기

innodb_additional_mem_pool_size = 16M      

# Redo 로그 버퍼크기 

innodb_log_buffer_size = 16M               

 

# 로그 버퍼 사이즈로 성능에 맞춰 로그를 기록하는 경우 크게 설정

# 로그 파일 사이즈로 버퍼풀 사이즈의 25% 정도로 설정

innodb_log_file_size = 64M         

 

# 커밋 로그 옵션으로 성능 최적화로 1분마다 저장되도록 2로 설정      

# 1=트랜젝션 실행할때마다 로그 파일에 기록되고 디스크 플러시가 실행

innodb_flush_log_at_trx_commit = 2

                             

 

# 트렌젝션 two-phase commit 지원, 디스크 플러시 횟수를 줄여 성능항상

innodb_support_xa = OFF                

 

# InooDB내에 쓰레드 갯수, 변수 0은 쓰레드간 동시성 비활성화

# innodb_thread_concurrency = 0            

# 롤백이 진행되기 전에 LOCK을 대기하는 시간(초)

innodb_lock_wait_timeout = 20          

# 크래시 복구 모드 설정 

innodb_force_recovery = 0              

# 성능을 위해 메모리에서 직접 액세스 하도록 설정

innodb_flush_method = O_DSYNC              

 

innodb_purge_threads = 1

innodb-read-io-threads = 2

innodb-write-io-threads = 2

innodb_thread_concurrency = 6

innodb-buffer-pool-instance = 3

 

# O_DIRECT=운영체제의 버퍼를 사용 않고 IO 실행, RAID 컨트롤러(캐시메모리 장착된)가 없거나 SAN 사용시 O_DIRECT를 사용 하지 않음

# 이중 쓰기 버퍼 비활성

innodb_doublewrite = 0                 

# 쓰레드가 지연되기 전에 (suspended) 풀어 주기 위해 InnoDB 뮤텍스 (mutex)를 기다리는 쓰레드의 대기 시간

innodb_sync_spin_loops = 20                

# LOCK TABLES은 AUTOCOMMIT=0경우에, InnoDB로 하여금 내부적으로 테이블을 잠금

innodb_table_locks = 1             

# InnoDB 큐를 조이닝 (joining)하기 전에 InnoDB 쓰레드가 일시 정지 (sleep)하는 시간  

innodb_thread_sleep_delay = 1000           

# 퍼지 연산 (purge operation)이 래깅 (lagging)될 때 INSERT, UPDATE 및 DELETE 연산을 지연 시키는 방법을 제어,

# 디폴트값 0일시 지연 없음

innodb_max_purge_lag = 0               

# 동시에 실행되는 쓰레드의 숫자. 이 값이 0이 되면 동시성 제어 (concurrency control)가 비활성화

innodb_commit_concurrency = 0          

# InnoDB에 동시에 들어갈 수 있는 쓰레드의 숫자는 innodb_thread_concurrency 변수로 알아볼 수가 있다.

# 여러 개의 쓰레드가 이미 컨커런시 한계에 도달하였다면, 하나의 쓰레드만이 큐에 들어갈 수 있다.

# 하나의 쓰레드가 InnoDB에 들어가게 되면, innodb_concurrency_tickets의 값과 일치하는 “자유 티켓”의 숫자가 주어지고

# 쓰레드가 자신의 티켓을 사용하기 전 까지는 자유롭게 InnoDB에 들어가고 나올 수가 있다.

# 이런 후에는, 쓰레드는 다시금 일관성 검사를 하고 InnoDB에 다시 들어가려고 시도하게 된다 

innodb_concurrency_tickets = 500           

 

[mysql]

# MySQL 설정그룹

default-character-set=utf8

# 경고 발생시 메세지 자동 출력

show-warnings                      

# SQL 프롬프트 설정

prompt=u@h:d_R:m:s>             

# 데이터 출력시 페이징처리

# pager=”less -n -i -F -X -E”              

# 자동 완성 기능 비활성화

# no-auto-rehash                   

# 데이터 변경 또는 삭제시 where구문 필수입력

# safe-updates                     

 

[myisam]

# MyISAM 옵션 설정 기본 그룹

## InnoDB를 사용하지 않고 MyISAM만 사용한다면 key_buffer_size를 4GB까지 설정

# 인텍스 캐시 크기

key_buffer_size = 32M                  

# 대량 삽입에 사용된 트리 캐시의 크기, 쓰레드당 각각 할당됨

bulk_insert_buffer_size = 32M              

# 인덱스 정렬시 할당되는 버퍼의 크기

myisam_sort_buffer_size = 1M               

# 인덱스 재 생성시 사용할 임시 파일의 최대 크기

myisam_max_sort_file_size = 2G         

# 정렬 복구시 사용될 쓰레드 갯수

myisam_repair_threads = 1              

# MyISAM 테이블을 열었을시 테이블 자동복구

myisam_recover                     

# 하나의 FULLTEXT 인덱스에 포함 되는 단어의 최소 길이 값,

ft_min_word_len = 3                    

 

 

[mysqld_safe]

# 에러로그에 경고메세지 기록

log-warnings = 1                   

# 에러로그 파일경로

log-error=/var/log/mysqld.log              

# 프로세스 ID 파일경로

pid-file=/var/run/mysqld/mysqld.pid  

'리눅스ETC' 카테고리의 다른 글

sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mysqldump  (0) 2016.03.30
mariaDB xtrabackup  (0) 2016.03.30
자바 자체(셀프? 사설?)인증서 등록하기  (0) 2016.03.30

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.


javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


이런 오류들은 인증서가 없거나 사설인증서일 경우에 발생한다.


사내인트라넷 같은 시스템에 공인된 상용인증서를 쓰기에는 부담스럽기 때문에 사설인증서를 종종사용한다.


아무 작업없이 사설인증서를 사용하면 위와같은 에러를 만날수 있으며 이를 해결하기 위해서는


이런 사설인증서를 자바 ca 인증파일에 삽입해줘야한다.



#사설인증서 생성


openssl genrsa -out systemv.domain.com.key 2048

openssl req -new -key systemv.domain.com.key -out systemv.domain.com.csr

openssl req -new -key systemv.domain.com.key -x509 -out systemv.domain.com.crt

openssl req -new -x509 -nodes -sha1 -days 3600 -key systemv.domain.com.key -out server_ca.crt 




# ssl url 호출 테스트용 파일 sslCall.java


vi sslCall.java


import java.io.*;

import java.security.*;

import java.net.*;


public class sslCall {

  public static void main(String[] args) {

    String url    =  "https://systemv.domain.com:443";

    String responseMessage =  "";

    InputStream is   =  null;

    InputStreamReader isr =  null;

    BufferedReader br  =  null;

    StringBuffer sb = new StringBuffer();

    System.setProperty ( "java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");

    com.sun.net.ssl.internal.ssl.Provider provider = new com.sun.net.ssl.internal.ssl.Provider();

    Security.addProvider(provider);


    try{

      URL httpsUrl = new URL(url);

      URLConnection conn =  httpsUrl.openConnection();

      conn.setUseCaches(false);

      conn.setConnectTimeout(4000);

      conn.setDoOutput(true);

      conn.connect();

      responseMessage = conn.getHeaderField(0);

      System.out.println(responseMessage);


      is = conn.getInputStream();

      isr = new InputStreamReader(is);

      br = new BufferedReader(isr);


      String line = null;

      while((line=br.readLine()) != null){

        sb.append(line);

      }


      System.out.println(sb.toString());

    }catch(Exception e){

      e.printStackTrace();

    }

  }

}


javac sslCall.java

java sslCall


익셉션나면 문제가 있는거.




# 원격지 인증서 뽑아오기


vi InstallCert.java


import javax.net.ssl.*;

import java.io.*;

import java.security.KeyStore;

import java.security.MessageDigest;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;


public class InstallCert {


    public static void main(String[] args) throws Exception {

        String host;

        int port;

        char[] passphrase;

        if ((args.length == 1) || (args.length == 2)) {

            String[] c = args[0].split(":");

            host = c[0];

            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);

            String p = (args.length == 1) ? "changeit" : args[1];

            passphrase = p.toCharArray();

        } else {

            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");

            return;

        }


        File file = new File("jssecacerts");

        if (file.isFile() == false) {

            char SEP = File.separatorChar;

            File dir = new File(System.getProperty("java.home") + SEP

                    + "lib" + SEP + "security");

            file = new File(dir, "jssecacerts");

            if (file.isFile() == false) {

                file = new File(dir, "cacerts");

            }

        }

        System.out.println("Loading KeyStore " + file + "...");

        InputStream in = new FileInputStream(file);

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

        ks.load(in, passphrase);

        in.close();


        SSLContext context = SSLContext.getInstance("TLS");

        TrustManagerFactory tmf =

                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        tmf.init(ks);

        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];

        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);

        context.init(null, new TrustManager[]{tm}, null);

        SSLSocketFactory factory = context.getSocketFactory();


        System.out.println("Opening connection to " + host + ":" + port + "...");

        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

        socket.setSoTimeout(10000);

        try {

            System.out.println("Starting SSL handshake...");

            socket.startHandshake();

            socket.close();

            System.out.println();

            System.out.println("No errors, certificate is already trusted");

        } catch (SSLException e) {

            System.out.println();

            e.printStackTrace(System.out);

        }


        X509Certificate[] chain = tm.chain;

        if (chain == null) {

            System.out.println("Could not obtain server certificate chain");

            return;

        }


        BufferedReader reader =

                new BufferedReader(new InputStreamReader(System.in));


        System.out.println();

        System.out.println("Server sent " + chain.length + " certificate(s):");

        System.out.println();

        MessageDigest sha1 = MessageDigest.getInstance("SHA1");

        MessageDigest md5 = MessageDigest.getInstance("MD5");

        for (int i = 0; i < chain.length; i++) {

            X509Certificate cert = chain[i];

            System.out.println

                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());

            System.out.println("   Issuer  " + cert.getIssuerDN());

            sha1.update(cert.getEncoded());

            System.out.println("   sha1    " + toHexString(sha1.digest()));

            md5.update(cert.getEncoded());

            System.out.println("   md5     " + toHexString(md5.digest()));

            System.out.println();

        }


        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");

        String line = reader.readLine().trim();

        int k;

        try {

            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;

        } catch (NumberFormatException e) {

            System.out.println("KeyStore not changed");

            return;

        }


        X509Certificate cert = chain[k];

        String alias = host + "-" + (k + 1);

        ks.setCertificateEntry(alias, cert);


        OutputStream out = new FileOutputStream("jssecacerts");

        ks.store(out, passphrase);

        out.close();


        System.out.println();

        System.out.println(cert);

        System.out.println();

        System.out.println

                ("Added certificate to keystore 'jssecacerts' using alias '"

                        + alias + "'");

    }


    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();


    private static String toHexString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(bytes.length * 3);

        for (int b : bytes) {

            b &= 0xff;

            sb.append(HEXDIGITS[b >> 4]);

            sb.append(HEXDIGITS[b & 15]);

            sb.append(' ');

        }

        return sb.toString();

    }


    private static class SavingTrustManager implements X509TrustManager {


        private final X509TrustManager tm;

        private X509Certificate[] chain;


        SavingTrustManager(X509TrustManager tm) {

            this.tm = tm;

        }


        public X509Certificate[] getAcceptedIssuers() {

            throw new UnsupportedOperationException();

        }


        public void checkClientTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {

            throw new UnsupportedOperationException();

        }


        public void checkServerTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {

            this.chain = chain;

            tm.checkServerTrusted(chain, authType);

        }

    }


}



javac InstallCert.java

java InstallCert






# 원격지서버 인증서가져와서 저장


java -cp ./ InstallCert systemv.domain.com


.....에러 어쩌고

.......에러 저쩌고

Enter certificate to add to trusted keystore or 'q' to quit: [1]


뜨면 엔터쳐서 저장함.




...어쩌고

......저쩌고

Added certificate to keystore 'jssecacerts' using alias 'systemv.domain.com-1'



현재경로에 jssecacerts 라는 keystore가 생긴다. 


자바에는 기본 keystore가 두개가 있는데 cacerts 와 jssecacerts이다.(읽어들일때 jssecacerts가 우선순위가 높은듯)


$JAVA_HOME/jre/lib/security/ 에 jssecacerts 파일이 없다면 방금 생성된 jssecacerts 파일을 카피하는 것만으로도


아래 나오는 익스포트, 임포트 작업은 필요없다.





# 인증서 추출 ( 패스워드 "changeit" 은 디폴트값이므로 변경했다면 해당 변경값으로 입력)


keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert -alias systemv.domain.com-1




# 추출한 인증서를 로컬 JDK에 임포트


keytool -importcert -keystore /app/java/jdk1.7.0_40/jre/lib/security/cacerts -storepass changeit -file output.cert -alias systemv.domain.com-1




# 확인해보자


keytool -list -keystore /app/java/jdk1.7.0_40/jre/lib/security/cacerts | grep systemv





# 끝으로 sslCall 로 테스트 실행


java sslCall


익셉션 없이 HTTP/1.1 200 OK 찍히고 소스 보이면 굿




# 삭제는 요로케

keytool -delete -keystore /app/java/jdk1.7.0_40/jre/lib/security/cacerts -storepass changeit -alias systemv.domain.com-1



'리눅스ETC' 카테고리의 다른 글

sftp 로그 남기기  (0) 2016.03.30
my.cnf utf8  (0) 2016.03.30
mysqldump  (0) 2016.03.30
mariaDB xtrabackup  (0) 2016.03.30
MySQL my.cnf  (0) 2016.03.30

to Top