apache ssl 적용할때 mod_ssl.so 관련 에러 이슈

아파치(apache) 웹서버에서 ssl 설정을 하려고 할 때,

vhost 설정후 httpd -t 로 syntax 테스트를 해보면 오류 메세지가 나올때가 있다.

 

[root@ㅁㅁ]# httpd -t
httpd: Syntax error on line 221 of /etc/httpd/conf/httpd.conf: Syntax error on line 12 of /etc/httpd/conf.d/ssl.conf: Cannot load /etc/httpd/modules/mod_ssl.so into server: /etc/httpd/modules/mod_ssl.so: cannot open shared object file: No such file or directory
[root@ㅁㅁ]# whereis mod_ssl.so
mod_ssl:
[root@ㅁㅁ]# which mod_ssl.so
/usr/bin/which: no mod_ssl.so in (/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)
[root@ㅁㅁ]# vi /etc/httpd/conf/httpd.conf
[root@ㅁㅁ]# httpd -l
Compiled in modules:
  core.c
  prefork.c
  http_core.c
  mod_so.c

 

mod_ssl.so 를 찾아봐도 안나오고, 이럴땐 mod_ssl을 설치해줘야 한다.

 

[root@ㅁㅁ]#yum install mod_ssl

 

이후 ssl vhost 설정해주고, httpd -t 로 syntax 체크해 보고, 이상 없으면, apache restart 해주면 된다.

 

mod_so.c 와 mod_ssl.so 모두 있어야 ssl설정 가능함
없으면 yum으로 설치
#yum install mod_ssl

letsencrypt wildcard 인증서 자동 갱신 실패 이슈

letsencrypt wildcard 인증서 자동 갱신 실패 이슈

멀티 서브 도메인의 ssl인증서를 한번에 적용하는 인증서가 wildcard(*) 인증서다.
유료로 신청해서 사용할 수 있지만, 무료 letsencrypt 로도 발급 받을 수 있다.
다만, wildcard 인증서는 자동 갱신시 오류가 발생된다.


#certbot renew
Processing /etc/letsencrypt/renewal/aaabbb.com.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert is due for renewal, auto-renewing...
Could not choose appropriate plugin: The manual plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('An authentication script must be provided with --manual-auth-hook when using the manual plugin non-interactively.',)
Failed to renew certificate bizdaara.com with error: The manual plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('An authentication script must be provided with --manual-auth-hook when using the manual plugin non-interactively.',)

certbot renew 를 실행해보면, "--manual-auth-hook" 로 발급 받은 경우 동일하게 다시 발급해야 한다고 한다.
이건, --manual-auth-hook 로 발급 받을때 DNS에 txt 레코드를 추가 하는 과정이 다시 필요해서 그렇다고 한다.
즉, letsencrypt의 wildcard 인증서는 재발급시 DNS txt레코드도 새로 발급되어 DNS에 새로 등록 해줘야 하는 과정이 필요한데..
자동 갱신에선 이걸 해주지 못하니, 수동으로 발급을 해줘야 한다는 거다.

아쉽지만, 공짜 wildcard 인증서를 사용하려면, 3개월 마다 수동으로 갱신을 해줘야 한다.

또 새로운걸 알아가네~~

letsencrypt 와일드카드(Wildcard) 인증서 생성하기

우선 와일드카드(Wildcard) 인증서가 뭔지 보자.

구글에서 "와일드카드 인증서"라고 검색해보면 아래와 같은 내용이 나온다.

와일드카드(Wildcard) 인증서란, 도메인(FQDN) 의 하위 서브 도메인 호스트에 대해서 무제한 적용할수 있는 SSL 인증서 타입 입니다. 최근에 SSL 인증서 발급 약 40% 선이 Wildcard SSL 인증서로 발급이 되고 있으며, 이는 그만큼 효용성이 높다는 것을 증명합니다.

 

이 와일드카드 인증서를 생성하기 위해서는 SSL인증서 발급기관에 의뢰하게 되면 대충 10만원 이상의 비용이 발생한다.

하지만, letsencrypt를 이용하면 무료로 발급할 수 있다.

다만, 3개월에 한번씩 갱신해줘야 하는 단점이 있지만.. 이도 자동으로 갱신 설정을 해놓으면 된다.

 

이제 letsencrypt 로 와일드카드 인증서 생성을 하는 과정을 보자.

 

생성하고자 하는 도메인을 "abcd.com" 이라고 하자.

여기에 *.abcd.com 을 운영을 위해 와일드카드(wildcard) SSL 인증서를 만들어 보자.

[root@svr ~]# certbot certonly --manual --preferred-challenges dns -d "*.abcd.com" -d "abcd.com"

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator manual, Installer None
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/abcd.com.conf)

It contains these names: abcd.com

You requested these names for the new certificate: *.abcd.com,
abcd.com.

Do you want to expand and replace this existing certificate with the new
certificate?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(E)xpand/(C)ancel: E
Renewing an existing certificate for *.abcd.com and abcd.com
Performing the following challenges:
dns-01 challenge for abcd.com
dns-01 challenge for abcd.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please deploy a DNS TXT record under the name
_acme-challenge.abcd.com with the following value:

0l5sfzMfdL7gpoQaEbssassdfaIMqWNdf0o4drAZmmQasdfR9Smd

Before continuing, verify the record is deployed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Press Enter to Continue

위에서 확인된 DNS TXT값을 도메인관리 기관에서 해당 도메인의 TXT값으로 추가해준다.

