메뉴 건너뛰기

imp

[bWAPP] Insecure DOR (Order Tickets)

lispro062016.10.18 01:42조회 수 1311댓글 0

    • 글자 크기

A4 - Insecure Direct Object References

Insecure DOR (Order Tickets)


hidden 필드의 15eur을 변조하여 시도한다.


medium level에서는 post 파라미터에 ticket_price를 추가한다.

lispro06 (비회원)
    • 글자 크기

댓글 달기

[bWAPP] bWAPP - Broken Authentication

[원문보기]

A2 - Broken Auth. & Session Mgmt.

bWAPP - Broken Authentication


소스코드의 tonystark/I am Iron Man 을 입력하여 로그인한다.


A2BA-ILF.PNG

위키백과 QA API X AWS lambda X API Gateway X SLACK

[원문보기]

공공 인공지능 오픈 API·DATA 서비스 포털의 위키백과 QA API를 aws 람다로 node.js 를 이용해 slack에서 받을 수 있도록 처리했습니다.

 

전체적인 내용은 https://blog.aliencube.org/ko/2016/05/15/slack-github-integration-with-aws-lambda/ 를 참고하였습니다.

http://www.usefulparadigm.com/2016/04/06/creating-a-slack-bot-with-aws-lambda-and-api-gateway/

https://gist.github.com/sjoonk/20ae13e5cd8be88e9824e3bad11b2859

 

http://aiopen.etri.re.kr/service_list.php 

 

s.png

 

 

exports.handler = (event, context) => {

    // Sets request options

    var options = {

        host: 'aiopen.etri.re.kr',

        port: '8000',

        path: '/WikiQA',

        method: 'POST',

        headers: {

          'Content-Type': 'application/json'

        }

    };

    var access_key = '발급받은키';

    var type = 'irqa';

    // Sets the request body    

    var data = {

        'access_key': access_key,

        'argument': {

            'question': event.text,

            'type': type

        }

    };

    var request = require('http');

    var req = request.request(options, function (res) {

      var chunks = [];

    

      res.on("data", function (chunk) {

        chunks.push(chunk);

      });

    

      res.on("end", function () {

        var body = Buffer.concat(chunks);

        console.log(body.toString());

        body = JSON.parse(body);

        console.log(body.result);

        if(body.result==0){

          var text = body.return_object.WiKiInfo.IRInfo[0].sent;

          var ans = body.return_object.WiKiInfo.AnswerInfo[0].answer;

        }else{

          var text = "없음";

          var ans = event.text;

        }

          context.succeed({

            "response_type": "in_channel",

            "text": "ETRI 위키백과 QA API 결과 : " + ans,

            "attachments": [

                {

                    "text": "https://ko.wikipedia.org/wiki/" + encodeURI(ans) + "\n" + text,

                    "color": "#7CD197"

                }

            ]

          });

      });

    });

    req.write(JSON.stringify(data));

    req.end();

};

 

 

aws gateway 에서 매핑템플릿에 application/x-www-form-urlencoded 를 추가하지 않으면, json 요청 값을 처리할 수 없으니, 꼭 추가하자.

(event undefined)

## convert HTML POST data to JSON
 
## get the raw post data from the AWS built-in variable and give it a nicer name
#set($rawAPIData = $input.path('$'))

## first we get the number of "&" in the string, this tells us if there is more than one key value pair
#set($countAmpersands = $rawAPIData.length() - $rawAPIData.replace("&", "").length())
 
## if there are no "&" at all then we have only one key value pair.
## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs.
## the "empty" kv pair to the right of the ampersand will be ignored anyway.
#if ($countAmpersands == 0)
 #set($rawPostData = $rawAPIData + "&")
#end
 
## now we tokenise using the ampersand(s)
#set($tokenisedAmpersand = $rawAPIData.split("&"))
 
## we set up a variable to hold the valid key value pairs
#set($tokenisedEquals = [])
 
## now we set up a loop to find the valid key value pairs, which must contain only one "="
#foreach( $kvPair in $tokenisedAmpersand )
 #set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length())
 #if ($countEquals == 1)
  #set($kvTokenised = $kvPair.split("="))
  #if ($kvTokenised[0].length() > 0)
   ## we found a valid key value pair. add it to the list.
   #set($devNull = $tokenisedEquals.add($kvPair))
  #end
 #end
