본문 바로가기

CERT C/전처리기

[CERT C/전처리기] (2) 인클루전 가드 미처리의 취약성

의미

인클루전 가드란, 여러 개의 같은 헤더파일이 include 되지 않도록 조건을 통해 발생할 수 있는 에러를 막아주는 기능이다.

 

동작 방식

이미 존재하는 헤더 파일을 추가시키려고 할 때, 인클루전 가드에 의해서 걸러지므로 헤더 파일 충돌이 일어나지 않는다.

 

문제 코드 1. 헤더 파일에 항상 인클루전 가드를 둬라

main 함수에서 빌드를 할 경우 출력을 예상해보기

// person.h
struct Person
{
	/* contents */
}
// student.h
#include <person.h>

Person stdudent1;

/*
	contents
*/
// student.h
#include <person.h>

Person stdudent1;

/*
	contents
*/

정답은 위에서 말했다시피 헤더파일 충돌로 오류가 나게 됩니다.

취약점 분석 및 해결 코드 1

분석 : main.c에서 person.h를 include 한 상태인데 student.h에서 person.h를 다시 include하면서 헤더파일 충돌이 일어나게 된다.

 

해결 방법 : 인클루전 가드를 사용한다.

 

// student.h
#ifndef CHECK_HEADER_H
#define CHECK_HEADER_H
#include <person.h>
#endif
Person stdudent1;

/*
	contents
*/
// main.c
#ifndef CHECK_HEADER_H
#define CHECK_HEADER_H
#include <person.h>
#endif
#include <student.h>

int main()
{
  /*
      contents
  */
}

빌드 성공

 

 

POINT

  • 헤더파일 충돌을 막기 위해서 반드시 인클루전 가드를 사용해라

참조


PRE06-C. Enclose header files in an include guard

 

wiki.sei.cmu.edu/confluence/display/c/PRE00-C.+Prefer+inline+or+static+functions+to+function-like+macroswiki.sei.cmu.edu/confluence/display/c/PRE06-C.+Enclose+header+files+in+an+include+guard