8 minute read

라즈베리파이 SSL 적용

SSL 적용 개요

: 이전 포스팅에서 발급받은 cerbot(Let’s Encrypt) 인증서를 적용해보자.

SSL 으로 어떻게 접근할까?

: SSL 은 https 이다. 그런데 보통 우리는 http, https 등의 프로토콜을 생략하고 도메인만 입력하면 https 로 접속된다. 우리한테는 당연한거지만 사실 따로 설정을 해주어야 한다.

방법1. 웹페이지에서 처리

: 사용자가 주소를 입력하면 html, jsp 로 이동되고 내용에서 https + 주소 하드코딩으로 redirect 처리한다.

Example)

  • location.href
  • jquery, javascript

비권장)
이런 방법은 다수의 페이지를 수정해야 할 때 너무 손이 많이가고, 보안적으로 취약하다.(페이지가 로딩하는 내용을 확인하는 등)

방법2. mod_alias

: 아파치에서 제공하는 모듈이다.

Example)

# 1. mod_alias의 redirect기능

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName www.example.com
   Redirect permanent / https://secure.example.com(https:443포트의 servername 해당서버의 도메인)/
</VirtualHost>

특정URL 용도로 권장)
단순히 원하는 특정url을 정해진 어떤 url로 이동한다 라고 했을 때 유용하다. 어떤 경로를 강제로 사용하지 못하게하거나, 위와 같은 경우를 간단히 처리할 때 유용하다. 실질적으로 추가할 라인도 단한 줄에 불과하다.

방법3. mod_rewrite

: 아파치에서 제공하는 모듈이다.

Example)

# 1. mod_alias의 redirect기능
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

복잡한 URL 처리 용도로 권장)
rewrite를 사용할 경우 좀 더 많은 수정과 정규식을 사용해야 한다. 이 경우에는 첫번째 방식(Redirect)을 추천한다고 한다. 이유는 단지 포트를 옮기기 위한 작업이므로 복잡한 상황에 대한 대처는 필요하지 않기 때문이다.

SSL 적용

SSL 적용과정

: 웹서버(아파치) 측에서 수정한다. (Apache 2.4 기준)

  1. (아파치루트/conf/httpd.conf) 모듈로드,설정 ON
    : ssl 모듈을 로드하고 설정파일을 사용하기위해 주석해제 한다.

     cd /fswas/apache/httpd/httpd-2.4.541/conf/
     vi httpd.conf
    
     # SSL 모듈 사용하기위해 주석해제
     LoadModule ssl_module modules/mod_ssl.so
    
     # SSL 설정파일을 include 하기위해 주석해제 한다.
     Include conf/extra/httpd-ssl.conf
    
    
  2. (아파치루트/conf/extra/httpd-ssl.conf) SSL설정파일 수정하기
    : 주석해제한 설정 파일 내용을 수정한다.

     cd /fswas/apache/httpd/httpd-2.4.541/conf/extra
     vi httpd-ssl.conf
    
    
     ##############################################
     - ASIS
    
     ##############################################
     #  <VirtualHost _default_:443>
          
     #      DocumentRoot "/fswas/apache/httpd/httpd-2.4.541/htdocs"
     #      ServerName www.example.com:443
     #      ServerAdmin you@example.com
     #      ErrorLog "/fswas/apache/httpd/httpd-2.4.541/logs/error_log"
     #      TransferLog "/fswas/apache/httpd/httpd-2.4.541/logs/access_log"
    
     #      #   SSL Engine Switch:
     #      SSLEngine on
    
     #      #   Server Certificate:
     #      SSLProtocol all -SSLv3
     #      SSLProxyProtocol all -SSLv3
     #      SSLCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES
     #      SSLProxyCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES
    
     #      SSLCertificateFile "/fswas/apache/httpd/httpd-2.4.541/conf/server.crt"
     #      SSLCertificateKeyFile "/fswas/apache/httpd/httpd-2.4.541/conf/server.key"
     #      # SSLCACertificateFile "/fswas/apache/httpd/httpd-2.4.541/conf/server-ca.crt"
    
     #  </VirtualHost>
    
    
     ##############################################
     - TOBE (아래와 같이 변경)
     ##############################################
     <VirtualHost _default_:443>
          
         # 기본정보
         DocumentRoot "/fswas/apache/httpd/httpd-2.4.541/htdocs"
         ServerName www.blang.co.kr:443  # 변경
         ServerAdmin layup3@naver.com    # 변경
         ErrorLog "/fswas/apache/httpd/httpd-2.4.541/logs/error_log"
         TransferLog "/fswas/apache/httpd/httpd-2.4.541/logs/access_log"
    
         #   SSL Engine Switch:
         SSLEngine on
    
         #   Server Certificate:
         SSLProtocol all -SSLv3
         SSLProxyProtocol all -SSLv3
         SSLCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES
         SSLProxyCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES
     
         # SSL(Let’s Encrypt) 발급한 경로 지정하기
         SSLCertificateFile "/etc/letsencrypt/live/www.blang.co.kr/cert.pem"        #발급한 경로로 설정
         SSLCertificateKeyFile "/etc/letsencrypt/live/www.blang.co.kr/privkey.pem"  #발급한 경로로 설정
         SSLCACertificateFile "/etc/letsencrypt/live/www.blang.co.kr/chain.pem"     #발급한 경로로 설정
    
     </VirtualHost>
    
    
  3. 설정완료

