[ASP.NET MVC] DI 컨테이너 설정(Ninject)

Posted by 알 수 없는 사용자
2015. 9. 13. 17:17 프로그래밍/.NET

지난번 Ninject 사용에서는 응용프로그램에 대해 적용하는 방법을 알아보았는데

이번에는 레스토랑의 메뉴리스트를 보여주는 시나리오를 통해 ASP.NET MVC에서 DI를 어떻게 적용하는지 알아보자.


1. NinjectController 생성

[코드1]

Ninject를 이용해 의존성 주입을 하기 위한 NinjectController 클래스를 생성한다.

의존성주입이 필요하다면 줄 Addbindings()함수에 추가하면 된다.


2. NinjectController 등록

[코드2]

[코드2]의 10번째 줄은 [코드1]에서 생성한 클래스를 사용한다고 ASP.NET MVC에 알리는 과정이다.


3. 도메인 모델 생성

[코드3]

[코드4]

메뉴리스트에서 메뉴정보를 갖는 Menu클래스를 정의하고 Repository를 추가한다.


3. 데이터바인딩

[코드5]
원래라면 DB에서 데이터를 불러와서 메뉴정보에 담는 과정이 필요한데 여기서는 DB사용하지 않으므로
임시 데이처를 추가한다.
데이터바인딩작업은 위의 [코드1]에서 만든 NinjectController 클래스의 AddBinding() 함수에서 한다.

4. 메뉴 컨트롤러 생성

[코드6]

메뉴목록을 보여주기 위해 MenuController 클래스에 List함수를 추가했다.


5. 메뉴 리스트 뷰 생성

[코드7]

메뉴리스트 뷰생성은 [코드6]의 List함수에서 마우스 오른쪽 클릭 -> 뷰 추가 버튼을 클릭하여 생성한다.

뷰생성시 강력한 형식의 뷰를 선택하여 [코드3]에서 생성한 메뉴클래스를 입력한다.


6. 결과 확인 하기



[그림1]

코드작성이 완료되었으면 빌드하여 결과를 확인한다.



'프로그래밍 > .NET' 카테고리의 다른 글

[ASP.NET MVC]Ninject 사용법  (748) 2015.08.23
[ASP.NET MVC]Dependency Injection 개념  (1309) 2015.08.02
[ASP.NET MVC] Controller에서 데이터 전달  (4) 2015.07.11
[ASP.NET MVC] Project 생성, MVC Hello World!  (4) 2015.06.26
<ASP.NET> Razor  (5) 2015.05.18

[codecademy] 4. FUNCTIONS

Posted by 알 수 없는 사용자
2015. 9. 5. 16:49 프로그래밍/Python


FUNCTIONS ( 1 ~ 19 )

1. What Good are Functions? 


샘플코드에서 보면 tax와 tip을 계산하는 함수 두가지를 정의해 놓은것을 볼수 있다.

함수를 정의하고 사용하는 방법을 이제부터 설명할 것이다.


문제없음.


2. Function Junction

i . 함수 헤더는 def 함수이름(): 으로 시작한다. 그리고 필요에 따라 함수이름 뒤 괄호안에 파라미터값을 받을수 있다.

ii. 좋은 함수는 함수에대한 설명도 포함되어야 한다. 설명은 주석(""" ~~ """)을 사용한다.

iii.  함수의 몸통( 내용 )의 절차에 따라 함수가 실행된다. 조건문처럼 들여쓰기 된다. 

문제

Go ahead and create a function, spam, that prints the string "Eggs!" to the console. 

Don't forget to include a comment of your own choosing (enclose it in triple quotes!).


3. Call and Response

함수를 정의한 후에, 정의된 함수를 호출하는 방법이다.

ex> def spam(): 과같이 함수를 정의했다면 spam()과 같이 함수를 호출해주면 된다.


문제

We've set up a function, square. 

Call it on the number 10 (by putting 10 between the parentheses of square()) on line 9!


4. Parameters and Arguments

샘플코드에서 n은 square 함수의 매개변수이다. 매개변수는 인수를 전달할 변수의 이름 역할을 한다.


문제

Check out the function in the editor, power.

It should take two arguments, a base and an exponent, and raise the first to the power of the second.

It's currently broken, however, because its parameters are missing.

Replace the ___s with the parameters base and exponent and call power on a base of 37 and a power of 4.


5. Functions Calling Functions

/

샘플코드와 같이 함수안에서 다른 함수를 호출할 수 있다.


문제

Let's look at the two functions in the editor: one_good_turn (which adds 1 to the number it takes in as an argument) 

