[SPRING] ch03. OS 명령어

2017. 9. 21. 10:16·SKILL/Security
728x90
반응형
package secure.ch03.ex01.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/ch03/ex01/os")
public class OSController {
    @RequestMapping(method=RequestMethod.GET)
    public void main(){}
    
    @RequestMapping(method=RequestMethod.POST)
    @ResponseBody
    public String testCommandInjection(HttpServletRequest request, HttpSession session){
        String job=request.getParameter("job");
            
        if(job != null  && job.equals("type")) {
            job = job + " "
                 + session.getServletContext().getRealPath("/WEB-INF/views/ch03/ex01/")
                 + "hello.txt"; 
            System.out.println("ch03.ex01: " + job);
        }
        
        Process process;
        String osName = System.getProperty("os.name");
        String[] cmd;

        if(osName.toLowerCase().startsWith("window")) {
            cmd = new String[]{"cmd.exe", "/c", job};
            System.out.print("ch03.ex01: ");
            for(String s : cmd) System.out.print(s+" ");
            System.out.println();
        }else cmd = new String[]{"/bin/sh",job};
        
        StringBuffer buffer=new StringBuffer();    
        try {
            process = Runtime.getRuntime().exec(cmd);
            InputStream in = process.getInputStream(); 
            Scanner sc = new Scanner(in,"utf-8");
            buffer.append("<b>RESULT: </b>");
            while(sc.hasNextLine() == true) 
                buffer.append(sc.nextLine());
        }catch(IOException e){
            buffer.append("ERROR!");
            e.printStackTrace();
        } 
        return buffer.toString();
    }
}
 
 
 
/WEB-INF/views/ch03/ex01/hello.txt
 
Hello, I love You.
 
 
/WEB-INF/views/ch03/ex01/os.jsp
 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function(){
    $("button").bind("click", function() { 
          var formArr = $("form").serializeArray(); 
            $("#result").empty(); 
            $.ajax({
                data: formArr,
                method: "post",
                success: function(result){                                     
                 $("#result").append(result); 
                },
                error: function(a, b, errMsg){
                   $("#result").append(errMsg); 
                }
           }); 
    });
});
</script>
<form>
    작업선택:
     <select name="job">
         <option value="type">-- type hello.txt --</option>
         <option value="dir">-- dir --</option>
     </select> 
     <button type="button">제출</button>          
</form>
<p id="result"></p>
 
 
 
 
package secure.ch03.ex02.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("ch03.ex02.osController")
@RequestMapping("/ch03/ex02/os")
public class OSController {
    @RequestMapping(method=RequestMethod.GET)
    public void main(){}
    
    @RequestMapping(method=RequestMethod.POST)
    @ResponseBody
    public String testCommandInjection(String job, HttpSession session){
        String result = "REJECTED.";
        String[] allowedCmds = {"type", "dir"};
        boolean isAllowed = false;
        for(String cmd:allowedCmds) if(cmd.equals(job)) isAllowed = true;        
        
        if(isAllowed){
            if(job != null  && job.equals("type")) {
                job = job + " "
                     + session.getServletContext().getRealPath("/WEB-INF/views/ch03/ex01/")
                     + "hello.txt"; 
                System.out.println("ch03.ex01: " + job);
            }
            
            Process process;
            String osName = System.getProperty("os.name");
            String[] cmd;
    
            if(osName.toLowerCase().startsWith("window")) {
                cmd = new String[]{"cmd.exe", "/c", job};
                System.out.print("ch03.ex01: ");
                for(String s : cmd) System.out.print(s+" ");
                System.out.println();
            }else cmd = new String[]{"/bin/sh",job};
            
            StringBuffer buffer=new StringBuffer();    
            try {
                process = Runtime.getRuntime().exec(cmd);
                InputStream in = process.getInputStream(); 
                Scanner sc = new Scanner(in,"utf-8");
                buffer.append("<b>RESULT: </b>");
                while(sc.hasNextLine() == true) 
                    buffer.append(sc.nextLine());
            }catch(IOException e){
                buffer.append("ERROR!");
                e.printStackTrace();
            } 
            result = buffer.toString();
        }
        return result;
    }
}
 
 
 
 
/WEB-INF/views/ch03/ex02/os.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function(){
    $("button").bind("click", function() { 
          var formArr = $("form").serializeArray(); 
            $("#result").empty(); 
            $.ajax({
                data: formArr,
                method: "post",
                success: function(result){                                     
                 $("#result").append(result); 
                },
                error: function(a, b, errMsg){
                   $("#result").append(errMsg); 
                }
           }); 
    });
});
</script>
<form>
    작업선택:
     <select name="job">
         <option value="type">-- type --</option>
         <option value="dir">-- dir --</option>
         <option value="del">-- del --</option>
     </select> 
     <button type="button">제출</button>          
</form>
<p id="result"></p>
 
 

728x90
반응형

'SKILL > Security' 카테고리의 다른 글

LETSENCRYPT 에서 SSL 인증서를 무료로 발급 받아 웹 서버에 적용하기  (0) 2018.05.17
SSL 보안 인증서 발급 - CSR 발급  (0) 2018.05.17
[SPRING] ch04. 로그인  (0) 2017.09.21
[SPRING] ch02. SQL Injection - 방어  (0) 2017.09.21
[SPRING] ch01.SQL Injection - 공격  (0) 2017.09.21
'SKILL/Security' 카테고리의 다른 글
  • SSL 보안 인증서 발급 - CSR 발급
  • [SPRING] ch04. 로그인
  • [SPRING] ch02. SQL Injection - 방어
  • [SPRING] ch01.SQL Injection - 공격
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    nginx ssl 설정
    VS Code 팁
    Node
    ssl 인증서 발급
    프런트엔드
    SSL 인증서
    java casting
    lang rust
    자바 for문
    Java Array
    svelte
    nginx ssl 적용
    mysql db
    러스트
    css transition
    vue cli
    자바 클래스
    docker
    css tb
    spring java
    티스토리 자동화
    리눅스 설치
    ubuntu
    브라우저 자동화
    자바 생성자
    API 설계
    proxy pass
    오류
    gitlab 설치
    jsp parameter
    rust linux
    React Compiler
    css block
    AI 코딩 에이전트
    클론코딩
    vscode
    Extension Bisect
    jsp include
    servlet class
    자바 exception
    css perspective
    css list
    Rust lang
    nginx
    vue 설치
    css float
    에디터 팁
    자바 객체 지향
    css table
    자바 배열
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[SPRING] ch03. OS 명령어
상단으로

티스토리툴바