#end
 
## next we set up our loop inside the output structure "{" and "}"
{
#foreach( $kvPair in $tokenisedEquals )
  ## finally we output the JSON for this pair and append a comma if this isn't the last pair
  #set($kvTokenised = $kvPair.split("="))
 "$util.urlDecode($kvTokenised[0])" : #if($kvTokenised[1].length() > 0)"$util.urlDecode($kvTokenised[1])"#{else}""#end#if( $foreach.hasNext ),#end
#end
}

[bWAPP] Broken Auth. - Logout Management

[원문보기]

A2 - Broken Auth. & Session Mgmt.

Broken Auth. - Logout Management


로그아웃 후, back button을 눌러 이전 페이지에서 중요 정보를 접근할 수 있는지 여부 확인


A2BA-LM.PNG

[bWAPP] Broken Auth. - Password Attacks

[원문보기]

A2 - Broken Auth. & Session Mgmt.

Broken Auth. - Password Attacks


무작위 공격이나 id/pw 예측 공격으로 로그인을 시도한다.


A2BA-PA.PNG

[bWAPP] SQL Injection (GET/Search)

[원문보기]

A1 - Injection

SQL Injection (GET/Search)


컬럼명을 담고 있는 db의 table로 접근해 SQL Injection 공격을 해볼 수 있다.


Iron Man' union select 1,1,1,column_name,1,1,1 from information_schema.columns;#


A1SQL1.PNG

[bWAPP] Base64 Encoding (Secret)

[원문보기]

A6 - Sesitive Data Exposure

Base64 Encoding (Secret)



cookie 값을 url decode 하여, base64decode 해본다.


A6SDE-B64.PNG

[oAuth2] 구글 스프레드시트 접근

[원문보기]

기존 data query 로 visualization 을 사용하던 코드에서


Error in query: ACCESS_DENIED. This spreadsheet is not publicly viewable and requires an OAuth credential.


상기와 같은 에러가 발생한다면, 아래를 통해 authorization 관련 내용을 추가해야 한다.


https://developers.google.com/chart/interactive/docs/spreadsheets


demo.html, demo.js 로 적용 가능하며, 개발자 콘솔에서 client id를 생성하여 해당 문서들에 적용해야 한다.


1) 프로젝트가 없다면 생성

2) 사용자 인증정보 선택

3) 사용자 인증정보 만들기 - OAuth 2.0 클라이언트 ID

도메인 입력(최상단 도메인으로 하면 된다.)


demo.js 의 makeApiCall() 함수에서 oauth2 라는 전역 변수에 추가 파라미터를 입력하고


function makeApiCall() {
  // Note: The below spreadsheet is "Public on the web" and will work
  // with or without an OAuth token.  For a better test, replace this
  // URL with a private spreadsheet.
  var tqUrl = 'https://docs.google.com/spreadsheets' +
      '/d/[SS경로]/gviz/tq' +
      '?tqx=responseHandler:handleTqResponse' +
      '&access_token=' + encodeURIComponent(gapi.auth.getToken().access_token);
  oauth2 = '&tqx=responseHandler:handleTqResponse' + '&access_token=' + encodeURIComponent(gapi.auth.getToken().access_token);
  $(window.document.body).append('<script src="' + tqUrl +'" type="text/javascript"></script>');
}



기존 visualization data query 호출 경로에 access_token 파라미터가 추가되도록 했다.


var srUrl = "https://docs.google.com/spreadsheets/d/[SS경로]/gviz/tq?gid=0"+oauth2;



오랜만에 다시하려니, 설명이 부족해 조금 더 추가함


문서에 들어갈 소스
  <button id="authorize-button" style="visibility: hidden">Authorize</button>
  <script src="./demo.js" type="text/javascript"></script>
  <script src="https://apis.google.com/js/auth.js?onload=init"></script>
    <script src="[J쿼리경로]" type="text/javascript"></script> 
<script>데이터쿼리함수</script>


[demo.js]

