C/C++ Secure Function 에 대해서
Visual Studio 2005 Secure Function 에 좀더 쓰겠습니다.

사실 strcpy 류의 함수를 _s 의 postfix를 붙여주는 것만으로는 충분하지 않습니다.

char szBuf[10];
strcpy(szBuf, “test”)

와 같은 코드를 그냥 컴파일 하면 분명히 deprecated warning이 나옵니다.
그리고 _CRT_SECURE_NO_DEPRECATE 를 정의하거나, #pragma warning 을 이용해서 warning control을 할 수 있습니다.
이 방법은 예전의 방법입니다. Secure check를 전혀 하지 않는 방법이지요. 그런데 C++의 특성상 string manipulation 과정에서
buffer overrun이나 stack을 깨먹는 경우가 허다해서 _s postfix가 붙은 함수들이 나왔습니다.

하나만 살펴보면

errno_t strcpy_s(
char *strDestination,
size_t sizeInBytes,
const char *strSource
);

와 같은 signature를 띄고 있습니다. 기존의 strcpy 가 2개의 parameter를 받는 반면 이 함수는 3개를 받습니다.
그래서 C/C++에서는 아래와 같이 수정해야 합니다.

char szBuf[10];
strcpy_s(szBuf, 10, “test”)

그런데 사용자가 C가 아닌 C++을 사용하고 있고, _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 값이 1로 define 되어 있다면(default로 1로 정의되어 있습니다.)
있다면, template function의 도움을 받아서 좀더 쉽게 수정을 할 수가 있는데요, strcpy_s 의 template function signature는 아래와 같습니다.

template <size_t size>
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only

첫번째 parameter가 char * 가 아니라 char 배열에 대한 reference를 받는 형태로 변경되었습니다. 또한 type argument로 size_t 형태의 size를 받습니다.
이 함수를 사용하기 위해서는, 코드를 다음과 같이 바꾸어야 합니다.

char szBuf[10]
strcpy_s<10>(szBuf, “test”);

하지만 template function은 type inferencing 을 수행할 수 있으므로,

char szBuf[10]
strcpy_s(szBuf, “test”);

라고도 쓸 수 있습니다.
그래서 그냥 _s 만 쓰면 만사가 다 해결 될 것 같은데, 또 다른 문제가 있습니다. 위의 template function의 첫번째 parameter가 반드시 배열이여야 한다는 것이지요.

아래 코드를 보면 알 수 있는데요.

int _tmain(int argc, _TCHAR* argv[])
{
char arrayChar[10];
strcpy_s(arrayChar, "hello");

char *pDynamicChar = new char[10];
strcpy_s(pDynamicChar, "hello");
delete [] pDynamicChar;
return 0;
}

첫번째 strcpy_s 는 정확히 char array를 parameter로 전달됩니다. 하지만 두번째 strcpy_s 는 char *를 parameter로 전달합니다.
이 경우 template function의 type inferencing 이 일어나지 않으므로, “error C2660: 'strcpy_s' : function does not take 2 arguments” 와 같은 오류가 발생하게 됩니다.
두번째 pattern이 매우 널리 사용되는 구조임에 불구하고 말이죠. 이 경우 위의 코드는 아래와 같이 변경되어야 합니다.

int _tmain(int argc, _TCHAR* argv[])
{
char arrayChar[10];
strcpy_s(arrayChar, "hello");

char *pDynamicChar = new char[10];
strcpy_s(pDynamicChar, 10, "hello");
delete [] pDynamicChar;
return 0;
}

원래의 strcpy_s() 함수를 쓴거죠. 즉 template function 은 static array에 대해서만 동작을 합니다. 이것은 자칫 큰 혼란을 가져 올 수 있는데, 어떨때는 strcpy_s가 2개의 parameter를 가지는 것처럼 보였다가, 또 어떨때는 strcpy_s 가 반드시 3개의 parameter를 가져야 하는 것 처럼 보이기 때문입니다.

