본문 바로가기

보안/시큐어코딩

[시큐어코딩실습] Command Injection 취약점 제거


commandInjection.txt


/WebContent/WEB-INF/test/test.jsp 파일 수정


  <div class="hint">

     <form action="command_test.do"  id="form5">

          (5) Command Injection 테스트:   

          <select  name="data"  id="data5">

              <option value="0">show File1.txt</option>

              <option value="1">show Dir</option>

          </select>

          <input type="button"   id="button5" value="실행"  >

          <br/> 

     </form>

  </div> 


/Java Resources/src/kr.co.openeg.lab.test.controller/TestController.java 파일 수정


@RequestMapping(value="/test/command_test.do", method = RequestMethod.POST)

@ResponseBody

public String testCommandInjection(HttpServletRequest request, HttpSession session){

StringBuffer buffer=new StringBuffer();

String[] allowCommand={"type","dir"};

String data=request.getParameter("data");

// 요청 파라메터의 값이 0,1이 되도록 view 페이지를 변경한다.

// 파라메터값을 index로 사용하여 allowCommand에 등록되어 있는 명령어를 검색하여 사용한다.

// 요청 파라메터가 null 이거나 0,1 이 아닌경우 에러 처리한다.



        int index=-1;

        try {

            index=Integer.parseInt(data);

        }catch(NumberFormatException e) {

            index=99;

        }

        

        if ( index >= 0 && index < 2) {

            data=allowCommand[index];

        } else {

            buffer.append("허용되지 않은 요청입니다");

    return buffer.toString();

        }

if ( data != null ) {

Process process;

String osName = System.getProperty("os.name");

String[] cmd;

if(osName.toLowerCase().startsWith("window")) {

    cmd = new String[] { "cmd.exe","/c",data };

    for( String s : cmd)

       System.out.print(s+" ");

} else {

    cmd = new String[] { "/bin/sh",data };

}

 

try {

process = Runtime.getRuntime().exec(cmd);

InputStream in = process.getInputStream(); 

Scanner s = new Scanner(in,"UTF-8");

buffer.append("실행결과: <br/>");

while(s.hasNextLine() == true) {

              buffer.append(s.nextLine()+"<br/>");

}

} catch (IOException e) {

// TODO Auto-generated catch block

buffer.append("명령어 실행 오류 발생");

e.printStackTrace();

} finally {

return buffer.toString();

}

      } else {

     buffer.append("명령어 실행 오류 발생");

     return buffer.toString();

    }

}