and deserves_another (which adds 2).

Change the body of deserves_another so that it always adds 2 to the output of one_good_turn.

6. Practice Makes Perfect


함수만드는 연습을 해보자


문제

1.First, def a function called cube that takes an argument called number. Don't forget the parentheses and the colon!


2.Make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).


3.Define a second function called by_three that takes an argument called number.


4.if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.


Don't forget that if and else statements need a : at the end of that line!


7. I Know Kung Fu


모듈을 import 하는 방법을 설명할것이다. 

여기서 모듈은 변수와 함수를 포함한 파일로 한번 import 하게되면 모듈에 포함된 함수와 변수를 사용할수있다.


문제

Before we try any fancy importing, let's see what Python already knows about square roots. 

On line 3 in the editor, ask Python to

which we would expect to equal five.


8. Generic Imports

7번의 문제에서 에러메시지를 보면 sqrt라는 이름이 정의되지 않았다고 에러가 발생했다 .

파이썬은 아직 제곱근을 알지 못한다는것이다.


파이썬 모듈중에 math라는 모듈이 있는데, 이모듈은 유용한 변수,함수, 그리고 다양한 함수들중 sqrt() 함수를 포함한다.

math 모듈에 접근하기 위해서는 import라는 키워드를 이용하면 된다.


문제

You'll need to do two things here:


1. Type import math on line 2 in the editor.

2. Insert math. before sqrt() so that it has the form math.sqrt(). 

   This tells Python not only to import math, but to get the sqrt() function from within math.


Then hit Save & Submit to see what Python now knows.


9. Function Imports

math 모듈을 import 하여 sqrt함수를 사용하는 법을 알았다. 

하지만 오직 sqrt 함수만 필요할 경우에 매번 math.sqrt() 라고 타이핑하는것이 번거로울 때가 있다

샘플코드와 같이 하게되면 모듈 중에서도 특정함수만 import 할수있다.


문제

Let's import only the sqrt function from math this time.