이러한 혼돈을 피하기 위해서는, 제 개인적인 견해로는 위에서 예를 들어 드린 template function은 사용하지 않는 것이 더 좋을 것 같습니다. 즉 처음부터 사용자가 _s postfix가 붙은 함수들은 모두 parameter가 한 개씩 늘었다고 이해하는 편이, 혼돈일 덜하기 때문입니다. 따라서

int _tmain(int argc, _TCHAR* argv[])
{
char arrayChar[10];
strcpy_s(arrayChar, 10, "hello");

char *pDynamicChar = new char[10];
strcpy_s(pDynamicChar, 10, "hello");
delete [] pDynamicChar;
return 0;
}

와 같이 쓰는 것이 좀더 일관되어 보입니다. 만일 이렇게 쓰기로 결정했다면 이제 template overload function 를 원천적으로 쓰지 못하도록 막는 것이 필요합니다.
아까 말씀드린데로 _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 가 1로 정의되어 있을 때만 template overload function이 정의 되므로, 이녀석을 0로 define 해주는 것이 필요합니다.
그런데
#define _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 0
구문을 어디에 둘것인가도 좀 까다로운데, 가장 좋은 방법은 stdafx.h 파일에 header file include 이전에 위치시키는 것이 가장 좋겠습니다.
즉,

#pragma once

#define _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 0

#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include
#include

와 같이 쓰면 됩니다.

이런 secure Template overloads와 관련해서 3가지의 constant가 있는데요

_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES
위에서 알아본 바와 같이 _s postfix가 붙은 함수 이름으로 template function을 정의합니다.
즉,

errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only

를 정의하게 됩니다.

_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
_s postfix가 붙지 않음 함수 이름으로 template function을 정의합니다.
즉,
errno_t strcpy(
char (&strDestination)[size],
const char *strSource
); // C++ only

를 정의하게 됩니다.

_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 를 1로 정의하게 되면
기존에 counter를 가지던 함수들 즉 strncpy 등의 함수에 대해서도 template overload function을 정의하게 됩니다.

Default 값은 각각

_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 1
_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 0
_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 0

입니다.

여기서 끝이 아닙니다. 또다른 문제는 return 형에 있습니다.
기존에 strcpy 류의 함수를 보면 dest string의 char *를 return 하도록 구성되어 있는데, secure function 들은 error_t 형태를 반환하게 됩니다.
다행이도 이 부분은 compiler 가 conversion 오류를 발생하기 때문에 찾기가 쉽습니다.

마지막으로 제나름의 Guideline을 알려드리면,

1. Secure function을 쓸건지 안쓸건지를 결정하자
2. Secure function을 안 쓸거라면 과감하게 _CRT_SECURE_NO_DEPRECATE 를 정의하고 프로그램이 죽어 나자빠 질때를 기다리자.
3. Secure function을 쓸거라면 _s postfix를 가진 함수로 모두 대체하고, parameter는 length가 포함된 함수를 쓰자.
4. template overload function 은 쓰지 않도록 CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 를 stdafx.h 파일에서 0 으로 정의하자.
5. 반환값을 사용하지 말자, 반환값의 형변환 오류가 발생하면 모두 변경한다.

그러나 이러한 Guideline이 모든 경우에 다 적용이 가능한 것은 아닙니다.
이미 개발되어 있는 code의 일부를 가져와서 쓰는 경우나, 어쩔 수 없이 예전의 방식을 써야 하는 경우가 아직은 상당히 존재하리라 예측됩니다.

감사합니다.

Regards,
김명신

ps)
최근에 제 글을 퍼가시는 분 중에 출처를 밝히지 않고 자신의 블로그에 올려 놓은 글을 본적이 여러번 있는데요.
많이 많이 퍼가시되 출처를 꼭 기재하셨으면 합니다. 아니면 세상의 평화를 위해서 Link를 등록하는게 더 좋을지도 모르겠군요.
감사합니다.
by 김명신 | 2006/06/21 15:49 | 복잡한컴퓨터이야기 | 트랙백(39) | 덧글(9)
트랙백 주소 : http://himskim.egloos.com/tb/1352834
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
Tracked from at 2007/03/10 23:43