호스트값 : _acme-challenge 

값 : 0l5sfzMfdL7gpoQaEbssassdfaIMqWNdf0o4drAZmmQasdfR9Smd

 

위 두개 값으로 dns관리에 추가해준다. 추가 dns에 적용이 된 후 이후 작업을 해야 하니,

아래 url에서 dns txt가 적용이 되었는지 확인을 해본다.
https://toolbox.googleapps.com/apps/dig/#TXT/_acme-challenge.domain.com
위 페이지에 접속해 조회할 도메인 정보를 입력하고 TXT 결과값을 확인해본다.
txt 결과값이 나오면 인증서 신청 화면에서 엔터를 치고,

두번째 TXT값을 확인한다.

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please deploy a DNS TXT record under the name
_acme-challenge.abcd.com with the following value:

8aOhySsbHUSKTsdfnDa9qwOstslSjlewLRjNx10cpsRqqaW

Before continuing, verify the record is deployed.
(This must be set up in addition to the previous challenges; do not remove,
replace, or undo the previous challenge tasks yet. Note that you might be
asked to create multiple distinct TXT records with the same name. This is
permitted by DNS standards.)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Press Enter to Continue


첫번째 TXT값과 동일한 등록 작업을 하고, dns txt값이 잘 나오는지 확인한 후 에 엔터를 친다.



IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/abcd.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/abcd.com/privkey.pem
   Your certificate will expire on 2024-03-11. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again. To non-interactively renew *all* of your
   certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

letsencrypt wildcard 인증서가 모두 생성이 되면 위와 같은 마지막 메세지가 나온다.

여기에서 위에 붉은색 부분을 이제 웹서버의 ssl vhost 설정에 추가해 주면 된다.


SSLCertificateFile /etc/letsencrypt/live/abcd.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/abcd.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/abcd.com/fullchain.pem

 

ssl vhost의 해당 도메인 부분에 위 인증서 정보를 추가해주고, 웹서버를 재시작 해주면 된다.

 

 

Support EFF's Work on Let's Encrypt

Protect digital privacy and free expression. The Electronic Frontier Foundation's public interest legal work, activism, and software development preserve fundamental rights.  EFF is a U.S. 501(c)(3) nonprofit,...

supporters.eff.org

 

 

 

끌어당겨셔 새로고침 하기 javascript 버젼 pullToRefresh

끌어당겨셔 새로고침 하기 javascript 버젼

모바일웹페이지에서 상단을 끌어당겨 새로고침을 하기
- 사용 모듈 : https://github.com/BoxFactura/pulltorefresh.js
- 사용 방법

< script src="https://github.com/BoxFactura/pulltorefresh.js"></ script>
< script>
    // initialize
    PullToRefresh.init({
      mainElement: '.global-body',
  instructionsPullToRefresh:'새로고침 하려면 당기세요',
  instructionsReleaseToRefresh:'새로고침 하려면 놓으세요',
  instructionsRefreshing :'새로고침 하는중...',
  shouldPullToRefresh:function(){return $('.global-body').scrollTop() === 0},
      onRefresh: function() { 
        // on refresh code goes here
        //alert('refresh') 
if($('.global-body').scrollTop() === 0){
location.reload(true);
}
      }
    });
</ script>

위에 간단하게 적용하는 스크립트이다.
내용은,
* mainElement : 새로고침할때 어떤 요소(element)앞에서 당겨지는지 해당 엘리먼트를 입력.
ㄴ적용해 보면 해당 엘리먼트(ID, class, element)앞에 새로고침하는 표시가 나오게 된다
* pullToRefresh가 기본으로 적용 되었을때는 영문으로 표시 되니, 텍스트로 변경할려고 하면 아래 정보를 변경한다
- instructionsPullToRefresh:'새로고침 하려면 당기세요',
- instructionsReleaseToRefresh:'새로고침 하려면 놓으세요',
- instructionsRefreshing :'새로고침 하는중...',
* 끌어당겨새로침 기능을 적용하다 보면, 스크롤을 내린 후 위로 올리는 동작중에 새로고침이 동작되는 경우가 있는데..
이때는 정확한 조건에 맞는지 확인을 해야 한다. 이 부분을 체크하는게 shouldPullToRefresh 부분이다.
- shouldPullToRefresh: 특정 엘리먼트의 scrollTop을 비교해서 처리하거나, 어떤 조건을 받아서 처리해 주면 된다.
ㄴ위 소스에서 처럼 하거나, mainElement가 body 가 아닌 경우
shouldPullToRefresh:function(){return !this.mainElement.scrollTop}

* onRefresh : 새로고침 처리 수행에 대한 결과 처리(action) 하는 부분. 
ㄴ일반적으로 페이지 새로고침. 그외 특별한 동작을 만들 수 있겠다.

리눅스 x윈도우 환경 설정하기 - xset

리눅스 설치 후 x윈도우 사용시 x윈도우에 대한 콘솔 설정하기

명령어 : xset

- x-window 환경에 대한 옵션을 설정한다

 

리눅스 데스크탑 설치후 스크린세이버, 절전모드를 비활성화하기 위해서 gui관리 메뉴를 통해 설정을 했지만 제대로 적용되지 않았다.

 

구글링을 해보니 xset 이라는 명령어를 통해 간단히 설정 할 수 있었다.

 

* screensaver off 하기

[root@localhost ~]# xset s off

 