(You don't need the () after sqrt in the from math import sqrt bit.)


10. Universal Imports

만약 우리가 모듈안의 모든 함수와 변수가 필요하다고 할때, 매번 math.XXX 라고 타이핑 해야 할까?

Universal Import 가 이런문제를 해결해준다.


문제

Use the power of from module import * to import everything from the math module on line 3 of the editor.


11. Here Be Dragons

Universal Imports가 표면적으로는 좋아보일수 있다.

하지만, 사용하다보면 이름이 같지만 기능이 다른 두개의 함수가 존재하는 문제가 발생할 수 있다.

만약 자신이 정의한 함수들이 모듈에서 import한 함수들의 이름과 충돌하지 않는다고 해도,

여러 모듈에서 Universal Imports를 한다면 변수나 함수들이 어느 모듈에서 가져온것인지 알 수 없게 된다.

이런 이유로 , module.name을 사용하거나 모듈내에서 필요한 것들만 가져다가 사용하는것이 가장 좋은방법이다.


문제

The code in the editor will show you everything available in the math module.


Click Save & Submit Code to check it out (you'll see sqrt, along with some other useful things like pi, factorial, and trigonometric functions).


12. On Beyond Strings

문자열과 관련된 내장함수들 ( .upper(), .lower(), str(), len() ) 을 이미 알고있고 이 함수들을 가지고 많은 것들을 할수 있다.

이거외에 조금더 분석적인 것들을 알아보자.


문제없음


13. max()

max() 함수는 입력된 숫자들 중 형태에 관계없이 비교하여 가장 큰수를 반환해준다.

ex> max(1,2,3) = 3


문제

Try out the max() function on line 3 of the editor.

You can provide any number of integer or float arguments to max().


14. min()

min은 max()와 반대로 가장 작은수를 반환한다.


문제

Go ahead and set minimum equal to the min() of any set of integers or floats you'd like.



15. abs()

abs() 는 절대값을 반환해준다.

ex>  abs(-3) = abs(3) = 3


문제

Set absolute equal to the absolute value of -42 on line 2


16. type()

마지막으로 type()은 데이터의 형태( 자료형 ) 을 반환해준다.

셈플코드의 출력은 아래와 같다.


문제

Have Python print out the type of an int, a float, and a str string in the editor. 

You can pick any values on which to call type(), so long as they produce one of each.


17. Review : Functions

샘플 코드를 보면서 복습해보자.


문제

1. First, def a function, shut_down, that takes one argument s. Don't forget the parentheses or the colon!

2. Then, if the shut_down function receives an s equal to "yes", it should return "Shutting down"

3. Alternatively, elif s is equal to "no", then the function should return "Shutdown aborted".

4. Finally, if shut_down gets anything other than those inputs, the function should return "Sorry"


18. Review: Modules

Importing modules를 복습해보자


문제

Import the math module in whatever way you prefer. 

Call its sqrt function on the number 13689 and print that value to the console.


19. Review: Built-In Functions

내장함수 사용하는것을 복습해보자.


문제

1. First, def a function called distance_from_zero, with one argument (choose any argument name you like).

2. If the type of the argument is either int or float, the function should return the absolute value of the function input.

3. Otherwise, the function should return "Nope"



Taking a Vacation ( 1 ~ 7 )


1. Before We Begin

파이썬의 함수들을 간단하게 복습해보자.

i. bigger라는 이름을 가지고 first,second 라는 이름의 두개의 인수를 받는 함수를 정의하였다.

ii. 이함수는 내장함수인 max() 함수를 이용하여 큰수를 출력한다.

iii. 마지막으로 bigger 함수는 True값을 반환한다.


문제

Write a function called answer that takes no arguments and returns the value 42.


Even without arguments, you will still need parentheses.


Don't forget the colon at the end of the function definition!


2. Planning Your Trip

여행시 시간당 지출을 계산하는 함수이다.


문제

Define a function called hotel_cost with one argument nights as input.

The hotel costs $140 per night. So, the function hotel_cost should return 140 * nights.


3. Getting There

샘플코드는 과일이름을 인수로 받고 해당과일의 색을 반환해주는 함수이다.


문제

1. Below your existing code, define a function called plane_ride_cost that takes a string, city, as input.

2. The function should return a different price depending on the location, similar to the code example above. Below are the valid destinations 

   and their corresponding round-trip prices.


"Charlotte": 183

"Tampa": 220

"Pittsburgh": 222

"Los Angeles": 475


4. Transportation

설명생략.


문제

1. Below your existing code, define a function called rental_car_cost with an argument called days.

2. Calculate the cost of renting the car:

3. Every day you rent the car costs $40.

4. if you rent the car for 7 or more days, you get $50 off your total.

5. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total.

6. You cannot get both of the above discounts.

7. Return that cost.


Just like in the example above, this check becomes simpler if you make the 7-day check an if statement and the 3-day check an elif statement.


5. Pull it Together

설명생략


문제

1. Below your existing code, define a function called trip_cost that takes two arguments, city and days.

2. Like the example above, have your function return the sum of calling the rental_car_cost(days), hotel_cost(days), and plane_ride_cost(city) 

    functions.

It is completely valid to call the hotel_cost(nights) function with the variable days. Just like the example above where we call double(n) with the

 variable a, we pass the value of days to the new function in the argument nights.


6. Hey, You Never Know !


문제

1. Modify your trip_cost function definition. Add a third argument, spending_money.

2. Modify what the trip_cost function does. Add the variable spending_money to the sum that it returns.


7. Plan Your Trip!


문제

After your previous code, print out the trip_cost( to "Los Angeles" for 5 days with an extra 600 dollars of spending money.


Don't forget the closing ) after passing in the 3 previous values!




[시스템해킹]버퍼오버플로우 실습

Posted by ZITOO
2015. 8. 28. 19:39 네트워크및보안&해킹/보안&해킹

  

  오버플로우에 대한 기본개념은 http://hackersstudy.tistory.com/27 을 보면 알 수 있다. 좀더 보충 해서 설명하자면 Buffer Overflow 공격에 취약한 함수는 strcpy, strcat, gets, fscanf, scanf, sprintf, sscanf, vfscanf, vsprintf, vscanf, streadd, strecpy, strtrns 이러한 함수 들이 있는데 이러한 함수들의 특징은 문자열의 최대크기를 정하지 않는다는 점이다.

 


STACK에는 지역변수, 인자, 함수종료후 돌아갈 곳의 주소(ret값)이 저장 되어 있다. 이 RET값을 다른 주소값으로 변환하여 관리자 권한을 획득하거나 악성코드의 주소등으로 바꾸는 등등 이런 것들이 STACK 기반의 버퍼오버플로우 공격이다.


HEAP는 malloc, calloc 등의 함수를 이용하여 프로그래머가 직접 공간을 할당하게 되는데, 이곳에 저장된 데이터 및 함수를 변경하여 원하는 결과를 얻어낼 수 있다. 이것이 HEAP 기반의 버퍼오버플로우 공격이다.  






 <그림 1 컴퓨터 메모리 구조


 


실습문제

 버퍼오버플로우를 시켜 함수 종료후 돌아가는 값인 ret의 주소를 쉘 프로그램의 주소로 덮어씌워서 쉘 프로그램을 실행시켜보자.


[코드1 stack.c]


실습을 하기에 앞서 ASLR(Address Space Layout Randomization)을 해제해야한다. ASLR은 리눅스 자체에서 오버플로우 공격을 막기 위해 프로그램 실행 시 메모리 주소를 랜덤 하게 바꾸어 주는 기술인데 해제하지 않으면 실습이 안되기 때문에 해제를 하고 시작해야 한다


gcc -fno-stack-protector -mpreferred-stack-boundary=2 -z execstack -o filename filename.c 

-fno-stack-protector : 스택 보호 기법 해제

-mpreferred-stack-boundary=2 : 스택 더미 없애기

-z execstack : 스택 메모리에 실행권한 부여


여기까지했다면 

$ gdb filename 

으로 gdb를 실행시켜보자. gdb 란 디버깅 작업 또는 프로그램의 안정성을 검사할 때 쓰는 것인데, 나는 해당 함수안의 어셈블리코드를 보기위해서 사용하였다. 만약 오류가 난다면 gdb를 사용하여 오류지점을 찾을 수 있다.


gdb 실행시킨뒤 

(gdb) disas main 

을 입력해주면 어셈블리코드가 출력된다.만약 No symbol table is loaded. Use the "file" command. 라는 실패 문구가 출력 된다면, debug option으로 compile

된 object가 아니기 때문에 나오는 문구이므로  

gcc filename.c -o filename -ggdb

와 같이 재컴파일을 해주도록 하자.

<그림2 stack.c main함수 부분 어셈블리 코드>

 스택기반 버퍼오버플로우는 argv로 들어오는 인자값을 buffer의 크기보다 크게 주어서 ret값의 주소가 있는 영역까지 넘치게 하여서 ret값을 악성코드로의 주소로 덮어버리는 것이다. 여기 실습에서는 널리 배포되어 있는 eggshell 소스로 쉘 프로그램을 실행하게 할것이다. stack프로그램 리턴주소대신에 eggshell 프로그램안에 있는 쉘코드를 집어넣어 동작하게 할것이다.


[코드2 eggshell.c]


<그림3 eggshell 주소>


 소스를 gcc로 컴파일해서 실행하여면 eggshell 프로그램의 쉘코드가 위치한 주소를 알 수 있다. 이제 이 주소를 ret값 위에 덮어 씌우기만 하면 된다.주소값을 입력할때 리틀-엔디안(Little-Endian)방식을 사용합니다. 예를 들어 위에 eggshell 주소가 0xbffff6a8이라면 

\xa8\xf6\xff\bf

라고 입력해주면 된다.


<그림4 버퍼오버플로우 발생>

 위에 그림을 보면 a가 11개까지는 오류가 발생하지 않는데, 12개부터 오류가 발생하는걸 볼 수 있다. 위에서 stack.c 코드를 보면 버퍼를 8로 설정해놧는데 왜 8개를 넘는 11개를 입력 하였는데 오류가 나지 않는걸까? 먼저 ./stack + a*11 이기때문에 위에 입력한 건 12바이트라고 할수 있다. 13바이트부터 오류가 발생하는 이유는 ebp(Extended Base Pointer)때문이다. 버퍼의 8byte + ebp의 4byte 이기때문에 12바이트이고 그 뒤부터 ret값이 오게된다. 

perel언어를 사용하기위해서 LANGUAGE를 설정해줘야 한다

export LANG = "ko_KR.euckr" 

echo $LANG 으로 자신의 LANGUAGE를 확인 할수 있다


<그림5 쉘 프로그램 실행 성공> 

마지막으로 

$./filename `perl -e 'print "A"x12, "자신이 실행하고자하는 프로그램의 주소(little edian으로 입력)"'` 

를 입력하면 쉘 코드가 실행되는 걸 알 수 있다.



출처 http://blog.naver.com/skddms/110180973377



'네트워크및보안&해킹 > 보안&해킹' 카테고리의 다른 글

CrackMe2 문제풀이  (6) 2015.07.17
DLL Injection  (6) 2015.06.21
CrackMe 문제풀이 (리버싱 기초)  (6) 2015.06.08
리버스 엔지니어링  (3) 2015.06.08
버퍼오버플로우  (928) 2015.06.08