제목 : downey tax preperation
christmas decorator bridal jewelry canada 360 degrees innovation...more

Tracked from at 2007/03/10 23:45

제목 : debt elimination science
Christmas greeting cards quickbooks inventory management personalized wedding favors...more

Tracked from at 2007/03/10 23:46

제목 : debt collectors
debt reduction credit card consolodation charm bracelets debt solution...more

Tracked from at 2007/03/10 23:47

제목 : continental airline ticket
irs tax relief hawaii mls listings tax deductible expenses...more

Tracked from at 2007/03/10 23:50

제목 : blue cross insurance
north georgia vacation rentals replica purses lake tahoe cabin rentals...more

Tracked from at 2007/03/10 23:51

제목 : rolex watch usa
internet business promoter v8.0.1 business edition crack wedding photographers california cheapest prepaid cellular...more

Tracked from at 2007/03/13 02:21

제목 : adsl broadband
homes for sale in hawaii debt elimination group hawaiian wear...more

Tracked from at 2007/03/13 02:21

제목 : business card designer plus ..
third degree burns borders books and music 360 degree feedback system...more

Tracked from at 2007/03/13 02:22

제목 : hard rock hotel
home loan mortgage rate diamond watches home mortgage refinancing...more

Tracked from at 2007/03/13 02:23

제목 : drunk orgy
drunk girls having sex drunk moms drunk drugged sluts...more

Tracked from at 2007/03/13 02:23

제목 : implants shemale slave
lingerie playmates galleries free shemale clips lingerie online stores...more

Tracked from at 2007/03/13 02:24

제목 : pants down rectal thermometer
jennifer lopez\'s butt cum gusher j lo\'s ass...more

Tracked from at 2007/03/13 02:24

제목 : costume hat jewelry red whol..
chuck taylor shoe rolex replica jordan shoe...more

Tracked from at 2007/03/13 02:24

제목 : ebay chevelle
alaska cruises lakewood tax services kauai hawaii...more

Tracked from at 2007/03/14 04:28

제목 : girls taking a shit
lesbian scat desperate housewives naked scat shit clips sample...more

Tracked from at 2007/03/14 04:31

제목 : dildos
milf seekers fingering milf hunter movies...more

Tracked from at 2007/03/14 23:19

제목 : abercrombie guys
cheap replica watches budget rentals replica designer purses...more

Tracked from at 2007/03/14 23:23

제목 : car wash equipment
debt and bill consolidation galleria jared jewelry owner debt reduction software...more

Tracked from at 2007/03/16 00:43

제목 : canon copiers
fathers day gifts professional wedding photography ohio department of taxation...more

Tracked from at 2007/03/17 02:04

제목 : flashing college girls
dare to flash horses insist mating flashing keypads...more

Tracked from at 2007/03/17 02:04

제목 : office secretary img
boss snow plows lesbian fisting hot secretary in stocking...more

Tracked from at 2007/03/17 02:09

제목 : female g spot
females squirting boss gt8 boys ejaculating...more

Tracked from at 2007/03/17 02:09

제목 : daughter sucking dad
father daughter fuck fest lesbian humiliation dad son action...more

Tracked from at 2007/03/17 02:22

제목 : cytherea female ejaculation
big black booty free female ejaculation movies beautiful butts...more

Tracked from at 2007/03/17 03:06

제목 : big fat tits
big thick butt black women latina fantasy fat cunt...more

Tracked from at 2007/03/17 03:20

제목 : breast massage
mechanical fucking machines developing breasts kinky sex toys...more

Tracked from at 2007/03/17 03:21

제목 : public flasher
calgary public library horse rape mardi gras tits...more

Tracked from at 2007/03/17 03:21

제목 : nicole richie flashing
mardi gras history free rape movies flashing truckers...more

Tracked from at 2007/03/17 03:21

제목 : female bondage
gay beef spanking art gay latino men...more

Tracked from at 2007/03/17 03:22

제목 : bang bus girl
gang bang squad masturbating girls young glory hole locations...more

Tracked from at 2007/03/17 03:22