* 절전모드 중지하기

[root@localhost ~]# xset -dpms

 

* 현재 설정되어 있는 x윈도우 환경 보기

[root@localhost ~]# xset -q

 

참고1 : xset 설정 (tistory.com)

 

xset 설정

xset SYNOPSISxset ← prompt 상에서 xset 명령어를 치시게 되면 아래와 같은 도움말이 출력됩니다. usage : xset [-display host:dpy] option ... To turn bell off: -b b off b 0 To set bell volume, pitch and duration: b [vol [pitch [dur]]

deois.tistory.com

참고2 : xset 명령 - IBM Documentation

 

xset 명령

용도X-Windows 환경에 대한 옵션을 설정합니다. 구문xset [  -디스플레이 디스플레이 ] [  b [  볼륨  [  피치  [  지속 기간  ] ] ] |  -b |   ... 에 대한 |  b 오프 ] [  백작 | tert-부틸  ]  c.  

www.ibm.com

 

업로드 디렉토리 php 실행 방지하기

apache 서버로 파일서버 운영하면서

업로드 디렉토리에 원치 않는 php, html 등과 같은 실행파일이 올라가는 경우가 있다

이럴 경우,

특정 디렉토리를 제외한 모든 업로드 디렉토리에서 php가 실행 되지 않게 해야 할 경우

 

"php_admin_flag engine off

 

를 이용해 주면 된다.

이 옵션을 httpd.conf에 설정해 여러 vhost에 동일하게 적용할 수 있다.

또는 특정 VirtualHost 부분에만 추가해서 적용도 가능하다.

 

<Directory "/home/제한할디렉토리/">
    <FilesMatch "\.(html|php|php3)$">
        php_admin_flag engine off
    </FilesMatch>
</Directory>

 

php 코드가 실행되지 않게 하려면 위와 같은 코드를 httpd.conf에 추가해 주면 된다.

이때, 특정 디렉토리는 php 실행을 허용해야 한다면, 

 

<Directory "/home/허용할디렉토리/">
    <FilesMatch "\.(html|php|php3)$">
        php_admin_flag engine on
    </FilesMatch>
</Directory>

 

와 같이 해주면 된다.

 

위 설정은

- apache2.4

- php 5.6

환경에서 적용한 방법이다.

certbot 갱신 실패 - apache plugin 오류

인증서 갱신일이 얼마 안남았다고 인증서 생성시 지정한 메일로 알림 메일을 받았다.
자동으로 갱신하도록 크론탭에 작성을 해놨었는데....
수동으로 확인을 해보니.. 아래와 같은 내용이 출력되며 갱신 실패.

[root@kidd ~]# /usr/bin/certbot renew
Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/AAAA.co.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not yet due for renewal

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/BBBB.co.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert is due for renewal, auto-renewing...
Could not choose appropriate plugin: The requested apache plugin does not appear to be installed
Failed to renew certificate kidd.co.kr with error: The requested apache plugin does not appear to be installed

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/CCCC.co.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not yet due for renewal

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/www.AAAA.co.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not yet due for renewal

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The following certificates are not due for renewal yet:
  /etc/letsencrypt/live/AAAA.co.kr/fullchain.pem expires on 2023-01-27 (skipped)
  /etc/letsencrypt/live/BBBB.co.kr/fullchain.pem expires on 2023-02-17 (skipped)
  /etc/letsencrypt/live/www.AAAA.co.kr/fullchain.pem expires on 2023-02-03 (skipped)
All renewals failed. The following certificates could not be renewed:
  /etc/letsencrypt/live/BBBB.co.kr/fullchain.pem (failure)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1 renew failure(s), 0 parse failure(s)


내용인 즉, apache plugin이 설치가 안되었다는 거 같은데...
letsencrypt 설치할때.. 그런거를 못봤던거 같고. 
인증서 생성시 생성 옵션이 뭔가 이전보다 적었다는거... 그정도 생각이 떠오른다..

구글신에게 물어보니...
"The requested apache plugin does not appear to be installed" 이 질문에 대한 여러 답변중에
python 관련 apache plugin을 설치하라는거가 있었다.
"python2-certbot-apache" - CentOS 7"python3-certbot-apache" - CentOS 8

현재 설치된 letsencrypt 의 plugin을 확인해보니, 아래와 같다.

[root@~]# certbot plugins
Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* standalone
Description: Spin up a temporary webserver
Interfaces: IAuthenticator, IPlugin
Entry point: standalone = certbot._internal.plugins.standalone:Authenticator

* webroot
Description: Place files in webroot directory
Interfaces: IAuthenticator, IPlugin
Entry point: webroot = certbot._internal.plugins.webroot:Authenticator
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

역시, apache 어쩌고는 없다.


현재 서버 버젼이 CentOS7 버젼이니, "python2-certbot-apache"를 설치하면 되겠다.
[root@~]# yum install certbot python2-certbot-apache

설치하고 나서 갱신을 해보니, 잘 되고, plugin도 확인해보니, apache plugin이 나온다.

[root@~]# certbot plugins
Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* apache
Description: Apache Web Server plugin
Interfaces: IAuthenticator, IInstaller, IPlugin
Entry point: apache = certbot_apache._internal.entrypoint:ENTRYPOINT

* standalone
Description: Spin up a temporary webserver
Interfaces: IAuthenticator, IPlugin
Entry point: standalone = certbot._internal.plugins.standalone:Authenticator

* webroot
Description: Place files in webroot directory
Interfaces: IAuthenticator, IPlugin
Entry point: webroot = certbot._internal.plugins.webroot:Authenticator
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


결론, 
letsencrypt 를 설치하고 인증서 생성시 apache 옵션이 안보이거나,
인증서 갱신시 apache plugin 어쩌고 하는 빨간색 오류줄이 보이면,
주저없이 OS버젼에 맞게 python2-certbot-apache를 설치해주면 된다.

 

letsencrypt 설치시 처음부터 apache plugin까지 설치하면 더 좋겠다.

[root@~] yum install certbot python2-certbot-apache 

특정IP가 아닌 user-agent 네이밍(이름)으로 접속이 많은 경우 차단하기

1. 접속하는 user-agent를 확인하다.
- 로그 기록을 combined 로 변경해 user-agent가 기록 되게 수정
- 로그 체크해서 user-agent를 확인한다.
- http.conf 를수정한다.


SetEnvIfNoCase User-Agent "^amazonaws" bad_bot
SetEnvIfNoCase User-Agent "^amazonaws.com" bad_bot
SetEnvIfNoCase User-Agent "^compute-1.amazonaws.com" bad_bot
SetEnvIfNoCase User-Agent "^BUbiNG" bad_bot
SetEnvIfNoCase User-Agent "^MJ12bot" bad_bot
<Directory "/home/daara">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
Deny from env=bad_bot
</Directory>

- 웹서버 재시작해준다.
- 로그 체크해보면 403 forbidden 상태 기록되는거 확인한다.

 

이 방법은 크롤링하는것들중 잡스러운것들에 대한 접속 차단할때 유용하다.

 

하나의 네트워크카드에 다중 IP 설정하기

리눅스에 단일 랜카드에 다중 IP추가하기

1. 현재의 IP설정 상태를 확인해본다.

#cd /etc/sysconfig/network-scripts

#vi ifcfg-eth0

ifcfg-eth0에는 현재 ip설정에 대한 정보가 담겨 있다.

 

2. ifcfg-eth0 를 복사해준다.

#cp ifcfg-eth0 ifcfg-eth0:0

복사를 하지 않고 직접 ifcfg-eth0:0 파일을 만들어 줘도 된다.

 

3. 복사한 ifcfg-eth0:0 파일에서 추가할 ip정보로 수정해 준다.

#vi ifcfg-eth0:0

DEVICE=eth0:0
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.0.100
GATEWAY=192.168.0.1
NETMASK=255.255.255.0

 

위 내용 정도만으로 작성해 주면된다.

 

4. ip를 활성화 하기 위해 networt 서비스를 재시작 해준다.

#service network restart

 

5. 적용이 잘되었는지 확인

#ifconfig

ifconfig를 현재 네트워크 설정 상태정보를 확인해 봤을대,

기존 eth0 와 새로 추가한 eth0:0 가 잘 나오면 이상 없이 적용된것이다.

물론, console을 이용해 새로 추가한 ip로 접속을 해봐도 될것이고.

 

 

 

letsencrypt ssl인증서 갱신, 생성 오류 사례

신규 인증서 생성시 아래와 같은 오류 발생 대처
에러1 -------------------------
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
An unexpected error occurred:
TypeError: __str__ returned non-string (type Error)
Please see the logfiles in /var/log/letsencrypt for more details.
해결 -------------------------
pip install urllib3==1.26.7
pip install requests==2.11.1



에러2 --------------------------
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
An unexpected error occurred:
SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",)

해결 ---------------------------
# --no-verify-ssl 옵션을 추가해서 생성한다. 
certbot certonly --no-verify-ssl

apache 웹서버 재시작(restart)가 안된다

우씨~ apache(httpd)가 갑자기 실행이 안된다......
별로 한것도 없는데.. 

[root@test119 ~]# systemctl start httpd
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
[root@test119 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since 목 2021-11-25 10:23:58 KST; 20s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 7536 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 32225 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)
  Process: 7523 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 7523 (code=exited, status=1/FAILURE)

11월 25 10:23:58 test119 systemd[1]: Starting The Apache HTTP Server...
11월 25 10:23:58 test119 systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
11월 25 10:23:58 test119 kill[7536]: kill: cannot find process ""
11월 25 10:23:58 test119 systemd[1]: httpd.service: control process exited, code=exited status=1
11월 25 10:23:58 test119 systemd[1]: Failed to start The Apache HTTP Server.
11월 25 10:23:58 test119 systemd[1]: Unit httpd.service entered failed state.
11월 25 10:23:58 test119 systemd[1]: httpd.service failed.


config파일들 syntex는 이상없는데..
ssl인증서 기간도 남아 있는데.. 
이것저것 구글링을 하다 보니, 에러로그를 확인해보라고 한다.
내가 아는 에러로그는 apache(httpd) 실행중에 생기는 문제를 기록하는것으로 아는데...
apache가 실행되면서도 잠깐이지만 바로 로그를 기록하는듯... 암튼.
로그를 확인해보니, 

[root@test119 conf.d]# tail /var/log/httpd/error_log
AH00016: Configuration Failed
[Thu Nov 25 10:23:58.816796 2021] [suexec:notice] [pid 7523] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Nov 25 10:23:58.817714 2021] [core:emerg] [pid 7523] (28)No space left on device: AH00023: Couldn't create the ssl-cache mutex
AH00016: Configuration Failed
[Thu Nov 25 10:28:10.437030 2021] [suexec:notice] [pid 7634] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Nov 25 10:28:10.459085 2021] [core:emerg] [pid 7634] (28)No space left on device: AH00023: Couldn't create the rewrite-map mutex
[Thu Nov 25 10:28:10.459102 2021] [:emerg] [pid 7634] AH00020: Configuration Failed, exiting
[Thu Nov 25 10:29:02.522577 2021] [suexec:notice] [pid 7684] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Nov 25 10:29:02.544507 2021] [core:emerg] [pid 7684] (28)No space left on device: AH00023: Couldn't create the rewrite-map mutex
[Thu Nov 25 10:29:02.544526 2021] [:emerg] [pid 7684] AH00020: Configuration Failed, exiting

