security-warnings.ts 10 KB

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