제목 : hunks galore
chippendale hunk gallery bound damsels in a skirt beefy hunks...more

Tracked from at 2007/03/17 03:22

제목 : scat slave
hidden cameras girls bathroom scat crankshaft girls pissing their panties...more

Tracked from at 2007/03/17 03:23

제목 : gay son fucking dad
lesbian incest nymph young mom mature son gallery...more

Tracked from at 2007/03/17 03:23

제목 : shemale panties
post op teen transsexuals erotic sexy lingerie free shemale gallery...more

Tracked from at 2007/03/17 03:23

제목 : hairy pussys
hirsute gay bestiality bush twins...more

Tracked from at 2007/03/17 03:23

제목 : shaved cunt
incest stories free naked young girl dad and son gay sex...more

Tracked from at 2007/03/17 03:24

제목 : shemale art
black tranny plus size lingerie shemale fucking...more

Tracked from at 2007/03/18 23:58

제목 : beyonce upskirt
britney spears flashing lesbians with dildo spy satellites...more

Tracked from at 2007/03/18 23:59

제목 : amatuer nudes
homemade penis pump blonde chicks amateurpages...more

Commented by 리노 at 2006/06/21 17:30
좋은 정보 감사합니다. 올려주신 글을 계기로, 그 동안 바쁘다는 핑계로 방치하고 있었던, Secure function에 대해서 좀 더 자세히 알아봐야 겠네요..
Commented by 김명신 at 2006/06/23 11:20
리노 : 특별한 어려움은 없으실 겁니다. 즐거운 공부 되세요.
Commented by 김병욱 at 2007/09/18 23:33
VS 6.0에서는 사용할 수가 없군요. 사용하려 해 봤더니 deprecated 예약어 때문에 막히는군요.
Commented by 김병욱 at 2007/09/27 14:34
근데...strcpy_s를 사용하여 프로그램을 작성하여도 프로그램을 배포 할때 특별한 dll을 내려주어야 하는건 없는 겁니까?
MSDN에 보니 라이브러리에 대한 내용은 없고 Windows95도 호환된다고 나오는것 보니까 컴파일 타임에만 작동하는 것 같은데...맞나요?
Commented by 곽선정 at 2009/02/27 11:27
vc6.0 소스들은 2008로 바꾸라는 회사의 명령이 있어서 자료를 찾다보니 여기까지 왔네요..
잘 지내시져?..^^..좋은글 잘보고 갑니다..
Commented by 김명신 at 2009/03/02 14:35
곽선정 : 오호라 오랫만이군 아직 VC6.0 이야기를 하는 것 보니 여전히 현역인듯. 고생많이하고 가끔 연락줘.
Commented by 아리새의펜촉 at 2009/05/22 16:02
프로그래밍과 보안을 공부하는 대학생입니다.

내용을 요약하면 strcpy_s 그대로 쓰되, 플래그를 수정해주라는 내용 같은데 제가 제대로 이해한 게 맞는지...
다만, strncpy도 있는데 굳이 strcpy_s를 쓰는 경우가 많은지가 궁금합니다.
저 같은 경우는 gcc를 쓴느지라 strcpy_s가 없거든요.

그리고 Secure function에 대해 공부하려면 어떤 참고 문헌이 좋은지 소개 부탁드립니다.
Commented by 김명신 at 2009/05/25 15:12
아리새의 펜촉 : 네.. 대강 요약하면 이해하신 내용이 맞는 것 같습니다. secure function에 대한 것은 msdn 문서가 가장 잘 나와있지 않은가 싶고요, 최근에 제가 번역한 windows via c/c++에도 나와있습니다. 감사합니다.
Commented by MuMbi준환 at 2009/07/03 15:24
_s secure function 을 사용을 자제하자는 의견을 들었습니다.

그 이유는 secure function 은 vs 에서만 돌아간다고 하는군요.

이식성을 위해서는 secure function 을 사용하면 안된다네요.

좋은 정보 감사합니다.

:         :

:

비공개 덧글



< 이전페이지 다음페이지 >