첨 보는 에러로그다. 
No space left on device: AH00023 ...... 이거 공간이 부족한가?

[root@test119 conf.d]# df
Filesystem           1K-blocks      Used  Available Use% Mounted on
/dev/mapper/cl-root 1942918240 179468112 1763450128  10% /
devtmpfs               4021816         0    4021816   0% /dev
tmpfs                  4037988         0    4037988   0% /dev/shm
tmpfs                  4037988    189684    3848304   5% /run
tmpfs                  4037988         0    4037988   0% /sys/fs/cgroup
tmpfs                  4037988         0    4037988   0% /tmp
/dev/sda2              1038336    169552     868784  17% /boot
/dev/sda1               204580      9672     194908   5% /boot/efi
tmpfs                   807600         0     807600   0% /run/user/0

디시크공간 이상없는데...

Couldn't create the ssl-cache mutex AH00016: Configuration Failed
이건 뭘까.... 구글링 해보자.

 


두번째 "내일은 치킨집 CEO"님의 포스팅 먼저...(국문이라...).
https://www.enteroa.com/tag/no-space-left-on-device/

"Semaphore"라는 프로세스가 생성되었다가 없어지지 않아서...
엄밀히 말하면, "Semaphore" 프로세스 생성 가능한 숫자를 이미 초과해서(No space left on device) 
apache(httpd)가 시작시 새로운 "Semaphore"를 생성하지 못하면서 apache(httpd) 실행이 안된다고 한다.

