security-warnings.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { webFrame } from 'electron';
  2. import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
  3. import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
  4. let shouldLog: boolean | null = null;
  5. const { platform, execPath, env } = process;
  6. /**
  7. * This method checks if a security message should be logged.
  8. * It does so by determining whether we're running as Electron,
  9. * which indicates that a developer is currently looking at the
  10. * app.
  11. *
  12. * @returns {boolean} - Should we log?
  13. */
  14. const shouldLogSecurityWarnings = function (): boolean {
  15. if (shouldLog !== null) {
  16. return shouldLog;
  17. }
  18. switch (platform) {
  19. case 'darwin':
  20. shouldLog = execPath.endsWith('MacOS/Electron') ||
  21. execPath.includes('Electron.app/Contents/Frameworks/');
  22. break;
  23. case 'freebsd':
  24. case 'linux':
  25. shouldLog = execPath.endsWith('/electron');
  26. break;
  27. case 'win32':
  28. shouldLog = execPath.endsWith('\\electron.exe');
  29. break;
  30. default:
  31. shouldLog = false;
  32. }
  33. if ((env && env.ELECTRON_DISABLE_SECURITY_WARNINGS) ||
  34. (window && window.ELECTRON_DISABLE_SECURITY_WARNINGS)) {
  35. shouldLog = false;
  36. }
  37. if ((env && env.ELECTRON_ENABLE_SECURITY_WARNINGS) ||
  38. (window && window.ELECTRON_ENABLE_SECURITY_WARNINGS)) {
  39. shouldLog = true;
  40. }
  41. return shouldLog;
  42. };
  43. /**
  44. * Checks if the current window is remote.
  45. *
  46. * @returns {boolean} - Is this a remote protocol?
  47. */
  48. const getIsRemoteProtocol = function () {
  49. if (window && window.location && window.location.protocol) {
  50. return /^(http|ftp)s?/gi.test(window.location.protocol);
  51. }
  52. };
  53. /**
  54. * Checks if the current window is from localhost.
  55. *
  56. * @returns {boolean} - Is current window from localhost?
  57. */
  58. const isLocalhost = function () {
  59. if (!window || !window.location) {
  60. return false;
  61. }
  62. return window.location.hostname === 'localhost';
  63. };
  64. /**
  65. * Tries to determine whether a CSP without `unsafe-eval` is set.
  66. *
  67. * @returns {boolean} Is a CSP with `unsafe-eval` set?
  68. */
  69. const isUnsafeEvalEnabled: () => Promise<boolean> = function () {
  70. // Call _executeJavaScript to bypass the world-safe deprecation warning
  71. return webFrame._executeJavaScript(`(${(() => {
  72. try {
  73. eval(window.trustedTypes.emptyScript); // eslint-disable-line no-eval
  74. } catch {
  75. return false;
  76. }
  77. return true;
  78. }).toString()})()`, false);
  79. };
  80. const moreInformation = `\nFor more information and help, consult
  81. https://electronjs.org/docs/tutorial/security.\nThis warning will not show up
  82. once the app is packaged.`;
  83. /**
  84. * #1 Only load secure content
  85. *
  86. * Checks the loaded resources on the current page and logs a
  87. * message about all resources loaded over HTTP or FTP.
  88. */
  89. const warnAboutInsecureResources = function () {
  90. if (!window || !window.performance || !window.performance.getEntriesByType) {
  91. return;
  92. }
  93. const isLocal = (url: URL): boolean =>
  94. ['localhost', '127.0.0.1', '[::1]', ''].includes(url.hostname);
  95. const isInsecure = (url: URL): boolean =>
  96. ['http:', 'ftp:'].includes(url.protocol) && !isLocal(url);
  97. const resources = window.performance
  98. .getEntriesByType('resource')
  99. .filter(({ name }) => isInsecure(new URL(name)))
  100. .map(({ name }) => `- ${name}`)
  101. .join('\n');
  102. if (!resources || resources.length === 0) {
  103. return;
  104. }
  105. const warning = `This renderer process loads resources using insecure
  106. protocols. This exposes users of this app to unnecessary security risks.
  107. Consider loading the following resources over HTTPS or FTPS. \n${resources}
  108. \n${moreInformation}`;
  109. console.warn('%cElectron Security Warning (Insecure Resources)',
  110. 'font-weight: bold;', warning);
  111. };
  112. /**
  113. * #2 on the checklist: Disable the Node.js integration in all renderers that
  114. * display remote content
  115. *
  116. * Logs a warning message about Node integration.
  117. */
  118. const warnAboutNodeWithRemoteContent = function (nodeIntegration: boolean) {
  119. if (!nodeIntegration || isLocalhost()) return;
  120. if (getIsRemoteProtocol()) {
  121. const warning = `This renderer process has Node.js integration enabled
  122. and attempted to load remote content from '${window.location}'. This
  123. exposes users of this app to severe security risks.\n${moreInformation}`;
  124. console.warn('%cElectron Security Warning (Node.js Integration with Remote Content)',
  125. 'font-weight: bold;', warning);
  126. }
  127. };
  128. // Currently missing since it has ramifications and is still experimental:
  129. // #3 Enable context isolation in all renderers that display remote content
  130. //
  131. // Currently missing since we can't easily programmatically check for those cases:
  132. // #4 Use ses.setPermissionRequestHandler() in all sessions that load remote content
  133. /**
  134. * #5 on the checklist: Do not disable websecurity
  135. *
  136. * Logs a warning message about disabled webSecurity.
  137. */
  138. const warnAboutDisabledWebSecurity = function (webPreferences?: Electron.WebPreferences) {
  139. if (!webPreferences || webPreferences.webSecurity !== false) return;
  140. const warning = `This renderer process has "webSecurity" disabled. This
  141. exposes users of this app to severe security risks.\n${moreInformation}`;
  142. console.warn('%cElectron Security Warning (Disabled webSecurity)',
  143. 'font-weight: bold;', warning);
  144. };
  145. /**
  146. * #6 on the checklist: Define a Content-Security-Policy and use restrictive
  147. * rules (i.e. script-src 'self')
  148. *
  149. * Logs a warning message about unset or insecure CSP
  150. */
  151. const warnAboutInsecureCSP = function () {
  152. isUnsafeEvalEnabled().then((enabled) => {
  153. if (!enabled) return;
  154. const warning = `This renderer process has either no Content Security
  155. Policy set or a policy with "unsafe-eval" enabled. This exposes users of
  156. this app to unnecessary security risks.\n${moreInformation}`;
  157. console.warn('%cElectron Security Warning (Insecure Content-Security-Policy)',
  158. 'font-weight: bold;', warning);
  159. }).catch(() => {});
  160. };
  161. /**
  162. * #7 on the checklist: Do not set allowRunningInsecureContent to true
  163. *
  164. * Logs a warning message about disabled webSecurity.
  165. */
  166. const warnAboutInsecureContentAllowed = function (webPreferences?: Electron.WebPreferences) {
  167. if (!webPreferences || !webPreferences.allowRunningInsecureContent) return;
  168. const warning = `This renderer process has "allowRunningInsecureContent"
  169. enabled. This exposes users of this app to severe security risks.\n
  170. ${moreInformation}`;
  171. console.warn('%cElectron Security Warning (allowRunningInsecureContent)',
  172. 'font-weight: bold;', warning);
  173. };
  174. /**
  175. * #8 on the checklist: Do not enable experimental features
  176. *
  177. * Logs a warning message about experimental features.
  178. */
  179. const warnAboutExperimentalFeatures = function (webPreferences?: Electron.WebPreferences) {
  180. if (!webPreferences || (!webPreferences.experimentalFeatures)) {
  181. return;
  182. }
  183. const warning = `This renderer process has "experimentalFeatures" enabled.
  184. This exposes users of this app to some security risk. If you do not need
  185. this feature, you should disable it.\n${moreInformation}`;
  186. console.warn('%cElectron Security Warning (experimentalFeatures)',
  187. 'font-weight: bold;', warning);
  188. };
  189. /**
  190. * #9 on the checklist: Do not use enableBlinkFeatures
  191. *
  192. * Logs a warning message about enableBlinkFeatures
  193. */
  194. const warnAboutEnableBlinkFeatures = function (webPreferences?: Electron.WebPreferences) {
  195. if (!webPreferences ||
  196. !Object.prototype.hasOwnProperty.call(webPreferences, 'enableBlinkFeatures') ||
  197. (webPreferences.enableBlinkFeatures != null && webPreferences.enableBlinkFeatures.length === 0)) {
  198. return;
  199. }
  200. const warning = `This renderer process has additional "enableBlinkFeatures"
  201. enabled. This exposes users of this app to some security risk. If you do not
  202. need this feature, you should disable it.\n${moreInformation}`;
  203. console.warn('%cElectron Security Warning (enableBlinkFeatures)',
  204. 'font-weight: bold;', warning);
  205. };
  206. /**
  207. * #10 on the checklist: Do Not Use allowpopups
  208. *
  209. * Logs a warning message about allowed popups
  210. */
  211. const warnAboutAllowedPopups = function () {
  212. if (document && document.querySelectorAll) {
  213. const domElements = document.querySelectorAll('[allowpopups]');
  214. if (!domElements || domElements.length === 0) {
  215. return;
  216. }
  217. const warning = `A <webview> has "allowpopups" set to true. This exposes
  218. users of this app to some security risk, since popups are just
  219. BrowserWindows. If you do not need this feature, you should disable it.\n
  220. ${moreInformation}`;
  221. console.warn('%cElectron Security Warning (allowpopups)',
  222. 'font-weight: bold;', warning);
  223. }
  224. };
  225. // Currently missing since we can't easily programmatically check for it:
  226. // #11 Verify WebView Options Before Creation
  227. // #12 Disable or limit navigation
  228. // #13 Disable or limit creation of new windows
  229. // #14 Do not use `openExternal` with untrusted content
  230. // #15 on the checklist: Disable the `remote` module
  231. // Logs a warning message about the remote module
  232. const warnAboutRemoteModuleWithRemoteContent = function (webPreferences?: Electron.WebPreferences) {
  233. if (!webPreferences || !webPreferences.enableRemoteModule || isLocalhost()) return;
  234. if (getIsRemoteProtocol()) {
  235. const warning = `This renderer process has "enableRemoteModule" enabled
  236. and attempted to load remote content from '${window.location}'. This
  237. exposes users of this app to unnecessary security risks.\n${moreInformation}`;
  238. console.warn('%cElectron Security Warning (enableRemoteModule)',
  239. 'font-weight: bold;', warning);
  240. }
  241. };
  242. // Currently missing since we can't easily programmatically check for it:
  243. // #16 Filter the `remote` module
  244. const logSecurityWarnings = function (
  245. webPreferences: Electron.WebPreferences | undefined, nodeIntegration: boolean
  246. ) {
  247. warnAboutNodeWithRemoteContent(nodeIntegration);
  248. warnAboutDisabledWebSecurity(webPreferences);
  249. warnAboutInsecureResources();
  250. warnAboutInsecureContentAllowed(webPreferences);
  251. warnAboutExperimentalFeatures(webPreferences);
  252. warnAboutEnableBlinkFeatures(webPreferences);
  253. warnAboutInsecureCSP();
  254. warnAboutAllowedPopups();
  255. if (BUILDFLAG(ENABLE_REMOTE_MODULE)) {
  256. warnAboutRemoteModuleWithRemoteContent(webPreferences);
  257. }
  258. };
  259. const getWebPreferences = async function () {
  260. try {
  261. return ipcRendererInternal.invoke<Electron.WebPreferences>(IPC_MESSAGES.BROWSER_GET_LAST_WEB_PREFERENCES);
  262. } catch (error) {
  263. console.warn(`getLastWebPreferences() failed: ${error}`);
  264. }
  265. };
  266. export function securityWarnings (nodeIntegration: boolean) {
  267. const loadHandler = async function () {
  268. if (shouldLogSecurityWarnings()) {
  269. const webPreferences = await getWebPreferences();
  270. logSecurityWarnings(webPreferences, nodeIntegration);
  271. }
  272. };
  273. window.addEventListener('load', loadHandler, { once: true });
  274. }