- Javascript windows script block
- Синтаксис
- Описание
- Правила области видимости блока
- С использованием var
- С let и const
- Block Third-Party Scripts with a Few Lines of Javascript
- The context
- The goal
- Groundwork — Using a MutationObserver to observe script elements insertion
- Disable Windows Script Host (WSH) to block .VBS malware How to securely prevent .VBS files (VBScript) from being executed by disabling Windows Script Host in Windows 7, Windows 8 and Windows 10
- How to prevent VBS files from running
- What to do if a harmful .VBS file is executed
- Conclusion
- Блоки в JavaScript
- Как создать блок кода в JavaScript?
- Чем может быть полезен блок?
- Недостатки
- Popups and window methods
- Popup blocking
- window.open
- Example: a minimalistic window
- Accessing popup from window
- Accessing window from popup
- Comments
Javascript windows script block
Блок инструкций (или сложная инструкция в других языках) используется для группировки нуля или более инструкций. Блок отделяется парой фигурных скобок и может опционально быть поименован :
Синтаксис
Описание
Эта инструкция широко используется с операторами управления потоком (н., if. else , for , while ). Например:
Обратите внимание, что блок инструкций не заканчивается точкой с запятой.
Блок инструкций часто называется сложной (составной) инструкцией в других языках. Он позволяет вам использовать несколько операторов там, где JavaScript ожидает один оператор. Помещение инструкций в блок — это распространённая практика в JavaScript. Противоположное поведение — использование пустого оператора там, где никаких действий не нужно, а оператор требуется.
Правила области видимости блока
С использованием var
Переменные, объявленные через var , не имеют блочной области видимости. Переменные, введённые внутри блока, имеют областью видимости содержащую их функцию или скрипт, и последствия записи в них значения распространяются за границы, собственно, блока, в котором они объявлены. Другими словами, блок инструкций не вводит новую область видимости. Хотя «отдельно стоящие» блоки не являются нарушением синтаксиса, не стоит использовать отдельно стоящие блоки в JavaScript, потому что они не делают то, чего вы от них ожидаете, если вы ожидаете, что они будут себя вести аналогично блокам в C или Java. Например:
Тут выводится 2, потому что оператор var x внутри блока — в той же области видимости, что и оператор var x перед блоком. В C или Java подобный код вывел бы 1.
С let и const
Наоборот, идентификаторы, объявленные с помощью let и const имеют блочную область видимости:
x = 2 ограничено рамками области видимости блока, в котором оно было определено.
То же самое и для const :
Обратите внимание, что объявленная внутри блока const c = 2 не кидает SyntaxError: Identifier ‘c’ has already been declared ( идентификатор ‘c’ уже был объявлен ) потому что она может быть объявлена единожды внутри блока.
Block Third-Party Scripts with a Few Lines of Javascript
How to prevent third-party scripts from collecting data, sending analytics, and more without user consent.
Disclaimer: This article is about blocking scripts that are known to be safe, like analytics — meaning scripts from third party services that you include on your own. To block malicious unwanted third-party scripts or prevent Cross Site Scripting attacks you should always consider using other solutions, like adding a Content-Security-Policy header!
The context
Here at Snips we take privacy very seriously. Now that the GDPR is in effect, we have decided that our owned websites should never collect analytics on visiting users — unless they opt-in voluntarily.
Unfortunately, blocking third-party analytics can be a bit tricky. The problem is that these services are built to start immediately, and that they rely on small minified code snippets and script tags. You can try to modify the minified code yourself, but it gets a bit messy and hard to maintain, especially if you use several libraries.
So in order to handle this better — automatically — we created a small open source library called Yett ( interesting meanin g) that takes care of blocking the execution of analytics scripts. The library also allows you to later unblock these scripts, once a user has opted in.
To block scripts automatically might seem trivial — but it’s actually not that easy to block inline script tags!
So while digging into the subject, we found some technical subtleties that we thought would be nice to share with the community 😉.
The goal
Here are the requirements:
- The code must be loaded and executed synchronously, before any other script;
- At this point you have no clue how the final html will look, since the document has not yet been fully loaded;
- The blocked scripts must not be altered in any way (the goal is to prevent them from executing without touching their own code);
- We should be able to (eventually) unblock the scripts programmatically later on.
Below we list a few techniques that will actually work.
Groundwork — Using a MutationObserver to observe script elements insertion
MutationObserver comes in handy in this case, since you can register the observer on the document element ahead of time and be notified whenever DOM nodes get inserted, especially script nodes.
This alone won’t be sufficient of course, but it will be the first step towards our goal.
Disable Windows Script Host (WSH) to block .VBS malware How to securely prevent .VBS files (VBScript) from being executed by disabling Windows Script Host in Windows 7, Windows 8 and Windows 10
Windows Script Host (or WSH) (also known as Windows Scripting Host) is a scripting language shipped with all major Windows and Windows Server distributions since Windows 98. Scripts made with WSH (which usually have VBS extension, since they are primarily written in VBScript) are usually more powerful and versatile than batch files (.BAT extension) and, for a certain period, they have been used within most software installation processes to carry out various system configuration activities. WSH is a language-independent system, as it allows you to write code using different script engines including VBScript (default), JavaScript, Perl and more.
Unfortunately, the great potential and versatility of the Windows Script Host eventually led most hackers and black-hat developers to use it to develop malicious script-based computer viruses and malware. A WSH script can automate almost any operation normally performed by Windows and can be launched with a single click, thus making it the perfect tool to be used in the e-mail spamming / e-mail phishing campaigns, where multiple fake invoices are sent to a wide amount of users hoping that some of them would “double click” on them, thus activating the malware. For this reason, the mere presence of a .VBS file directly attached to an e-mail or “hidden” in a .ZIP archive should alarm the user and block any impulse to open it – or, better said, to have it run against your system.
The good practice of never opening e-mail attachments with unknown or potentially dangerous file extensions is well-known among IT experts since year, and – also as a result of the threat due to the widespread spread of Ransomware – it finally begins to spread even among less experienced users: it is no coincidence that paying close attention to attachments received via e-mail (especially “invoices” and administrative / accounting documents) is one of the main tricks recommended by all experts and computer security sites (we have talked about them here).
Despite this, unfortunately there are still many users who, either because of their habit of clicking or distraction, continue to make mistakes of this type, which have the unfortunate result of causing execution of VBS scripts on your machine. The fact that it is not an EXE file should not be misleading: it is, as mentioned, scripts that take advantage of an extremely powerful and therefore potentially very dangerous Windows feature, which deserves the maximum attention in terms of prevention – and, even more so, in the unlikely scenario of an erroneous execution.
How to prevent VBS files from running
Given the above picture, the system administrator can definitely consider disabling the Windows Script Host feature on all client and / or server PCs for security reasons: this is certainly a good practice especially if this language is not used intensively , which is true in most cases. The blocking of the WSH function will prevent the execution of files with .VBS extension, which will then become “harmless” text files on all PCs subjected to this treatment.
Here are the steps to be taken to disable the Windows Script Host (WSH) functionality for the current user (step 2-3) and / or for all users (steps 4-5):
- Press the WINDOWS + R keys, then type regedit to open the system registry in edit mode.
- Navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows Script Host\Settings\
- Create (if it doesn’t exist already) a new REG_DWORD key, call it Enabled and assign a value of 0 (zero) to it.
- Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Script Host\Settings\
- Create (if it doesn’t exist already) a new REG_DWORD key, call it Enabled and assign a value of 0 (zero) to it.
The VBS execution block should now be effective: in order to test it, create a test.vbs file on the desktop and try to run it. If everything has been done correctly, you should see the following warning message appear in a popup window:
Windows Script Host access is disabled on this machine. Contact your administrator for details.
Needless to say, to bring back such functionality you just need to delete the Enabled registry key (or change its value to 1).
What to do if a harmful .VBS file is executed
In the event of an “unexpected” execution of a potentially harmful .VBS file it is certainly advisable to carry out the following precautions:
- Make a copy of the VBS file (without executing it) and scan it online with a tool like VirusTotal: this will allow you to identify the threat, a fundamental prerequisite for any subsequent “erase” or “cleaning” strategy. Needless to say, take special care not to execute that file while handling it! To lower the risk – for you and other users – we strongly recommend renaming it with a harmless extension (eg .TXT or .BAK).
- Perform a system scan with an available AntiVirus tool (Bitdefender, Kaspersky, Avira, Avast, etc.). If you do not have paid versions or active subscriptions, you can download and install one of the many free versions made available by the developers of the aforementioned products. Just be sure to download the executables only from the official sites and update the antivirus database to the latest version before starting the scan.
- Perform an additionalsystem scan with the Trend Micro Anti-Threat Toolkit offline installer version (32bit or 64bit, depending on your system CPU architecture). This is the software that gave us best results for scanning and removing the most dangerous malware (rootkits, ransomware) distributed through .VBS scripts.
In addition to performing the above-mentioned countermeasures, it is advisable to take a general look at the system to identify suspicious files and/or potential threats, including: files with strange or wrong extensions, unknown text files, performance drops, application crashes, and anything else that could unveil ransomware activities being in progress. We also advise you to read the following posts and perform the suggested best practices:
Conclusion
That’s it for now: given the widespread distribution of VBS viruses and malwares attached to e-mails throughout the whole Europe, we can only recommend to preventively disable WSH to all system administrators, unless explicitly required by specific scenarios.
Блоки в JavaScript
В сей поздний час мою голову посетила одна очень странная мысль. Не долго думая, я решил написать коротенький пост по этому поводу.
Что же, сил и времени на написание второй статьи о WebRTC у меня до сих пор нет, а на пост-заметку я решил все же найти мозговые и временные ресурсы.
Суть мысли, или даже вопроса — почему никто (встречавшийся мне) не использует отдельные блоки кода (помимо тех, которые используются с выражениями if else и т.д.) в своих JavaScript приложениях?
Как создать блок кода в JavaScript?
Легко! <> в начале выражения считается блоком (а не объектом). Например:
Чем может быть полезен блок?
В JavaScript блоки кода не создают свою область видимости (скоуп), поэтому будем искать полезность в чем-то другом.
Самое элементарное применение — разделение логических частей кода. Да еще какое! Блок можно использовать с меткой.
Толку с нее в данной ситуации мало. С таким успехом можно заменить метку на комментарий, но ведь как красиво смотрится.
Но остается проблема в ограниченности метки.
Опытный и не очень программист может сказать — все логичные блоки / части кода лучше выносить в отдельные функции. Но попробую сразу же не согласиться. Давайте рассмотрим пример из жизни?
Допустим, есть у меня Backbone приложение. При инициализации каждой view я должен совершать стандартные действия: подписываться на глобальные события, подписываться на изменения модели или коллекции и т.д.
Почему-то я не хочу выносить это в отдельные функции. Я привык, что в методе initialize я могу увидеть сразу подписку на все нужные события.
Так почему же мне не разделить эту массу кода на отдельные логические блоки кода в рамках одного метода и скоупа?
Недостатки
Даже не знаю, какие могут быть недостатки у такого способа разделения кода. Быть может, есть вероятность того, что можно запутаться — перепутать блок кода с объектом. Но у меня такой наклонности не возникает.
Вывод: использовать такие блоки — дело выбора каждого. Комментарии, блоки — кому как нравится. Но хотелось бы все же найти интересное применение таким блокам.
Popups and window methods
A popup window is one of the oldest methods to show additional document to user.
Basically, you just run:
…And it will open a new window with given URL. Most modern browsers are configured to open url in new tabs instead of separate windows.
Popups exist from really ancient times. The initial idea was to show another content without closing the main window. As of now, there are other ways to do that: we can load content dynamically with fetch and show it in a dynamically generated
Also, popups are tricky on mobile devices, that don’t show multiple windows simultaneously.
Still, there are tasks where popups are still used, e.g. for OAuth authorization (login with Google/Facebook/…), because:
- A popup is a separate window which has its own independent JavaScript environment. So opening a popup from a third-party, non-trusted site is safe.
- It’s very easy to open a popup.
- A popup can navigate (change URL) and send messages to the opener window.
Popup blocking
In the past, evil sites abused popups a lot. A bad page could open tons of popup windows with ads. So now most browsers try to block popups and protect the user.
Most browsers block popups if they are called outside of user-triggered event handlers like onclick .
This way users are somewhat protected from unwanted popups, but the functionality is not disabled totally.
What if the popup opens from onclick , but after setTimeout ? That’s a bit tricky.
The popup opens in Chrome, but gets blocked in Firefox.
…If we decrease the delay, the popup works in Firefox too:
The difference is that Firefox treats a timeout of 2000ms or less are acceptable, but after it – removes the “trust”, assuming that now it’s “outside of the user action”. So the first one is blocked, and the second one is not.
window.open
The syntax to open a popup is: window.open(url, name, params) :
url An URL to load into the new window. name A name of the new window. Each window has a window.name , and here we can specify which window to use for the popup. If there’s already a window with such name – the given URL opens in it, otherwise a new window is opened. params The configuration string for the new window. It contains settings, delimited by a comma. There must be no spaces in params, for instance: width=200,height=100 .
Settings for params :
- Position:
- left/top (numeric) – coordinates of the window top-left corner on the screen. There is a limitation: a new window cannot be positioned offscreen.
- width/height (numeric) – width and height of a new window. There is a limit on minimal width/height, so it’s impossible to create an invisible window.
- Window features:
- menubar (yes/no) – shows or hides the browser menu on the new window.
- toolbar (yes/no) – shows or hides the browser navigation bar (back, forward, reload etc) on the new window.
- location (yes/no) – shows or hides the URL field in the new window. FF and IE don’t allow to hide it by default.
- status (yes/no) – shows or hides the status bar. Again, most browsers force it to show.
- resizable (yes/no) – allows to disable the resize for the new window. Not recommended.
- scrollbars (yes/no) – allows to disable the scrollbars for the new window. Not recommended.
There is also a number of less supported browser-specific features, which are usually not used. Check window.open in MDN for examples.
Example: a minimalistic window
Let’s open a window with minimal set of features, just to see which of them browser allows to disable:
Here most “window features” are disabled and window is positioned offscreen. Run it and see what really happens. Most browsers “fix” odd things like zero width/height and offscreen left/top . For instance, Chrome open such a window with full width/height, so that it occupies the full screen.
Let’s add normal positioning options and reasonable width , height , left , top coordinates:
Most browsers show the example above as required.
Rules for omitted settings:
- If there is no 3rd argument in the open call, or it is empty, then the default window parameters are used.
- If there is a string of params, but some yes/no features are omitted, then the omitted features assumed to have no value. So if you specify params, make sure you explicitly set all required features to yes.
- If there is no left/top in params, then the browser tries to open a new window near the last opened window.
- If there is no width/height , then the new window will be the same size as the last opened.
Accessing popup from window
The open call returns a reference to the new window. It can be used to manipulate it’s properties, change location and even more.
In this example, we generate popup content from JavaScript:
And here we modify the contents after loading:
Please note: immediately after window.open , the new window isn’t loaded yet. That’s demonstrated by alert in line (*) . So we wait for onload to modify it. We could also use DOMContentLoaded handler for newWin.document .
Windows may freely access content of each other only if they come from the same origin (the same protocol://domain:port).
Otherwise, e.g. if the main window is from site.com , and the popup from gmail.com , that’s impossible for user safety reasons. For the details, see chapter Cross-window communication.
Accessing window from popup
A popup may access the “opener” window as well using window.opener reference. It is null for all windows except popups.
If you run the code below, it replaces the opener (current) window content with “Test”:
let newWin = window.open(«about:blank», «hello», «width=200,height=200»); newWin.document.write( «
Comments
- If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
- If you can’t understand something in the article – please elaborate.
- To insert few words of code, use the tag, for several lines – wrap them in
tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)