이건, "Semaphore"가 아파치의 여러 프로세스간 데이타 동기화를 위해 필요한데..
apache(httpd)가 비정상적으로 종료될때 이미 생성된 "Semaphore"를 초기화 되지 못해 그렇다고 한다.

암튼, 일단 
해당 프로세스가 얼마나 있는지 확인

[root@test119 conf.d]# ipcs -s | wc -l
130

130개가 현재 존재중이다.

그럼 최대가능수는?
[root@test119 conf.d]# ipcs -ls

------ Semaphore Limits --------
max number of arrays = 128
max semaphores per array = 250
max semaphores system wide = 32000
max ops per semop call = 32
semaphore max value = 32767

현재 max number of arrays 는 128개라고 한다.
이미 초과했고, 초기화(종료) 되어 있지 않아서 apache(httpd)가 실행이 안되니, 
현재 생성되어 있는 Semaphore 를 초기화 하자.
[root@test119 conf.d]# ipcrm -a
[root@test119 conf.d]# ipcs -s | wc -l
4

이제 4개 있다고 한다.(어디서 생성되었지? 초기화 하자 마자 생성되네...)
다시 apache(httpd) 실행을 해보니 잘된다.
[root@test119 conf.d]# systemctl start httpd


이번 에러는 첨 경험해보는 경우이다.
system관리 ..... 넘 어려줘~~



참조 페이지
https://www.enteroa.com/tag/no-space-left-on-device/
https://serverfault.com/questions/991946/no-space-left-on-device-ah00023-couldnt-create-the-mpm-accept-mutex-when-re

mysql replication error - 복제 오류 복구 하기

#slave에서 로그 확인
> show status slave;
+----------------+----------------+-------------+-------------+---------------+------------------+---------------------+-------------------------+---------------+-----------------------+------------------+-------------------+-----------------+---------------------+--------------------+------------------------+-------------------------+-----------------------------+------------+------------+--------------+---------------------+-----------------+-----------------+----------------+---------------+--------------------+--------------------+--------------------+-----------------+-------------------+----------------+-----------------------+-------------------------------+---------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------------+----------------+
| Slave_IO_State | Master_Host    | Master_User | Master_Port | Connect_Retry | Master_Log_File  | Read_Master_Log_Pos | Relay_Log_File          | Relay_Log_Pos | Relay_Master_Log_File | Slave_IO_Running | Slave_SQL_Running | Replicate_Do_DB | Replicate_Ignore_DB | Replicate_Do_Table | Replicate_Ignore_Table | Replicate_Wild_Do_Table | Replicate_Wild_Ignore_Table | Last_Errno | Last_Error | Skip_Counter | Exec_Master_Log_Pos | Relay_Log_Space | Until_Condition | Until_Log_File | Until_Log_Pos | Master_SSL_Allowed | Master_SSL_CA_File | Master_SSL_CA_Path | Master_SSL_Cert | Master_SSL_Cipher | Master_SSL_Key | Seconds_Behind_Master | Master_SSL_Verify_Server_Cert | Last_IO_Errno | Last_IO_Error                                                                                                                               | Last_SQL_Errno | Last_SQL_Error |
+----------------+----------------+-------------+-------------+---------------+------------------+---------------------+-------------------------+---------------+-----------------------+------------------+-------------------+-----------------+---------------------+--------------------+------------------------+-------------------------+-----------------------------+------------+------------+--------------+---------------------+-----------------+-----------------+----------------+---------------+--------------------+--------------------+--------------------+-----------------+-------------------+----------------+-----------------------+-------------------------------+---------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------------+----------------+
|                | 192.168.10.1 | repluser    |        3306 |            60 | mysql-bin.000028 |           967473320 | mysqld-relay-bin.000075 |     967473465 | mysql-bin.000028      | No               | Yes               |                 |                     |                    |                        |                         |                             |          0 |            |            1 |           967473320 |       967473664 | None            |                |             0 | No                 |                    |                    |                 |                   |                |                  NULL | No                            |          1236 | Got fatal error 1236 from master when reading data from binary log: 'Client requested master to start replication from impossible position' |              0 |                |
+----------------+----------------+-------------+-------------+---------------+------------------+---------------------+-------------------------+---------------+-----------------------+------------------+-------------------+-----------------+---------------------+--------------------+------------------------+-------------------------+-----------------------------+------------+------------+--------------+---------------------+-----------------+-----------------+----------------+---------------+--------------------+--------------------+--------------------+-----------------+-------------------+----------------+-----------------------+-------------------------------+---------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------------+----------------+

