문제
https://school.programmers.co.kr/learn/courses/30/lessons/120907
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
해당 문제는 주어진 식과 결과가 서로 맞는지 검증한 불리언 값들을 리스트에 담아 반환하는 문제이다. 사실 파이썬에서는 "수식 계산하면 eval()"를 자주 사용 했기 때문에, 이를 활용하여 코드를 작성하였다.
🖥️ main.py
from typing import List
def solution(quizs) -> List[str]:
answer: List[str] = []
for quiz in quizs:
quiz = quiz.split(" = ")
if eval(quiz[0]) == int(quiz[1]):
answer.append("O")
else:
answer.append("X")
return answer
문제를 맞히고 난 뒤, 맞춘 사람들 코드를 보면서 내가 흡수할만한 부분이 있는지 체크를 하는데, 다른 코드에서 재밌는 주제로 이야기하는 것을 보게 되었다.
eval함수가 보안적으로 취약한 부분이 있다는데 이를 모르고 사용했으니, 이에 대해서 공부를 해봐야겠다는 생각이 들었다. 일단 파이썬 공식문서에서 eval함수에 대해 정의한 글을 찾아 읽어 봤다.
- eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions.
string타입인데도 불구하고 eval을 실행하면 연산의 값을 얻을 수 있다는 장점이 있지만, "eval이 사용자가 입력한 string 값을 시스템에 전달하기 때문에 악의적인 명령어도 그대로 실행한다"라는 문제점을 가지고 있었다.
좀 더 쉽게 이해하기 위해 아래에 그 취약점을 이용하여 서버 root 디렉터리 정보를 가져오는 코드를 작성하였다.
🖥️ main.py
x = str(input("실행할 수식을 입력하세요 : ")
print eval(x)
============
실행할 수식을 입력하세요 : __import__('os').system('ls /')
Applications Volumes home
Developer bin installer.failurerequests
Library cores macOS Install Data
Network data net
System dev private
Users etc sbin
이런 일이 일어나는 이유는 eval(expression)이 expression에 들어온 해당 표현식을 그대로 실행 한 뒤 그 결과 값만을 가져오기 때문이었다. 따라서 파이썬에서 eval함수를 사용할 때는 이런 부분을 고려하여 사용하도록 하여야겠다.
'Algorithm > Programmers' 카테고리의 다른 글
프로그래머스 LV2 [1차] 캐시 (0) | 2023.07.30 |
---|---|
프로그래머스 LV0 접미사인지 확인하기 (2) | 2023.07.19 |
프로그래머스 LV2 JadenCase 문자열 만들기 (0) | 2023.07.19 |
프로그래머스 LV2 튜플 (0) | 2023.07.17 |
프로그래머스 LV2 영어 끝말잇기 (0) | 2023.07.17 |