// NOTE: You must replace the client id on the following line.
var clientId = '발급받은ID';
var scopes = 'https://spreadsheets.google.com/feeds';

function init() {
  gapi.auth.authorize(
      {client_id: clientId, scope: scopes, immediate: true},
      handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult && !authResult.error) {
    authorizeButton.style.visibility = 'hidden';
    makeApiCall();
  } else {
    authorizeButton.style.visibility = '';
    authorizeButton.onclick = handleAuthClick;
  }
}

function handleAuthClick(event) {
  gapi.auth.authorize(
      {client_id: clientId, scope: scopes, immediate: false},
      handleAuthResult);
  return false;
}

function makeApiCall() {
  // Note: The below spreadsheet is "Public on the web" and will work
  // with or without an OAuth token.  For a better test, replace this
  // URL with a private spreadsheet.
  var tqUrl = 'https://docs.google.com/spreadsheets' +
      '/d/[SS경로]/gviz/tq' +
      '?tqx=responseHandler:handleTqResponse' +
      '&access_token=' + encodeURIComponent(gapi.auth.getToken().access_token);
  oauth2 = '&tqx=responseHandler:handleTqResponse' + '&access_token=' + encodeURIComponent(gapi.auth.getToken().access_token);
  $(window.document.body).append('<script src="' + tqUrl +'" type="text/javascript"></script>');
}

function handleTqResponse(resp) {
데이터쿼리함수();
}

[bWAPP] XML/XPath Injection (Search)

[원문보기]

A1 - injection

XML/XPath Injection (Search)


~/bWAPP/xmli_2.php?genre=action%27)]/password%20|%20//hero[contains(genre,%20%27horror&action=search


genre=action')]/password | //hero[contains(genre,'horror


'|' 를 이용해 앞 단에 password 노드를 출력하도록 입력하고 뒤에는 오류가 나지 않도록 완성시킨다.


A1-XPATH-SRC.PNG

[매핑] 퍼스널 트레이닝과 공격 기법을 매칭해 본다

[원문보기]

사이드 레터럴 레이즈 - 레터럴 무브먼트

 

마운틴 클라이머 - 프리빌리지 에스컬레이션

 

점핑 잭 - 디스커버리

 

플랭크 / 크런치 - 퍼시스턴스

 

버피테스트 - 스캐닝

 

스쿼트 - 크레덴셜 엑세스

 

니업 / 푸시업 - 이니셜 엑세스

 

레그 레이즈 - 임팩트

 

덤벨 킥백 - 디펜스 이베이전

 

[GS] ArrayFormula 함수 활용하기

[원문보기]

ArrayFormula 는 영역의 내용을 그대로 참조할 수 있다.


importrange 함수는 다른 파일(스프레드시트)의 영역을 참조하는데, limit 가 걸려있고, 느리므로 별로 안 좋아한다.


ArrayFormula 를 이용해 다른 view 를 구성하는 것이 필요한 경우 사용 가능하다.


A, B, C 컬럼 중 A, C 만 연속해서 활용해야할 때 좋다.


더더욱 좋은 것은 문자열의 가공이 가능하다는 것이다.


=ArrayFormula(if('sheet'!V3:X="",,left('sheet'!V3:X,19)))


V3 행부터 X 행 전체 내용을 가져오는데, 비어있지 않다면(내용이 있다면) LEFT 함수를 거쳐 출력하는 것이다.


원래 내용은 20자인데, 별로 안 예쁘게 출력될 때, 새로운 view를 구성하면서 문자열을 자르고 출력시킬 수 있다.



또다른 활용으로는 index 와 row 를 이용한 순서 바꾸기(reverse) 이다.


=INDEX(ArrayFormula('sheet'!B$2:B),COUNTA(ArrayFormula('sheet'!$B$2:$B))-ROW()+2,1)


해당 예제는 2행 부터 시작되는 경우이고, arrayformula를 사용하는 시트도 2행부터 시작하여 내용을 맞췄다.


C 컬럼의 경우 그대로 복사하면, 옆의 행을 참조하도록 상대 주소가 반영된다.


3행의 경우도 전체 참조내용에서 row 함수에 의해 index 가 반전되므로 역정렬된 데이터를 볼 수 있다.


