보안 기초 — contextIsolation과 CSP 설정
"Electron 앱은 브라우저보다 더 위험하다" — 웹 앱과 달리 파일 시스템, 프로세스 실행 등 시스템 전체에 접근할 수 있기 때문입니다.
Electron 보안 체크리스트
| 설정 | 권장값 | 이유 |
|---|---|---|
contextIsolation | true (기본) | Prototype pollution 방지 |
nodeIntegration | false (기본) | 렌더러에서 Node.js 접근 차단 |
sandbox | true | OS 수준 프로세스 격리 |
webSecurity | true (기본) | 동일 출처 정책 유지 |
allowRunningInsecureContent | false (기본) | HTTP 콘텐츠 차단 |
contextIsolation
const win = new BrowserWindow({
webPreferences: {
contextIsolation: true, // 기본값 — 변경하지 마세요
nodeIntegration: false, // 기본값 — 변경하지 마세요
preload: path.join(__dirname, 'preload.js'),
},
});
contextIsolation이 true이면:
- Preload 스크립트와 렌더러의 JavaScript 컨텍스트가 완전히 분리
Array.prototype.push같은 빌트인 객체를 오염시켜도 서로 영향 없음contextBridge를 통해서만 API 노출 가능
Content Security Policy (CSP)
<!-- index.html — CSP 메타 태그 -->
<meta http-equiv="Content-Security-Policy"
content="
default-src 'self';
script-src 'self';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
font-src 'self';
"
/>
CSP 디렉티브 설명
| 디렉티브 | 설명 |
|---|---|
default-src 'self' | 기본적으로 같은 origin만 허용 |
script-src 'self' | 인라인 스크립트와 외부 스크립트 차단 |
style-src 'self' 'unsafe-inline' | 인라인 스타일 허용 |
connect-src | fetch/XHR 요청 허용 대상 |
session에서 CSP 설정
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; script-src 'self'"
],
},
});
});
Sandbox 모드
const win = new BrowserWindow({
webPreferences: {
sandbox: true, // OS 수준 프로세스 격리
preload: path.join(__dirname, 'preload.js'),
},
});
Sandbox가 활성화되면:
- 렌더러 프로세스가 OS 수준에서 격리됨
- Preload 스크립트에서
require()가 제한적으로만 동작 electron,events,timers,url모듈만 require 가능
외부 콘텐츠 로드 시 보안
// 외부 URL 로드를 제한
win.webContents.on('will-navigate', (event, url) => {
const allowedOrigins = ['file://', 'app://'];
if (!allowedOrigins.some(origin => url.startsWith(origin))) {
event.preventDefault();
shell.openExternal(url);
}
});
// 새 창 열기 제한
win.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https://')) {
shell.openExternal(url);
}
return { action: 'deny' };
});
위험한 설정 목록
// ⚠️ 절대 프로덕션에서 사용하지 마세요
const DANGEROUS = {
nodeIntegration: true, // 렌더러에서 require 사용 가능
contextIsolation: false, // 컨텍스트 격리 해제
webSecurity: false, // 동일 출처 정책 해제
allowRunningInsecureContent: true, // HTTP 콘텐츠 허용
experimentalFeatures: true, // 실험 기능 활성화
enableBlinkFeatures: 'dangerous', // 위험한 Blink 기능
};
면접 포인트 정리
contextIsolation: true+nodeIntegration: false가 보안의 기본- CSP로 외부 스크립트 실행을 차단하여 XSS 방지
- Sandbox로 OS 수준 격리 적용 가능
- 외부 URL로의 네비게이션을
will-navigate에서 차단 webSecurity: false는 개발 중에도 사용을 자제
보안 기초를 다뤘으면, 다음은 보안 심화를 알아봅시다.
댓글 로딩 중...