security-warnings.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
  2. import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
  3. const { mainFrame: webFrame } = process._linkedBinding('electron_renderer_web_frame');
  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 = () => {
  70. return webFrame._isEvalAllowed();
  71. };
  72. const moreInformation = `\nFor more information and help, consult
  73. https://electronjs.org/docs/tutorial/security.\nThis warning will not show up
  74. once the app is packaged.`;
  75. /**
  76. * #1 Only load secure content
  77. *
  78. * Checks the loaded resources on the current page and logs a
  79. * message about all resources loaded over HTTP or FTP.
  80. */
  81. const warnAboutInsecureResources = function () {
  82. if (!window || !window.performance || !window.performance.getEntriesByType) {
  83. return;
  84. }
  85. const isLocal = (url: URL): boolean =>
  86. ['localhost', '127.0.0.1', '[::1]', ''].includes(url.hostname);
  87. const isInsecure = (url: URL): boolean =>
  88. ['http:', 'ftp:'].includes(url.protocol) && !isLocal(url);
  89. const resources = window.performance
  90. .getEntriesByType('resource')
  91. .filter(({ name }) => isInsecure(new URL(name)))
  92. .map(({ name }) => `- ${name}`)
  93. .join('\n');
  94. if (!resources || resources.length === 0) {
  95. return;
  96. }
  97. const warning = `This renderer process loads resources using insecure
  98. protocols. This exposes users of this app to unnecessary security risks.
  99. Consider loading the following resources over HTTPS or FTPS. \n${resources}
  100. \n${moreInformation}`;
  101. console.warn('%cElectron Security Warning (Insecure Resources)',
  102. 'font-weight: bold;', warning);
  103. };
  104. /**
  105. * #2 on the checklist: Disable the Node.js integration in all renderers that
  106. * display remote content
  107. *
  108. * Logs a warning message about Node integration.
  109. */
  110. const warnAboutNodeWithRemoteContent = function (nodeIntegration: boolean) {
  111. if (!nodeIntegration || isLocalhost()) return;
  112. if (getIsRemoteProtocol()) {
  113. const warning = `This renderer process has Node.js integration enabled
  114. and attempted to load remote content from '${window.location}'. This
  115. exposes users of this app to severe security risks.\n${moreInformation}`;
  116. console.warn('%cElectron Security Warning (Node.js Integration with Remote Content)',
  117. 'font-weight: bold;', warning);
  118. }
  119. };
  120. // Currently missing since it has ramifications and is still experimental:
  121. // #3 Enable context isolation in all renderers that display remote content
  122. //
  123. // Currently missing since we can't easily programmatically check for those cases:
  124. // #4 Use ses.setPermissionRequestHandler() in all sessions that load remote content
  125. /**
  126. * #5 on the checklist: Do not disable websecurity
  127. *
  128. * Logs a warning message about disabled webSecurity.
  129. */
  130. const warnAboutDisabledWebSecurity = function (webPreferences?: Electron.WebPreferences) {
  131. if (!webPreferences || webPreferences.webSecurity !== false) return;
  132. const warning = `This renderer process has "webSecurity" disabled. This
  133. exposes users of this app to severe security risks.\n${moreInformation}`;
  134. console.warn('%cElectron Security Warning (Disabled webSecurity)',
  135. 'font-weight: bold;', warning);
  136. };
  137. /**
  138. * #6 on the checklist: Define a Content-Security-Policy and use restrictive
  139. * rules (i.e. script-src 'self')
  140. *
  141. * Logs a warning message about unset or insecure CSP
  142. */
  143. const warnAboutInsecureCSP = function () {
  144. if (!isUnsafeEvalEnabled()) return;
  145. const warning = `This renderer process has either no Content Security
  146. Policy set or a policy with "unsafe-eval" enabled. This exposes users of
  147. this app to unnecessary security risks.\n${moreInformation}`;
  148. console.warn('%cElectron Security Warning (Insecure Content-Security-Policy)',
  149. 'font-weight: bold;', warning);
  150. };
  151. /**
  152. * #7 on the checklist: Do not set allowRunningInsecureContent to true
  153. *
  154. * Logs a warning message about disabled webSecurity.
  155. */
  156. const warnAboutInsecureContentAllowed = function (webPreferences?: Electron.WebPreferences) {
  157. if (!webPreferences || !webPreferences.allowRunningInsecureContent) return;
  158. const warning = `This renderer process has "allowRunningInsecureContent"
  159. enabled. This exposes users of this app to severe security risks.\n
  160. ${moreInformation}`;
  161. console.warn('%cElectron Security Warning (allowRunningInsecureContent)',
  162. 'font-weight: bold;', warning);
  163. };
  164. /**
  165. * #8 on the checklist: Do not enable experimental features
  166. *
  167. * Logs a warning message about experimental features.
  168. */
  169. const warnAboutExperimentalFeatures = function (webPreferences?: Electron.WebPreferences) {
  170. if (!webPreferences || (!webPreferences.experimentalFeatures)) {
  171. return;
  172. }
  173. const warning = `This renderer process has "experimentalFeatures" enabled.
  174. This exposes users of this app to some security risk. If you do not need
  175. this feature, you should disable it.\n${moreInformation}`;
  176. console.warn('%cElectron Security Warning (experimentalFeatures)',
  177. 'font-weight: bold;', warning);
  178. };
  179. /**
  180. * #9 on the checklist: Do not use enableBlinkFeatures
  181. *
  182. * Logs a warning message about enableBlinkFeatures
  183. */
  184. const warnAboutEnableBlinkFeatures = function (webPreferences?: Electron.WebPreferences) {
  185. if (!webPreferences ||
  186. !Object.hasOwn(webPreferences, 'enableBlinkFeatures') ||
  187. (webPreferences.enableBlinkFeatures != null && webPreferences.enableBlinkFeatures.length === 0)) {
  188. return;
  189. }
  190. const warning = `This renderer process has additional "enableBlinkFeatures"
  191. enabled. This exposes users of this app to some security risk. If you do not
  192. need this feature, you should disable it.\n${moreInformation}`;
  193. console.warn('%cElectron Security Warning (enableBlinkFeatures)',
  194. 'font-weight: bold;', warning);
  195. };
  196. /**
  197. * #10 on the checklist: Do Not Use allowpopups
  198. *
  199. * Logs a warning message about allowed popups
  200. */
  201. const warnAboutAllowedPopups = function () {
  202. if (document && document.querySelectorAll) {
  203. const domElements = document.querySelectorAll('[allowpopups]');
  204. if (!domElements || domElements.length === 0) {
  205. return;
  206. }
  207. const warning = `A <webview> has "allowpopups" set to true. This exposes
  208. users of this app to some security risk, since popups are just
  209. BrowserWindows. If you do not need this feature, you should disable it.\n
  210. ${moreInformation}`;
  211. console.warn('%cElectron Security Warning (allowpopups)',
  212. 'font-weight: bold;', warning);
  213. }
  214. };
  215. // Currently missing since we can't easily programmatically check for it:
  216. // #11 Verify WebView Options Before Creation
  217. // #12 Disable or limit navigation
  218. // #13 Disable or limit creation of new windows
  219. // #14 Do not use `openExternal` with untrusted content
  220. const logSecurityWarnings = function (
  221. webPreferences: Electron.WebPreferences | undefined, nodeIntegration: boolean
  222. ) {
  223. warnAboutNodeWithRemoteContent(nodeIntegration);
  224. warnAboutDisabledWebSecurity(webPreferences);
  225. warnAboutInsecureResources();
  226. warnAboutInsecureContentAllowed(webPreferences);
  227. warnAboutExperimentalFeatures(webPreferences);
  228. warnAboutEnableBlinkFeatures(webPreferences);
  229. warnAboutInsecureCSP();
  230. warnAboutAllowedPopups();
  231. };
  232. const getWebPreferences = async function () {
  233. try {
  234. return ipcRendererInternal.invoke<Electron.WebPreferences>(IPC_MESSAGES.BROWSER_GET_LAST_WEB_PREFERENCES);
  235. } catch (error) {
  236. console.warn(`getLastWebPreferences() failed: ${error}`);
  237. }
  238. };
  239. export function securityWarnings (nodeIntegration: boolean) {
  240. const loadHandler = async function () {
  241. if (shouldLogSecurityWarnings()) {
  242. const webPreferences = await getWebPreferences();
  243. logSecurityWarnings(webPreferences, nodeIntegration);
  244. }
  245. };
  246. window.addEventListener('load', loadHandler, { once: true });
  247. }