구글 form의 고질적인 문제(아래로 쌓이면 내용 확인을 위해 스크롤)가 있어 찾아봤다.

[GS] apps script 를 이용한 구글 드라이브로 파일 업로드

[원문보기]

PHP 를 이용한 파일 업로드는 서버에 저장된 파일을 스크립트를 이용해 리스트와 파일로 저장하는 방식이었다.


이제는 apps script를 이용해 직접 구글 드라이브로 업로드하여 중간 절차와 서버 사용 부담을 줄였다.


[원본글]

https://ctrlq.org/code/19747-google-forms-upload-files


[file.gs]

/* The script is deployed as a web app and renders the form */

function doGet(e) {

  return HtmlService

    .createHtmlOutputFromFile('form.html')

    .setTitle("파일 업로드");

}


function uploadFileToGoogleDrive(data, file, name, kind, row) {


  try {


    var tD = Utilities.formatDate(new Date(), "GMT+9", "yyyyMMdd");

    var folder, folders = DriveApp.getFoldersByName(tD);

    var imageFolder = DriveApp.getFolderById("폴더");

    /* Find the folder, create if the folder does not exist */

    if (folders.hasNext()) {

      folder = folders.next();

    } else {

      folder = imageFolder.createFolder(tD);

    }


    var contentType = data.substring(5,data.indexOf(';')),

        bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),

        blob = Utilities.newBlob(bytes, contentType, file);


    var file = folder.createFolder(tD).createFile(blob);

    

    return "OK";


  } catch (f) {

    return f.toString();

  }


}


[form.html]

<!-- File upload button -->

<input id="file" type="file">

<!-- Form submit button -->

<button id="sb" onclick="submitForm();return false;">전송</button>

<!-- Show Progress -->

<div id="progress"></div>

<!-- Add the jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script>


  var file, 

      reader = new FileReader();


  // Upload the file to Google Drive

  reader.onloadend = function(e) {

    google.script.run

      .withSuccessHandler(showMessage)

      .uploadFileToGoogleDrive(

         e.target.result, file.name, 

         $('select#company option:selected').text(), 

         $('select#kind').val(), 

         $('select#company').val()

      );

  };


  // Read the file on form submit

  function submitForm() {

      file = $('#file')[0].files[0];

      if(!file){

        alert('파일선택');

      }else{

        file = $('#file')[0].files[0];

        showMessage("Uploading file..");

        reader.readAsDataURL(file);

      }

  }


  function showMessage(e) {

    $('#progress').html(e);

    $('#sb').prop("disabled",true);

  }


</script>

[GS] 구글 사이트에서 oAuth 사용하기 위한 설정

[원문보기]

구글 사이트에 google script의 html 입력 방식으로 data query를 이용한 스프레드시트 내용 가져오기 방법이 있다.


스프레드시트가 전체 공개라면 상관 없지만, 부분 공개라면, oAuth 인증키를 이용한 권한 확인이 한번 더 필요하다.


https://console.developers.google.com 에서 사용자 인증 정보 -> 사용자 인증 정보 만들기 -> oAuth 클라이언트 ID -> 웹애플리케이션 용으로 만든다.


주소는 구글 사이트에서 웹앱 배포에 따라 생성된 js 경로를 입력해 준다.


사이트관리 -> 애플리케이션 스크립트 -> 새로만들기에 의해 생성된 gs가 배포되어 사이트에 삽입되면 개발자도구 콘솔을 통해 에러 메시지로 확인할 수 있다.


error.jpg


postMessage 경고는 처리하지 못하겠고, oAuth 도 승인된 자바스크립트 원본을 등록하는 방법이 올바른지 의문이다. 일단 동작하는데 의의를 뒀다.


auth.jpg

명령어 - bench (PC사양을 출력한다)

[원문보기]

Comman Window에서 다음과 같이 입력한다.

  To get started, select MATLAB Help or Demos from the Help menu.


>> bench


ans =


    0.5783    0.7319    0.3472    0.6259    0.7043    1.5608


>>

[python] 파일에서 문자열 찾기 소스

[원문보기]
http://bable.tistory.com/343 의 소스이다.