SSL 적용 테스트

: WEB서버를 시작하고 https 으로 접속해본다.

문제발생(1) :: shmcb 에러현상

: SSL 설정을 완료했지만 다음과 같은 에러가 발생한다.

# 웹서버 기동 쉘
webstart   

# 에러가 발생했다.
AH00526: Syntax error on line 92 of /fswas/apache/httpd/httpd-2.4.541/conf/extra/httpd-ssl.conf:
SSLSessionCache: 'shmcb' session cache not supported (known names: ). Maybe you need to load the appropriate socache module (mod_socache_shmcb?).

  1. 원인
    다음과같이 세션캐쉬가 지원하지않는다며 shmcb 모듈이라는게 필요하다고 에러가난다. Apache2.4에 SSL을 적용할때 이슈인가 보다
  2. 해결방안
    (아파치루트/conf/httpd.conf) 아래처럼 주석을 해제하고 모듈을 로드한다.
     # 우선 모듈이 있는지 확인
     cd /fswas/apache/httpd/httpd-2.4.541/modules 
        
     # 모듈이 존재한다!
     ls | grep shmcb
     mod_socache_shmcb.so 
    
    
     # mod_socache_shmcb.so 모듈 로드하기
     cd /fswas/apache/httpd/httpd-2.4.541/conf/
     vi httpd.conf
        
     # CTH SSL 사용시 세션캐쉬관련하여 해당모듈이 필요함
     # 그러므 주석해제
     LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
        
    
  3. 해결완료
    접속하여 다시 확인한다. (https://www.blang.co.kr/)

    https 프로토콜이 적용되어 404 에러가 아닌 정상적으로 접속이 된다. 하지만 mod_jk 으로 로드밸런싱 설정된 WAS서버로 넘어가지 않았다.


문제발생(2) :: https 로드밸런싱 불가현상

: 위 문제해결로 SSL 적용이 완료되어 https 접속이 가능했지만 WAS서버측으로 로드밸런싱이 작동하지 않는 문제가 발생했다.

사진1

위 페이지는 웹서버 내의 존재하는 index.html 파일이다.
1 WAS측의 ‘/’ 루트로 매핑되어 서블릿이 실행되어야하는데
2 WEB측의 ‘/’ 루트로 매핑되어 웹서버 web.xml안에서 태그로 정의된 웹서버의 index.html 이 호출되었다. (결국 지금상황은 https 접속이 되었지만 https 프로토콜로 접속한 경우는 로드밸런싱이 안된다는 뜻이 된다.)

  1. 원인
    SSL에는 톰캣으로 보내기위한 매핑을 검사하는 JkMount 처리가 없다. 즉, 나는 80포트에만 JkMount 처리를 해두었던것이다.
  2. 해결방안
    (아파치루트/conf/extra/httpd-ssl.conf) JkMount(mod_jk.so)를 이용해서 Tomcat과 연동되는 경우, 80포트의 JkMount 설정을 SSL 관련 VirtualHost에 동일하게 복사해야 한다고 한다. 즉, 기존에 80포트에 설정(httpd.conf)해둔 jkMount 내용을 SSL(443) 포트에도 동일하게 작성(httpd-ssl.conf) 하자. 그러면 요청에대해 설정한 매핑을 검사하고 톰캣측에 정상적으로 보낼것이다.
     # httpd.conf 안에서 80포트에만 설정해둔 JkMount 내용을 복사하고 진행.
     vi 아파치루트/conf/extra/httpd-ssl.conf  
        
     # 붙여넣기
     JkMount /* blang_balancer
        
    
  3. 해결완료
    접속하여 다시 확인한다. (https://www.blang.co.kr/)

    위 처럼 작성함으로써 ssl(443)포트에도 JkMount 으로 모든 요청을 톰캣서버로 가도록하니까 정상적으로 로드밸런싱이 되었다.


문제발생(3) :: www유무에 따른 ssl적용

: 지금까지 내용으로면 문제없이 SSL 반영이 정상완료로 보인다. 하지만, 문제가 있었다. 문제(2) 에서 사진을 자세히보면 ssl이 적용되지 않았다. 찾아보니 www를 붙여서 도메인을 입력한 경우와 붙이지 않은 경우에 따라 SSL 적용이 안되었다.

사진1

위 사진을 다시 자세히보면 www 를 입력하지 않아 ssl 적용이 되지않았다. 원래는 자물쇠모양이 나오고 보안연결이 되어야한다.

  1. 원인
    2가지 시점에서 원인을 다르게 볼 수있다. (두번째시점 방법으로 진행)

    참고) 현재 DNS 상황 간단하게 보기
    DNS가 잘작동하는지 보고싶은 레코드설정 선택 후 간단하게 주소만 입력하면 확인할 수 있다. https://toolbox.googleapps.com/apps/dig/#A/

    • 첫번째시점) SSL발급시점에 메인도메인,서브도메인중에 서브도메인 하나만 발급함.

      # 나는 인증서 발급당시 이렇게 작성했는데...
      # sudo certbot certonly --manual --email layup3@naver.com -d www.blang.co.kr
      
      # 이렇게 할 수 있을것이다.(메인도메인과 서브도메인을 모두 발급)
      sudo certbot certonly --manual --email layup3@naver.com -d www.blang.co.kr -d blang.co.kr
      
      

      단순히 물리적으로 2개의 SSL을 발급/적용 하지 않았으므로 문제. 라는 뜻이다.
      SSL인증서를 생성할때 메인도메인www.서브도메인 은 같은 도메인으로 치는 경향이 있으니 -d blang.co.kr -d www.blang.co.kr 처럼 둘 모두 작성하면 두개의 SSL인증서를 받을 수 있었을 것이다.

    • 두번째시점) 입력한 url을 https으로 rewrite 처리를 안함

      보통은 이 방법을 사용하는듯 하다.
      발급받은 1개의 특정 SSL 으로 리다이렉트 한다.
      방법도 여러가지인데 대중적인 방법은 mod_rewrite.so 모듈을 사용한 리다이렉트를 구현하는것으로 확인된다.

  2. 해결방안
    위에 두번째시점에서 문제를 해결한다. 리다이렉트 모듈을 추가하고 기능을 적용하도록한다. 어떤 주소를쳐도 SSL이 적용된 www.도메인 형태로 요청하도록 처리하는것이 목적이다.
     cd /fswas/apache/httpd/httpd-2.4.541/conf 
     vi httpd.conf
    
    
     #LoadModule
     LoadModule rewrite_module modules/mod_rewrite.so  #주석해제 
    
     # Virtual hosts 설정을 사용하는 경우 
     Include conf/extra/httpd-vhosts.conf  #주석해제 
    
    
     cd /fswas/apache/httpd/httpd-2.4.541/conf/extra 
     vi httpd-vhosts.conf
    
     # Server1 :: www.blang.co.kr 으로 요청한경우
     <VirtualHost *:9510>
         ServerAdmin layup3@naver.com
         DocumentRoot "/fswas/apache/httpd/httpd-2.4.541/htdocs"
         ServerName www.blang.co.kr
         ErrorLog "/fswaslog/apache/dbd/error_log"
         CustomLog "/fswaslog/apache/dbd/error_log"
         common
    
         RewriteEngine On
         RewriteCond %{HTTPS} off
         RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    
     </VirtualHost>
    
    
     # Server1 :: blang.co.kr 으로 요청한경우
     <VirtualHost *:9510>
         ServerAdmin layup3@naver.com
         ServerName blang.co.kr
         ErrorLog "/fswaslog/apache/dbd/error_log"
         CustomLog "/fswaslog/apache/dbd/error_log" common
    
         RewriteEngine On
         RewriteCond %{HTTPS} off
         RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI}
     
     </VirtualHost>
    
    

    사용자가 입력할때는 balng.co.kr 또는 www.blang.co.kr 일것이다. 즉, 웹기본 80포트로 요청한다는 뜻이된다. (참고로 나는 기본 수신포트 를 9510 으로 잡아놨으므로 9510 으로 작성했다.)

    www.blang.co.kr 으로 요청이오면 https 를 붙여주고, blang.co.kr 으로 요청이오면 https://www. 을 붙여주면 된다 그리고 443 포트로 쏴주면 끝이다.

  3. 해결완료
    SSL(443) 포트로 정상 요청된다.

SSL 적용완료

: cerbot(Let’s Encrypt) 을 이용한 SSL 인증서발급부터 시작하여 적용까지 완료하였다. 하지만 3개월 마다 갱신시켜주어야 할 것이다.

참고하기 좋은 포스트 https://swiftcoding.org/https-cert

[23.07.13 추가작성] 재발급 (SSL 갱신기간이 만료 되었다.)

: (23.07.13) 현재 갱신기간이 만료되었다. 뭔가 다시보려니까 설정 해둔 것들이 너무 많아서 다시 정리하려고한다. 다음과 같이 조치한다.

(httpd-vhosts.conf) https 리다이렉트 중단시키기

: modjk를 통한 리다이렉트가 적용되어있기때문에 다시 수동갱신을 할 때에 웹서버내의 파일에 접근을 못한다. (WAS으로 연동되므로) 그래서 주석을 우선 웹서버 내의 파일접근을 가능하도록 수정해야한다.

(httpd-vhosts.conf)

# Server1 :: www.blang.co.kr 으로 요청한경우
<VirtualHost *:9510>
    ServerAdmin layup3@naver.com
    DocumentRoot "/fswas/apache/httpd/httpd-2.4.541/htdocs"
    ServerName www.blang.co.kr
    ErrorLog "/fswaslog/apache/dbd/error_log"
    CustomLog "/fswaslog/apache/dbd/error_log" common

    #    ServerAlias blang.co.kr  의미없음
    # RewriteEngine On
    # RewriteCond %{HTTPS} !=on
    # RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

    #    RewriteEngine On                                        주석처리
    #    RewriteCond %{HTTPS} off                                주석처리
    #    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}      주석처리

  1. 이제 www.blang.co.kr 으로 접근하면
  2. 리다이렉트를 수행하지 않고
  3. 웹서버 내의 파일에 접근한다.

(명령어) 만료된 인증서 제거하기

# 아래와 같이 나의 만료되버린 기존 인증서가 있다. 
root@cddawso1:/etc/letsencrypt/live/www.blang.co.kr# pwd
/etc/letsencrypt/live/www.blang.co.kr
root@cddawso1:/etc/letsencrypt/live/www.blang.co.kr# l
합계 12
drwxr-xr-x 2 root root 4096 12월  5  2022 .
drwx------ 3 root root 4096 12월  5  2022 ..
-rw-r--r-- 1 root root  216 12월  5  2022 README
lrwxrwxrwx 1 root root   39 12월  5  2022 cert.pem -> ../../archive/www.blang.co.kr/cert2.pem
lrwxrwxrwx 1 root root   40 12월  5  2022 chain.pem -> ../../archive/www.blang.co.kr/chain2.pem
lrwxrwxrwx 1 root root   44 12월  5  2022 fullchain.pem -> ../../archive/www.blang.co.kr/fullchain2.pem
lrwxrwxrwx 1 root root   42 12월  5  2022 privkey.pem -> ../../archive/www.blang.co.kr/privkey2.pem


# 삭제
root@cddawso1:/etc/letsencrypt/live/www.blang.co.kr# certbot -auto delete

## 삭제 완료 확인
cd /etc/letsencrypt/live

root@cddawso1:/etc/letsencrypt/live# ls -al /etc/letsencrypt/live/
합계 12
drwx------ 2 root root 4096  7월 13 16:02 .
drwxr-xr-x 9 root root 4096  7월 13 16:02 ..
-rw-r--r-- 1 root root  740 10월 13  2022 README
root@cddawso1:/etc/letsencrypt/live#

발급(이전 포스팅 내용과 동일)

# 설치
root@cddawso1:/etc/letsencrypt/live# sudo certbot certonly --manual --email layup3@naver.com -d www.blang.co.kr
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Requesting a certificate for www.blang.co.kr

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Create a file containing just this data:

TPojqSP5O59Dj9zSnE8DCVQ07daubaZBXhgBOC5Ubg8.Maq3VP2H7kR4BKvqSK6M5UxpggCUz79D02DKpcVXqK4

And make it available on your web server at this URL:

http://www.blang.co.kr/.well-known/acme-challenge/TPojqSP5O59Dj9zSnE8DCVQ07daubaZBXhgBOC5Ubg8

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

  1. 인증서가 보인다.
  2. 잠깐 멈추고 키값(파일명,내용) 인증서 복사
  3. 추가 세션에서 ssh 접속 > 위 경로의 키값(파일명,내용) 작성
  4. 멈춘 세션으로 돌아와서 진행
  5. 발급완료

발급 완료

# 발급완료
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/www.blang.co.kr/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/www.blang.co.kr/privkey.pem
This certificate expires on 2023-10-11.
These files will be updated when the certificate renews.

NEXT STEPS:
- This certificate will not be renewed automatically. Autorenewal of --manual certificates requires the use of an authentication hook script (--manual-auth-hook) but one was not provided. To renew this certificate, repeat this same certbot command before the certificate's expiry date.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
root@cddawso1:/etc/letsencrypt/live#

(httpd-vhosts.conf) https 리다이렉트 원복하기

: modjk를 통한 리다이렉트가 적용되어있기때문에 다시 수동갱신을 할 때에 웹서버내의 파일에 접근을 못한다. (WAS으로 연동되므로) 그래서 주석을 우선 웹서버 내의 파일접근을 가능하도록 수정해야한다.

(httpd-vhosts.conf)

# Server1 :: www.blang.co.kr 으로 요청한경우
<VirtualHost *:9510>
    ServerAdmin layup3@naver.com
    DocumentRoot "/fswas/apache/httpd/httpd-2.4.541/htdocs"
    ServerName www.blang.co.kr
    ErrorLog "/fswaslog/apache/dbd/error_log"
    CustomLog "/fswaslog/apache/dbd/error_log" common

    #    ServerAlias blang.co.kr  의미없음
    # RewriteEngine On
    # RewriteCond %{HTTPS} !=on
    # RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

    RewriteEngine On                                        
    RewriteCond %{HTTPS} off                                
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}      

재발급 끝!

참고) Rewrite에 관하여

Rewrite 기본

  • RewriteEngine
    rewriting engine 활성화 여부.
  • RewriteCond
    RewriteRule과 함께 사용되는 규칙으로 RewriteCond 다음에 오는 RewriteRule은 RewriteCond에서 설정한 패턴과 일치하는경우만, Rule을 실행한다.
  • RewriteRule
    실질적인 Rewrite규칙들을 적용하는 지시자.

사용법
RewriteRule [Input URL] [Return URL]
(* [Input URL]에는 Perl정규식을 사용할 수 있다.)

참고) SSO에 관하여

: 리다이렉트는 검색엔진 처리인 sso 에도 밀접한 관련이 있다. 리다이렉트시 SEO처리가 어떻게 달라질까?

301, Permanently Moved

: Permanently라는 뜻이 영구히, 영구적인 이라는 뜻이므로, 영구적으로 이동한다는 것이다. 요청된 리소스가 영구적으로 이동 페이지로 이동되었다는 것이다.

302, Temporarily Moved

: Temporarily라는 뜻이 임시적, 임시적인 이라는 뜻이므로, 임시적으로 이동했다는 것을 나타냅니다. 요청된 리소스가 임시적으로 이동 페이지로 이동되었다는 것이다.

차이점

: 무엇이 다른걸까? 검색엔진의 크롤링하는 페이지가 다르다. 인터넷 브라우저에서 사용자가 A라는 페이지를 요청했는데, Url이 B라는 페이지로 변경되었다면 해당 페이지는 리다이렉트가 되었다는 것을 뜻한다. 이럴때, 301 리다이렉트를 한다면 검색엔진 크롤링에서는 B라는 페이지에 대한 수집을 하지만 302 리다이렉트를 한다면, A라는 페이지에 대해서 수집할 것이다.

Leave a comment