#에러 스킵 시도
> stop slave;SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;start slave;
--> 복제 오류 지속됨.


#현재 master binlog 포지션 이후 로그 기록 확인
> show binlog events in 'mysql-bin.000028' from 967473320 limit 3\G;
Empty set (0.00 sec)

ERROR:
No query specified
--> 데이타가 없다고 함


#현재 binlog파일의 마지막 로그 추출후 확인
> mysqlbinlog --no-defaults --database=daara_db --start-date="2021-10-18 04:30:00" --stop-date="2021-10-18 04:40:00" /var/lib/mysql/mysql-bin.000028 > binlog1018.sql
--> 최종 로그 포지션 안맞음.(더이상없음)
#새로운 binlog파일의 시작 체크
> mysqlbinlog --no-defaults --database=daara_db --start-date="2021-10-18 04:30:00" --stop-date="2021-10-18 04:40:00" /var/lib/mysql/mysql-bin.000029 > binlog1018.sql
--> 해당 시작 포지션 확인후 slave에서 master position 변경

--Slave
> STOP SLAVE;
> CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000029', MASTER_LOG_POS=4;
> START SLAVE;
> SHOW SLAVE STATUS\G; -- 에러확인
--> 복제 정상 동작

 

 

 

잘 진행되던 복제가 오류 났을때, 전에는 일반적으로 "SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1"를 실행해서 해결하고는 했다. 그런데 이번에는 그렇게 되지 않아 좀 애먹었다. 

위에서 보는거 처럼, 오류난 로그 포지션을 스킵을 해줘도 안되서, 현재 오류나는 곳의 binlog파일과, master position을 확인해서 해당 binlog파일을 열어 최종 로그를 확인해보니, 오류나는 binlog에는 해당 포지션이 존재하지 않았다.

아마도, 서버의 오류로 인해 binlog 기록이 잘못되었던거 같다.

 

binlog파일들을 확인해서 현재 오류나는 binlog 다음 파일을 확인 해서 position을 변경해주고 시작하니 이상 없이 복제가 잘되었다.

 

 

DOMDocument()를 이용해 입력된 string에서 html의 유효성을 체크해 보자

libxml_use_internal_errors(user_errors)
- libxml의 표준 에러 정보를 비활성화 하고, 사용자 정의 오류를 할 수 있도록 해줌.
- user_errors : option 항목으로 사용자 오류 처리가 가능할지 여부를 지정. 기본값은 false

libxml_clear_errors()
- libxml 오류 버퍼를 지움.

libxml_get_errors()
- libxml 오류 버퍼가 있을때 오류 정보를 배열로 반환. 없을때는 빈 배열을 반환함.


위 정보와 DOMDocument()를 이용해 입력된 string에서 html의 유효성을 체크해 보자

$string = '<div>안녕하세요</div><span>네. 안녕하세요';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
libxml_clear_errors();
$doc_re = $doc->loadHTML($string);

if(count(libxml_get_errors())>0)  echo '에러 발생';

에러 존재 여부에 따라서 이후 처리를 해주면 되겠다.

mysql binlog에서 특정 위치(position) 읽어보기

mysql 서버 쌓이는 binlog를 특정 position에서 최근 로그를 읽어보자.

 

mysql> show binlog events in 'mysql-bin.000011' from 850378398 limit 3\G;

*************************** 1. row ***************************
   Log_name: mysql-bin.000011
        Pos: 850378398
 Event_type: Intvar
  Server_id: 154
End_log_pos: 850378426
       Info: INSERT_ID=6631643
*************************** 2. row ***************************
   Log_name: mysql-bin.000011
        Pos: 850378426
 Event_type: Query
  Server_id: 154
End_log_pos: 850378632
       Info: use `db`; insert LOW_PRIORITY into log (admin_id, admin_log, remote_addr, im_log_seq) values ('best','message:view','61.250.146.69', 727044)
*************************** 3. row ***************************
   Log_name: mysql-bin.000011
        Pos: 850378632
 Event_type: Intvar
  Server_id: 154
End_log_pos: 850378660
       Info: INSERT_ID=679994370
3 rows in set (0.00 sec)

 

 

