기본 콘텐츠로 건너뛰기

CPP-lang-vulnerabilities

C++ 언어 공통 취약점

C++는 C가 아니다. 이것이 무엇보다 첫 번째로 염두해야할 점이다. printf(), char*와 유사한 것들을 사용하지 말고 C++의 방향성대로 코드를 진행하자. 만약 C의 방식을 고수해야한다면 C의 보안 표준 또한 함께 참고한다.

Memory handling

  • malloc()free()함수를 사용하지 않고 new()delete()함수를 사용한다. 코드에서 Exception 발생 시 new에 의해 할당된 메모리는 할당 취소된다.

String handling

  • char*를 사용하지 않고 std::string 클래스를 사용한다.
  • fscanf를 사용하지 않고 std::outputstream 오브젝트와 함께 >>연산자를 사용한다.

File handling

  • fopen()함수를 사용하지 않는다. 읽기 위해서는 std::ifstream를 사용한다. 쓸 때는 좀 더 복잡한 고려사항이 있는 데, C의 open 플래그 값과 함께 open()호출하고 boost 라이브러리를 사용하면 파일 기술자 자체에서 좋은 스트림을 얻을 수 있다.
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

namespace io = boost::iostreams;

class ex {};

int main ()
{
    int fd = open("/my/file", O_WRONLY|O_CREAT|O_EXCL, 0600);
    if (fd == -1)
        throw ex();
    io::stream_buffer<io::file_descriptor_sink> fp (fd);
    std::ostream out(&fp);

    out << "Hello, world" << std::endl;
    return 0;
}