security-warnings.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 as any)._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 resources = window.performance
  94. .getEntriesByType('resource')
  95. .filter(({ name }) => /^(http|ftp):/gi.test(name || ''))
  96. .filter(({ name }) => new URL(name).hostname !== 'localhost')
  97. .map(({ name }) => `- ${name}`)
  98. .join('\n');
  99. if (!resources || resources.length === 0) {
  100. return;
  101. }
  102. const warning = `This renderer process loads resources using insecure
  103. protocols. This exposes users of this app to unnecessary security risks.
  104. Consider loading the following resources over HTTPS or FTPS. \n${resources}
  105. \n${moreInformation}`;
  106. console.warn('%cElectron Security Warning (Insecure Resources)',
  107. 'font-weight: bold;', warning);
  108. };
  109. /**
  110. * #2 on the checklist: Disable the Node.js integration in all renderers that
  111. * display remote content
  112. *
  113. * Logs a warning message about Node integration.
  114. */
  115. const warnAboutNodeWithRemoteContent = function (nodeIntegration: boolean) {
  116. if (!nodeIntegration || isLocalhost()) return;
  117. if (getIsRemoteProtocol()) {
  118. const warning = `This renderer process has Node.js integration enabled
  119. and attempted to load remote content from '${window.location}'. This
  120. exposes users of this app to severe security risks.\n${moreInformation}`;
  121. console.warn('%cElectron Security Warning (Node.js Integration with Remote Content)',
  122. 'font-weight: bold;', warning);
  123. }
  124. };
  125. // Currently missing since it has ramifications and is still experimental:
  126. // #3 Enable context isolation in all renderers that display remote content
  127. //
  128. // Currently missing since we can't easily programmatically check for those cases:
  129. // #4 Use ses.setPermissionRequestHandler() in all sessions that load remote content
  130. /**
  131. * #5 on the checklist: Do not disable websecurity
  132. *
  133. * Logs a warning message about disabled webSecurity.
  134. */
  135. const warnAboutDisabledWebSecurity = function (webPreferences?: Electron.WebPreferences) {
  136. if (!webPreferences || webPreferences.webSecurity !== false) return;
  137. const warning = `This renderer process has "webSecurity" disabled. This
  138. exposes users of this app to severe security risks.\n${moreInformation}`;
  139. console.warn('%cElectron Security Warning (Disabled webSecurity)',
  140. 'font-weight: bold;', warning);
  141. };
  142. /**
  143. * #6 on the checklist: Define a Content-Security-Policy and use restrictive
  144. * rules (i.e. script-src 'self')
  145. *
  146. * Logs a warning message about unset or insecure CSP
  147. */
  148. const warnAboutInsecureCSP = function () {
  149. isUnsafeEvalEnabled().then((enabled) => {
  150. if (!enabled) return;
  151. const warning = `This renderer process has either no Content Security
  152. Policy set or a policy with "unsafe-eval" enabled. This exposes users of
  153. this app to unnecessary security risks.\n${moreInformation}`;
  154. console.warn('%cElectron Security Warning (Insecure Content-Security-Policy)',
  155. 'font-weight: bold;', warning);
  156. }).catch(() => {});
  157. };
  158. /**
  159. * #7 on the checklist: Do not set allowRunningInsecureContent to true
  160. *
  161. * Logs a warning message about disabled webSecurity.
  162. */
  163. const warnAboutInsecureContentAllowed = function (webPreferences?: Electron.WebPreferences) {
  164. if (!webPreferences || !webPreferences.allowRunningInsecureContent) return;
  165. const warning = `This renderer process has "allowRunningInsecureContent"
  166. enabled. This exposes users of this app to severe security risks.\n
  167. ${moreInformation}`;
  168. console.warn('%cElectron Security Warning (allowRunningInsecureContent)',
  169. 'font-weight: bold;', warning);
  170. };
  171. /**
  172. * #8 on the checklist: Do not enable experimental features
  173. *
  174. * Logs a warning message about experimental features.
  175. */
  176. const warnAboutExperimentalFeatures = function (webPreferences?: Electron.WebPreferences) {
  177. if (!webPreferences || (!webPreferences.experimentalFeatures)) {
  178. return;
  179. }
  180. const warning = `This renderer process has "experimentalFeatures" enabled.
  181. This exposes users of this app to some security risk. If you do not need
  182. this feature, you should disable it.\n${moreInformation}`;
  183. console.warn('%cElectron Security Warning (experimentalFeatures)',
  184. 'font-weight: bold;', warning);
  185. };
  186. /**
  187. * #9 on the checklist: Do not use enableBlinkFeatures
  188. *
  189. * Logs a warning message about enableBlinkFeatures
  190. */
  191. const warnAboutEnableBlinkFeatures = function (webPreferences?: Electron.WebPreferences) {
  192. if (!webPreferences ||
  193. !Object.prototype.hasOwnProperty.call(webPreferences, 'enableBlinkFeatures') ||
  194. (webPreferences.enableBlinkFeatures != null && webPreferences.enableBlinkFeatures.length === 0)) {
  195. return;
  196. }
  197. const warning = `This renderer process has additional "enableBlinkFeatures"
  198. enabled. This exposes users of this app to some security risk. If you do not
  199. need this feature, you should disable it.\n${moreInformation}`;
  200. console.warn('%cElectron Security Warning (enableBlinkFeatures)',
  201. 'font-weight: bold;', warning);
  202. };
  203. /**
  204. * #10 on the checklist: Do Not Use allowpopups
  205. *
  206. * Logs a warning message about allowed popups
  207. */
  208. const warnAboutAllowedPopups = function () {
  209. if (document && document.querySelectorAll) {
  210. const domElements = document.querySelectorAll('[allowpopups]');
  211. if (!domElements || domElements.length === 0) {
  212. return;
  213. }
  214. const warning = `A <webview> has "allowpopups" set to true. This exposes
  215. users of this app to some security risk, since popups are just
  216. BrowserWindows. If you do not need this feature, you should disable it.\n
  217. ${moreInformation}`;
  218. console.warn('%cElectron Security Warning (allowpopups)',
  219. 'font-weight: bold;', warning);
  220. }
  221. };
  222. // Currently missing since we can't easily programmatically check for it:
  223. // #11 Verify WebView Options Before Creation
  224. // #12 Disable or limit navigation
  225. // #13 Disable or limit creation of new windows
  226. // #14 Do not use `openExternal` with untrusted content
  227. // #15 on the checklist: Disable the `remote` module
  228. // Logs a warning message about the remote module
  229. const warnAboutRemoteModuleWithRemoteContent = function (webPreferences?: Electron.WebPreferences) {
  230. if (!webPreferences || isLocalhost()) return;
  231. const remoteModuleEnabled = webPreferences.enableRemoteModule != null ? !!webPreferences.enableRemoteModule : false;
  232. if (!remoteModuleEnabled) return;
  233. if (getIsRemoteProtocol()) {
  234. const warning = `This renderer process has "enableRemoteModule" enabled
  235. and attempted to load remote content from '${window.location}'. This
  236. exposes users of this app to unnecessary security risks.\n${moreInformation}`;
  237. console.warn('%cElectron Security Warning (enableRemoteModule)',
  238. 'font-weight: bold;', warning);
  239. }
  240. };
  241. // Currently missing since we can't easily programmatically check for it:
  242. // #16 Filter the `remote` module
  243. const logSecurityWarnings = function (
  244. webPreferences: Electron.WebPreferences | undefined, nodeIntegration: boolean
  245. ) {
  246. warnAboutNodeWithRemoteContent(nodeIntegration);
  247. warnAboutDisabledWebSecurity(webPreferences);
  248. warnAboutInsecureResources();
  249. warnAboutInsecureContentAllowed(webPreferences);
  250. warnAboutExperimentalFeatures(webPreferences);
  251. warnAboutEnableBlinkFeatures(webPreferences);
  252. warnAboutInsecureCSP();
  253. warnAboutAllowedPopups();
  254. if (BUILDFLAG(ENABLE_REMOTE_MODULE)) {
  255. warnAboutRemoteModuleWithRemoteContent(webPreferences);
  256. }
  257. };
  258. const getWebPreferences = async function () {
  259. try {
  260. return ipcRendererInternal.invoke<Electron.WebPreferences>(IPC_MESSAGES.BROWSER_GET_LAST_WEB_PREFERENCES);
  261. } catch (error) {
  262. console.warn(`getLastWebPreferences() failed: ${error}`);
  263. }
  264. };
  265. export function securityWarnings (nodeIntegration: boolean) {
  266. const loadHandler = async function () {
  267. if (shouldLogSecurityWarnings()) {
  268. const webPreferences = await getWebPreferences();
  269. logSecurityWarnings(webPreferences, nodeIntegration);
  270. }
  271. };
  272. window.addEventListener('load', loadHandler, { once: true });
  273. }