위와 같이 하면 결과가 검색하는 포지션 위치에서 최근 3개의 로그를 읽을 수 있다.

특정 포지션에서 로그를 확인할때 사용할수 있겠다.

 

 

* binlog - mysql binary log는 DDL(create, drom, alter)문과, DML(insert, update, delete)를 통해 수행되는 db query 문들의 정보를 저장한다고 보면 된다. 단, show 나 select문은 저장되지 않는다. 

이 binlog는 DB를 복제(replication)하거나, 특정 시점에 있었던 query를 확인하고 복구하는데도 사용이 가능하다.

 

아래 해당 내용이 잘 소개된 이웃글이 있으니 상세한 부분이 궁금하면 방문해길..

https://myinfrabox.tistory.com/20

letsencrypt 인증서 다른서버로 복사하기

letsencrypt 인증서 생성 후 서버를 이전 또는 이중화 하는 경우가 있을것이다.

이때 기존 생성한 인증서를 복사한 방법은 아래와 같다.

 

우선 인증서가 설치된 위치로 이동한다.

cd /etc/letsencrypt

이동 후 하위의 디렉토리들을 확인하고, 하위 디렉토리중 

인증서 정보, 설정 정보, 갱신정보가 있는

"archarchive", "live", "renewal", "renewal-hooks" 를 복사한다.

이때, 특정 도메인만 하겠다고 하면 해당 도메인 인증서만 복사한다.

 

두번째로 기존 인증서에 사용하는 계정정보(account)를 확인해 둔다.

이 부분이 중요한데, 다른서버에서 계정정보가 다르기 때문에 타겟 서버에 이동후 인증서 파일정보에 있는 계정을 타켓서버에 맞게 변경을 해줘야 한다.

 

타겟서버에서도 letsencrypt의 인증서 계정정보를 확인한다.

ls /etc/letsencrypt/accounts/acme-v02.api.letsencrypt.org/directory/

위와 같이 하거나, 타겟서버에서 생성된 인증서가 있다면 해당 인증서의 설정 파일을 열어 확인해도 된다.

 

복사한 원본 letsencrypt 인증서를 타겟서버에 복사한다.

 

마지막으로 복사한 인증서 정보에서 account 를 변경해 준다.