테스트 결과 동작한다.

import string
f = open("c:\Python27\target.txt","r")

lines = [] # list

for paragraph in f:
lines = string.split(paragraph, ".")
for each_line in lines:
if each_line.find(" get ") > 0:
print each_line
else:
pass

f.close()



C:Python27>python.exe line.py
you get test
i get to the wh

벡터선언 및 plotting

[원문보기]
w와 x를 벡터로 선언하고 2개의 영역으로 나뉘어 한개 figure에 그린다.

syms w x
w = [1.0
2.5198
4.3267
.
.
.
.
163186.0735
163199.4767
163215.91700000002
];
subplot(2,1,1);
plot(w);
title('iq table(interpolation)');
x = [1.0
2.5198
4.3267
6.3496
.
.
.
.
165086.6174
165113.4940
165140.3718
];
subplot(2,1,2);
plot(x);
title('iq table');

[itop] Helpdesk assign

[원문보기]

아무리 찾아도 change management 에서 할당 가능한 team과 person 이 helpdesk 에서 목록으로 출력되지 않는다.


역할 등이 해당 업무에 적합한 contact 들이 없어서 그런 것으로 추정했다.


Service management 에서 Delivery Models 를 임으로 추가하여 할당할 수 있는 team 과 person 이 출력되도록 했다.


delivery.png


기능은 매우 많고, DB 사용에 따른 메모리 소모도 큰데, 어떻게 효율적으로 사용할지는 고민해 봐야겠다.


assign.png


* Delivery model 임의 추가(모를 땐, 입력하고 보는 것이다.)

added.png

함수 - 데이터 생성 함수 magic

[원문보기]

 magic(k)는 1에서 k^2까지의 정수를 사용하여 열, 행 그리고 대각선의 합이 똑같은 정방행렬을 만들어주는 Matlab의 데이터 생성함수이다.


  To get started, select MATLAB Help or Demos from the Help menu.


>> B = magic(4)


B =


    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1


>>

행렬에서의 요소 치환 - 효율성 비교

[원문보기]

A = magic(4);
A(2:3,2:3) = [0 0; 0 0]
B = A;
for j = 1:4
        for k = 1:4
                if A(j,k) == 0
                        A(j,k) = 99
                end
        end
end
B
[j, k] = find(B==0);
    B(j,k) = 99

위의 코드는 A를 magic(4)으로 생성후, A22에서 A33까지를 0으로 치환한 후 B에 대입하였다. 그 후, A의 요소 중 0을 찾아 99로 치환하는 for문을 보여주며, B는 행렬의 특성을 이용해 find함수로 처리한다. for문은 반복적으로 처리하며, find는 한번에 처리함을 볼 수 있다.


A =


    16     2     3    13
     5     0     0     8
     9     0     0    12
     4    14    15     1



A =


    16     2     3    13
     5    99     0     8
     9     0     0    12
     4    14    15     1



A =


    16     2     3    13
     5    99    99     8
     9     0     0    12
     4    14    15     1



A =


    16     2     3    13
     5    99    99     8
     9    99     0    12
     4    14    15     1



A =


    16     2     3    13
     5    99    99     8
     9    99    99    12
     4    14    15     1



B =


    16     2     3    13
     5     0     0     8
     9     0     0    12
     4    14    15     1



B =


    16     2     3    13
     5    99    99     8
     9    99    99    12
     4    14    15     1

plot의 속성, axis의 속성, font의 속성 설정

[원문보기]
그림은 plot tool을 본 화면이다. 멋지군..

for j = 1:8192
    a(j-0) = j^(4/3);
end
pplot = plot(a,'m-.','LineWidth',[1.5]);
pfont = text(4096, 65536,'bulletleftarrow middle value','fontsize',18,'color',[1 0 0]);
axis([0 8200 0 170000]);
axis square, title('AXIS SQUARE'), grid;
%%아래의 get함수는 속성을 지정할 수 있는 파라미터와 현재 속성값을 볼 수 있다.
plot_property = get(pplot)
font_property = get(pfont)
axis_property = get(gca)
첨부 (1)
plottool.JPG
115.4KB / Download 55
위로