sed -i 's/old계정/new계정/' /etc/letsencrypt/renewal/*

 

참고 url : community.letsencrypt.org/t/copy-etc-letsencrypt-or-regenerate-to-move/141684/3

 

on duplicate key update 사용시 last_Insert_Id 가져오기

mysql 에서 insert 와 update를 한번의 query에서 할 수 있는 방법은

 

"on duplicate key update" 기능을 이용하면된다.

 

그런데, insert 구문으로만 등록시 lastInsertId는 잘 가져오는데,

 

"on duplicate key update"를 붙여주면 lastInsertId를 못가져오는 경우가 발생한다.

 

아마도 update구문이 같이 있다보니, 그러는거 같은데... 흠..

 

이를 해결하기 위해서는,

당연히 auto_increment 컬럼(expr)이 있어야 하며,

이를 on duplicate key update 구문에 추가해 주면 된다.

 

insert into ebook (expr, name,title) values (0, 'test','asfdafd') on duplicate key update name='test',title='asfdafd', expr=last_insert_id(expr);

 

이렇게 하면 insert 가 실행되고 나서 last_insert_id()를 가져올 수 있다.

 

 

 

데이타를 엑셀 시트로 작성시 유용한 스타일

데이타를 엑셀(excel) 시트로 작성시 유용한 스타일

 

1. 숫자를 일반문자 형태로 처리

style='mso-number-format:"\@";'

 

2. 숫자로 3자리마다(천단위) 콤마 찍기

style='mso-number-format:"\#\,\#\#0_;'

 

3. 한 셀(sale cell)에 줄바꿈(newline) 처리가 필요할때

style='mso-data-placement:same-cell;'

 

 

 

letsencrypt ssl인증서 만료 갱신 오류 해결 - webroot 관련

ssl인증서는 최근 웹서비스에서는 필요불가결한 서비스이다.

여러 웹서비스를 운영할 경우 상당히 많은 부분에 ssl 인증서가 필요하다 보니 비용 문제에 직면하게 된다.

 

그래서, 무료로 사용이 가능한 letsencrypt 인증서를 많이들 사용하는데....

잘만 관리해주면 상당히 괞찮은 ssl 적용 방법이라고 생각된다.

 

다만, 가끔씩 갱신이 잘 안된다거나, 갱신 오류가 발생하기도 하는데...

오늘은 아래와 같은 오류에 대해서 해결하는 방법을 공유해 본다.

 

 

letsencrypt ssl 인증서 갱신하기

 

우선, 인증서를 적용하는 도메인을 aaaa.bbbb.kr 이라고 가정하고..

 

리눅스 크론탭(crontab)에 통해 매달 2일정도 갱신을 시도하도록 스케줄링을 적용해 놓았다.

# letsencrypt renew
00 5 10,16 * * root /root/letsencrypt/certbot-auto renew >> /var/log/letsencrypt/renew.log

 

그런데, 확인을 해보니, 인증서 만료일이 갱신되지 못하고 실패가 나고 있었다.

그래서, 직접 갱신 시도를 해보았다.

 

#cd /root/letsencrypt

#./certbot-auto renew

 

갱신을 실행해 보니, 아래와 같은 메세지가 출력되었다.

 

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/aaaa.bbbb.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert is due for renewal, auto-renewing...
Plugins selected: Authenticator webroot, Installer None
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for aaaa.bbbb.kr
Cleaning up challenges
Attempting to renew cert (aaaa.bbbb.kr) from /etc/letsencrypt/renewal/aaaa.bbbb.kr.conf produced an unexpected error: Missing command line flag or config entry for this setting:
Input the webroot for aaaa.bbbb.kr:. Skipping.
All renewal attempts failed. The following certs could not be renewed:
  /etc/letsencrypt/live/aaaa.bbbb.kr/fullchain.pem (failure)

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

All renewal attempts failed. The following certs could not be renewed:
  /etc/letsencrypt/live/aaaa.bbbb.kr/fullchain.pem (failure)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1 renew failure(s), 0 parse failure(s)

 

내용을 보니, 뭔가 수정을 하라는거 같은데....

오류 내용에 뭔가 빠져 있다고 하는거 같고... 그게 webroot 와 관련되는거 같고...

그래서 구글링을 통해 확인을 해보니...

configuration 파일(/etc/letsencrypt//renewal/aaaa.bbbb.kr.conf)에 webroot 정보가 빠져서 그렇다고 한다.

 

설정파일을 열어 확인해보니, 해당 부분이 없서 추가 해주었다.

 

#vi /etc/letsencrypt/renewal/aaaa.bbbb.kr.conf

# renew_before_expiry = 30 days
version = 0.38.0
archive_dir = /etc/letsencrypt/archive/aaaa.bbbb.kr
cert = /etc/letsencrypt/live/aaaa.bbbb.kr/cert.pem
privkey = /etc/letsencrypt/live/aaaa.bbbb.kr/privkey.pem
chain = /etc/letsencrypt/live/aaaa.bbbb.kr/chain.pem
fullchain = /etc/letsencrypt/live/aaaa.bbbb.kr/fullchain.pem

# Options used in the renewal process
[renewalparams]
server = https://acme-v02.api.letsencrypt.org/directory
authenticator = webroot
account = asdfasfasfasfdasfdasfdasfdasdfa

 

설정 파일 내용을 보면, webroot에 대한 정보가 없다.

그래서, aaaa.bbbb.kr 에 대한 웹루트(/webroot/aaaa.bbbb.kr) 정보를 설정 파일 하단에 추가 주었다.

 

[[webroot_map]]
aaaa.bbbb.kr = /webroot/aaaa.bbbb.kr

 

 

이렇게 수정을 마치고, 다시 갱신 시도를 해보니 오류 없이 잘 되었다.

 

#./certbot-auto renew

 

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/aaaa.bbbb.kr.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert is due for renewal, auto-renewing...
Plugins selected: Authenticator webroot, Installer None
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for aaaa.bbbb.kr
Waiting for verification...
Cleaning up challenges

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
new certificate deployed without reload, fullchain is
/etc/letsencrypt/live/aaaa.bbbb.kr/fullchain.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/aaaa.bbbb.kr/fullchain.pem (success)

 

 

 

 

notepad++ 이용중에 sftp 인증 오류 날때

notepad++ 이용중에 sftp 인증 오류 날때.

 

잘 사용하던 notepad++ 에서 sftp로그인중 갑자기 접근 인증 오류가 발생해 난감할때가 있다.

이는 어떤 이유에선지 모르겠지만, 호스트키(host key)정보가 잘못 저장되어 일어나는 경우로 보인다.

 

해결하는 방법은

C:\Users\사용자계정\AppData\Roaming\Notepad++\plugins\config\NppFTP

부분으로 이동해서

known_hosts 파일을 찾아 에디터로 열어서 sftp 접속 문제가 발생하는 서버의 호스트(IP)를 찾아 지운 후 저장하고,

notepad++을 다시 접속해서 사용하면 된다.

 

 

난감할때가 있긴한데, 알고 보면 간단하다.

 

또한, notepad++의 sftp정보의 백업도 간단하다.

위 디렉토리에 있는 NppFTP.xml 파일만 백업하면, sftp에 설정한 접속정보를 백업할 수 있다.

 

 

 

php soap 통신 개발시 'SoapClient' not found 에러 대처

Soap 통신시 Class 'SoapClient' not found 에러

SOAP(Simple Object Access Protocol)는 인터넷상에서 xml기반으로 메세지를 상호 교환할때 사용한다.

soap 통신 프로그램 개발시 "SoapClient" not found에러가 발생하게 되면
이는 서버에 soap 라이브러리가 활성화 되어 있지 않은것이다.

우선,
현재 서버에서 soap 관련 라이브러리가 설치되어 있나 확인을 한다.
간단히, phpinfo()로 확인을 해보면,
Soap Client enabled
Soap Server enabled
되어 있어야 한다.





만약, 없다면..
서버에서 soap 설치여부를 다시 확인
[root@~]rpm -qa | grep php-soap 엔터
 결과값이 없으면 설치해야 한다.

설치
[root@~]yum install php-soap 엔터
 파일 다운로드 받으면서 중간에 "Is this ok [y/n]" 나오면 Y 엔터
 complet! 메세지 출력이 되면서 설치 완료된다.

다시 체크
[root@~]rpm -qa | grep php-soap
php-soap-5.3.3-46.el6_6.x86_64

설치된것을 확인할 수 있다.

이제 서버를 재시작해주면 soap를 사용할 수 있다.
[root@~]service httpd restart