Unviewable vba project for excel

Время на прочтение
5 мин

Количество просмотров 25K

Всем привет! Я обычный пользователь MS Excel. Не являющийся профессиональным программистом, но накопивший достаточно опыта, для установки и обхода защиты проектов VBA.

Дисклеймер:

В данной статье рассмотрены виды защиты проектов VBA, от несанкционированного доступа. Их сильные и слабые стороны – ранжирование.

Цель статьи показать слабые и сильные стороны каждого вида защиты проекта VBA в MS Office.

Демонстрация разработанных инструментов, в надстройке Macro Tools VBA, для снятия и установки той или иной защиты. 

Все инструменты реализованы стандартными средствами VBA, без использования дополнительных библиотек. 

Главная панель Надстройки Macro Tools VBA

Первый вид защиты — Обычный пароль

Время на снятие: мгновенно

Недостаток: быстрый доступ к запароленному модулю VBA

Стандартный инструмент (В среде VBE: панель Tools -> VBAProject Properties -> Protection). 

Самая легко снимающаяся защита. В интернете легко находится код, для снятия данной защиты. 

Данную защиту можно снять следующим инструментом:

Второй вид защиты — Project is Unviewable

Время на снятие:  от 10 до 15 мин (в ручную)

Недостаток: доступ к исходному коду модуля VBA

Один из самых распространённых видов защит.  Встречается в 95% файлах с защитой модуля VBA. При попытке открыть проект, открывается диалоговое окно, с  сообщением:  Project is Unviewable.


Большинство пользователей Excel, не могут снять данную защиту, так как она имеет множество вариации и нюансов, для ее снятие нужно иметь представление о внутренней структуре файла Excel.

Основан, данный вид защиты, на изменение ключей:

CMG=«4A488FCC54D054D054D054D0»

DPB=«0B09CE0F8E108E108E»

GC=«CCCE09520B120C120CED»

в файле vbaProject.bin

Кратко, как создается данная защита

Для создания данной защиты нужно, разархивировать файл Excel. Перейти в архиве в папку xl, открыть файл vbaProject.bin,  в конце файла находятся наши ключи, редактируем значения ключей на пусто, сохраняем файл. Переводим наш архив, обратно в файл Excel. Готово! 

Это самый простой вариант данной защиты, но существует множество модификаций.

Алгоритм снятия защиты Project is Unviewable.

1)  Разархивируем подопытный файл, переходим в файл  …xl_relsworkbook.xml.rels

2)      В файле workbook.xml.rels  ищем строку, содержащую слово  vbaProject, обычно имеет следующий вид:  />. В этой строке нас интересует ключ Target,иего значение. Значение является название файла, в котором находится проект VBA. Иногда, защищающий меняет значения ключа на printerSettings.bin.Получается маскировка файла с проектом VBA  под другой файл.

3)      Открываем на редактирование файл, указанный в  ключе Target, ищем в файле ключи  CMG, DPB, GC. И меняем в их названиях любую букву на любую другую, например: CMC, DPC, CC. При поиске нужно быть аккуратным, так как защищающий может поместить  в проект форму,  подписью повторяющую один из ключей, например такую: DPB=«0B09CE0F8E108E108E». При ее изменении проект VBA, будет удален из книги Excel.  Сохраняем и закрываем файл.

4)      Переводим архив обратно в файл Excel.

5)      Запускаем приложение Excel, выполняем следующее: в Центре управления безопасностью -> Параметры макросов  -> Отключить все макросы без уведомления. Перезапускаем Excel. Данная операция нужна, для блокировки защиты, которую иногда ставят авторы макросов. Данная защита реализована следующим образом. В модуле VBA «ЭтаКнига», создается процедуры, реагирующие на события открытия книги или закрытия книги. Эти события обычно проверяют, наличие пароля на проект VBA, запрет сохранения и прочее.

6)      Открываем файл. Если все правильно сделано то, Excel, будет ругаться на не правильные ключи, которые мы отредактировали, в пункте 3. Жмем, да, пока данные сообщения не закончатся и диалоговое окно закроется. 

      Если данное сообщение не появляется то, вы отредактировали не файл который содержит проект VBA.

7)      Открываем проект VBA. После всего, проект VBA должен быть доступен.

8)       Но иногда защита не снимается, тогда нужно сохранить файл, проверить, что он действительно сохранился! И проделать повторно операции с 1 по 7. Обычно так происходит когда в файле workbook.xml.rels в ключе Target  установлено printerSettings.bin.При сохранение,  Excel  исправляет это на значение на vbaProject.bin

Данную защиту можно установить и снять следующим инструментом:

Третий вид защиты — Hidden  Module, скрытые модули VBA

Время на снятие:  от 15 до 20 мин (нужен редактор OLE — объектов, Structured Storage Viewer, например.

Недостаток: доступ к коду модуля VBA

Менее распространенный вид  защиты обычно встречается в комбинации с защитой Project is Unviewable. При установке данной защиты модуль VBA не отображается в проекте книги Excel. О его существовании можно узнать, проанализировав код VBA (что требует время!) или открыть файл Excel в программе  OpenOffice  или  LibreOffice (так же можно смотреть код при защите Project is Unviewable, но данный способ не дает возможность получить рабочий файл, без пароля). 

Просмотр кода VBA в  LibreOffice

Кратко, как создается данная защита

Для создания данной защиты нужно отредактировать файл  с проектом VBA — vbaProject.bin  или printerSettings.bin,в зависимости от настроек в файле …xl_relsworkbook.xml.rels. В конце файла удаляются строки вида: Module1=32, 32, 635, 330, Z.  С нужными названиями модулей.

Для снятия данной защиты нужно в файле vbaProject.bin — восстановить удаленные записи модулей.

Данную защиту можно установить следующим инструментом.

Четвертый вид защиты — Обфускация кода

Время на снятие:  неизвестно, зависит от объема кода и пере использования частей кода

Обфусцированный код VBA

Недостаток:  необходимость тестирование файла после обфускации, на работоспособность

Крайне редкий вид защиты, основанный на изменении исходного кода VBA, в не удобочитаемый вид для человека. Удаляются все комментарии, форматирование кода, переименовываются названия всех переменных,  процедур, функций, модулей и прочего. Злоумышленнику никогда не удастся восстановить первоначальный вид кода, и потребует достаточно много времени для, его восстановления в удобно читаемый вид для человека.  

Для де-обфускации кода нужно иметь  время, специализированное ПО.

Данную защиту можно установить следующим инструментом.

Пятый вид защиты — Перенос кода в dll

Время на снятие:  неизвестно, зависит от языка программирования и квалификации

Недостаток:  необходимости в дополнительном  файле dll

Один из самых редких видов защиты. Основная идея перенос основного кода в отдельную библиотеку dll, написанную на любом другом языке программирования. Не распространённость данный вид защиты получил по следующей причине,  необходимости за файлом Excel, «таскать» дополнительный файл, dll.

Для получения доступа к коду dll, нужно обладать специальными знаниями.

Заключение

В заключении хочу выделить бесполезность защит:  Project is Unviewable и Hidden  Module которые, по существу ни отчего не защищают. Позволяют просматривать код VBA, без изменения исходного  файла, в таких программах как OpenOffice  или  LibreOffice. Так и снимаются без особых проблем.

Project is Unviewable+ VBA for Excel, Powerpoint, Word, Visio, Project, AutoCAD, Access

The Unviewable plus project is an attempt to once and for all protect your intellectual VBA property without external file dependencies from the lion’s share of hacking tricks. The current methods to password protect your code are either very weak and can easily be hacked with numerous detailed articles published all over the internet or quite complex.

What if you didn’t need to worry about others modifying or even stealing your code? With the Unviewable+ project, this thought is now a reality.

With support from the Excel community’s finest, we hired a world-class developer to code our program in a Delphi application. Our Indiegogo campaign contributors have helped us exceed our goal and add several additional features in the program. The Unviewable+ application was shaped by our supporters for our supporters.

An Unviewable plus VBA project cannot be defeated by numerous password hacking software, such as this password removal application. The unviewable plus VBA application is not based on the old shared workbook trick, which is easy to defeat and cannot be used, if there are Tables in your workbook or add-in. 

The software is an executable that will turn your add-in (or workbook) into an add-in (or workbook) with an unviewable VBA project. Besides Excel macro-enabled files, the unviewable+ application can also protect macro-enabled PowerPoint presentations and Word documents.

Testimonials From The MS-Office Community’s Finest

I can’t sing enough praises of Unviewable+. It is the solution I spent years trying to find and eventually gave up until it was created last year. I use it to protect all the add-ins I sell on my website and it has the most security features out of any software I have been able to find. Like others have alluded to, you are never going to find a product that is 100% hack-proof (I think everyone in the world is still looking for that kind of security for a digital product). But in the world of Excel/VBA, the Unviewable+ application is going to confuse 99.9% of the people who start getting curious about what’s behind the scenes…and I like those odds! Chris Newman, Excel MVP, USA

Picture

I’m impressed with Unviewable+, both for the ease and flexibility of use and also the security it brings to my PowerPoint add-in code. Because it can protect PPA/PPAM files, I don’t have to worry about accidentally making my source files unviewable, which makes for a simple, direct and trouble-free workflow. As I release new add-ins and update the existing ones, I plan to use Unviewable+  on all of them. Thanks for a great product! Steve Rindsberg, PowerPoint MVP, USA

Unviewable​+​ is a dream come true for anyone who has been working in VBA development for any length of time. Virtually every client I’ve ever had has asked about protecting their intellectual property and I’ve had to reluctantly tell them that unless they use a COM add-in, their IP is relatively easy to get at.  Now, however, with Unviewable​+​ I can offer my clients robust and 99% secure products that they can then turn around and resell with confidence. Thank you, Petros, for a great product. I recommend this product for any VBA developer, from novice to long-term pro. ​​It is well worth the price! Tim Jeffryes, TJs Tools LLC, USA

Tim Jeffryes, TJs Tools LLC Testimonial for Project is Unviewable+ VBA for Excel, PowerPoint & Word

Andrew Engwirda, Testimonial for Project is Unviewable+ VBA for Excel, PowerPoint & Word

Unviewable+ is something that has been missing from Excel from the very start — dependable security. We were all been resigned to the fact that our intellectual property could be stolen quickly and easily for so very long. Now, everything has changed. A solution that works, Unviewable+ VBA improves source code security in Office and let’s you sleep at night!
Andrew Engwirda, commercial programmer & former Excel MVP, Japan

Unviewable+ is a must have tool to keep your VBA code secure. The software is stable, has an intuitive user interface and is packed with features. Hats off, keep up the good work guys!
Istvan VOZAR, ExcelDashboardSchool.com, Hungary

Picture

DocTools

I was lucky to find Unviewable+ shortly after it was released and I have been a happy user ever since. I use it to protect the Word add-ins I provide via my website, wordaddins.com. As with many other VBA developers, I had been looking for a way to protect my add-ins but without success – until Unviewable+ was released. The software is very easy to use and it takes only a moment to protect a file. I highly recommend Unviewable+ to any developer who wants enhanced VBA protection.
Lene Fredborg, Word MVP – Office Apps & Services, Denmark

How The Delphi Application Looks

Project is Unviewable+ VBA application

What The End User Sees

Project is unviewable prompt in Spanish

«Project is Unviewable» error message while opening a locked Visual Basic for Applications project (VBA) in Microsoft Office Excel, PowerPoint or Word (Spanish version also shown)

Unviewable+ Explained

The UnviewablePlus.exe is a portable Delphi application [it is not an Excel add-in]. It will not install anything on your PC. The EXE file is the windows application that will make macro-enabled Office Excel, PowerPoint and Word files unviewable in VBE. It can be used on client sites by developers and by IT admins on user PCs to lock unviewable VBA projects in macro-enabled files. 

The Unviewable+ application was developed to meet the following requirements:

  • Unviewable+ maintains the normal file extension of your workbooks, presentations, templates and add-ins.
  • Unviewable+ protected files will not trigger antivirus software to block opening your workbook, presentation, template or add-in.
  • VBA code can still be read by malware analysis scanners and antivirus tools.
  • VBA projects still behave like macro workbooks (in regards to security warnings and trusted locations).
  • The application does not travel with workbooks, presentations, templates or addins.
  • The application is not intrusive. No DLLs are loaded on target computers. The protection scheme doesn’t depend on executabel code.
  • There is no performance penalty. VBA executes as fast as in unlocked files!
  • Unviewable+ files can be opened in both 32 and 64 bit versions of Office and Office for Mac.

Protection Types

Excel unviewable plus VBA

Unviewable+ feature matrix

HIDDEN MODULES

Standard modules will be hidden (classes and userforms will still be visible). The VBA project won’t be locked, so any module type can be added and saved. Procedures can be called from hidden modules, but VBA code cannot be read from them, even when using the VBA extensibility library. 

This setting could be useful, if you are trying to protect your code in standard modules, without alerting the end-user that a VBA protection scheme has been deployed within the macro-enabled file. Please ensure that there is at least one visible module (standard, class or userform) in the VBA project.

UNVIEWABLE PASSWORD PROTECTED VBA PROJECT

Unviewable password protected VBA projects are less secure than the equivalent locked projects, as recovery information has to be maintained within the file.

Unviewable password protected projects can be made visible and re-locked, if required. This setting is provided for developers who need to maintain their code, without having to publish updates to replace locked files. The project cannot be restored by the application, if the unviewable password is lost.

UNVIEWABLE LOCKED VBA PROJECT

Permanent protection. Please ensure that you have a backup copy of your source file before locking a VBA project with this setting. Locked VBA projects cannot be made visible by the application.

Protection Levels

VBADIFF COMPATIBLE
VbaDiff is a must-have source control and code differencing application. This least secure level is being offered to allow developers to work with VbaDiff and unviewable VBA projects.

SIMPLE
Similar protection as in the previous level, but VBA projects cannot be read by the VbaDiff application.

MEDIUM STRENGTH
Ideal setting for beta VBA applications or projects with poor error-handling. Also a good option, if the Ultimate protection restrictions conflict with your setup (see below)

ULTIMATE
The most secure unviewable setting. However, it comes with some restrictions:

  • The Ultimate setting is not available for Microsoft Word VBA. Please use the ‘Medium strength’ setting or lower.
  • ‘Option Private Module’ statement is ignored in projects protected with the Ultimate setting. All objects in a VBA project will be visible in VBIDE object browser. Please use the ‘Medium strength’ setting or lower, if you do not want to expose all objects in your project.
  • Public macros can neither be run using a shortcut key (e.g. Ctrl-<key>), nor are visible in the macro name box (on the developer tab) when using the Ultimate setting.
    • Declare macro shortcuts at runtime using the .Onkey method. Download demos here.
    • Use a ribbon UI to launch macros from addins.
    • Shortcut workaround for workbooks: Define shortcut keys by having hidden ActiveX command buttons in a worksheet with Accelerator keys set. Launch macros with ALT-<key> combinations.
  • The Debug button is enabled in untrapped runtime errors and it should not be clicked by Excel 2007-2010 users, as Excel may crash. Your code will still be unviewable in VBE, even if the Debug button is clicked. It is best practice to distribute locked files with robust error handling for optimal user experience.

Picture

Options

BACKUP COPY

The application can create a source backup copy, if the backup option is checked. The unviewable protection can only be removed from unviewable password protected files. Locked VBA projects cannot be restored. It’s up to software publishers to maintain their own source code versions of locked VBA projects. We believe that it’s worth it for the added security. Sorry, we do not offer code recovery services. It is your responsibility to design and execute a robust backup strategy.

DATE/BUILD STAMP

A hidden date-time stamp will be added when the file is locked.

COPYRIGHT NOTICE

The ‘licensed to’ text will be used to add a hidden copyright stamp inside the file

MULTI-LAYER PROTECTION (MLP)

Please ensure that this option is checked when locking Open XML files (4-letter extension). MLP is not applicable to the XLS/XLA legacy file formats. Use Microsoft Office Subject Interface Packages for digitally signing VBA Projects along with SignTool, instead of the VB editor menu if MLP is enabled.

Command Line Support

Unviewable+ can be used from the command line for batch file processing from version 2.74 beta onwards. Click image below to zoom-in.

Picture

Known Issues

Picture

Picture

[1] It has been reported that the early build of Excel 2013 shown is

not

compatible with the Ultimate protection level and stamping options. Later Excel 2013 versions can open Ultimate unviewable+ locked files without any issues.

Please use ‘Medium strength‘ protection and uncheck both date/build stamp and copyright notice, if this Office version is being used by your software users.

[2] VBA code stored in worksheets (document modules) can be read from workbooks with unprotected structure (Review> Protect Workbook), even if the VBA project is password locked or unviewable. Read the workaround here


[3] The Visual Basic Editor does not support Unicode. Instead, it uses a legacy Windows technology called ‘Code Pages’ to provide support for non-ASCII characters.

The Ultimate protection level and stamping options are

not

compatible with some Code Pages. Please use ‘Medium strength‘ protection and uncheck both date,  build stamp and copyright notice, if the system locale for non-unicode programs is set to certain languages (e.g. Chinese, Czech, Polish, Russian, Slovak etc). However, Ultimate protection can be used with several non-English Code Pages.

Picture

Translation Credits

Chinese: ExcelHome.net
Danish: John Rosenblad
Dutch: Ed Lutjeboer
French: Fabrice Rimlinger
German: Mourad Louha
Portuguese-Brasil: Felipe Gualberto
Spanish: Elvis Zem
Swedish: Jörgen Moller

Picture

French article

Unviewable+ VBA for Excel languages

Language files are not required, if the application is used with its default menus in English. Language files (.lng) that are not used, can be deleted from unviewable+ application folder.

For example, if you are using unviewable+ in French, delete all .lng files, except 

unviewable.fr.lng 

Language files can be discovered by the application in subfolders as well, so please ensure that unused lng files are deleted

Unviewable+ VBA Is Proudly Sponsored By

Picture

Frequently Asked Questions

Question: I have been using a converter tool to secure my Excel workbook and VBA, by placing it within an executable shell, which bypasses the Excel VBA security settings allowing it to open up on any PC. It works fine, but as it is in an executable format, it can be flagged up as a potential virus. What is the format of your protected workbook please. Will it flag up any possible warnings from antivirus monitoring software?
Reply: Unviewable+ protected Excel files will not trigger antivirus software to block opening your workbook or add-in. Unviewable+ maintains the normal file extension of your workbook or add-in files.

Question: Will anti-virus/malware programs balk at the files because they contain unviewable code?
Reply: The unviewable state in Visual Basic Editor is a

built-in Office feature used in shared workbooks. Although VBA code is unviewable in VBE, it can still be read by malware analysis tools.

Question: Will the projects still ‘behave’ like macro workbooks (in regards to security warnings and trusted locations)?
Reply: Unviewable+ maintains the normal file extension of your workbook or add-in files. Our tests have confirmed that unviewable+ protected files behave like any other macro-enabled Office file in regards to security warnings and trusted locations.

Question: Is the Unviewable+ application strictly for Excel or will it work with VBA in other Office programs? Does it work with PowerPoint? 
Reply: Yes, the Unviewable+ application is available for Excel, PowerPoint & Word. Site & Global licenses offer support for Microsoft Access, Project, Visio, Autodesk AutoCAD VBA and CorelDRAW (Enterprise features).

Question: Is it okay to lock a VBA project that has been password protected in Excel?
Reply: When you password protect a project as unviewable, your VBE password (Excel’s) will be retained. So after removing the unviewable password (don’t lose it!) you will have to unlock your project in Excel as you would do normally. If the Excel password is lost or forgotten, then use one of the published password hacking techniques or any Office password cracking software, such as this.

Question: Is any visible information stored by the Unviewable+ application in locked workbooks or addins? 
Reply: No, only an optional Date/Build or Copyright stamp may be stored hidden inside the vbaProject.bin

Question: Is there any performance difference between password protected and unviewable+ projects? 
Reply:

None! Unviewable+ modifies the behaviour of Visual Basic editor, not the way VBA code runs.

Question: Is there any conflict between Unviewable+ and Office Addins? Will Solver.xlam load correctly?
Reply: There is no conflict with Office add-ins or Solver, as the application does not travel with your files.

Question: Is «Project is Unviewable» shown in locked workbooks opened in Office/Excel 2016 for Mac? 
Reply: Yes

Question: In which Office versions actively supported by Microsoft can the file converted by the Unviewable+ application compatible be opened with: 
Reply: Office 2007 (32 bit), 2010, 2013, 2016 (32/64 bit)

A tell-tale sign from Microsoft that Office 16 VBA IDE is fully backwards compatible:

«…Macros and Add-ins—We’re not making any changes to Macros or Add-ins in this release. It’s rare that “no changes” is a something we’d want to highlight, but we think it’s worth celebrating the consistency in the programming model across releases. We understand how important this is and we’re committed to a high level of compatibility as we continue to innovate….» Read the full article here: Announcing the Office 2016 preview

Campaign 180% Funded In Indiegogo

Picture

Read the funding discussion about Unviewable+ in Linkedin

Picture

Visit Unviewable+ in Indiegogo

Download Locked Samples

Ribbon Commander download

Samples are intended for personal evaluation only. File redistribution or malicious uses are strongly prohibited!

VBA Tools Add-in

The ‘VBA Tools’ Excel add-in is bundled for free with any standalone perpetual license. The add-in offers an elementary VBA obfuscator, which can remove redundant information from files destined for publication, such as code indentation, blank lines & comments. Obfuscate your VBA code, before locking VBA projects with Unviewable+. There are a couple of more features:

  • Export your VBA code to a text file for use with code diff tools.
  • Turn On popular Library References. If you have ever pulled out your hair trying to find the PowerPoint VBA reference in that list of hundreds of references inside the VBE, your frustration will be gone. No more will you need to go through that hassle!
  • Toggle the VBE background between a white (default) and black color scheme.
  • Show or hide PowerPoint Add-in VBA code inside the Visual Basic Editor
  • Launch the Unviewable+ Delphi application from inside the add-in for convenience.

VBA Tools Excel Add-in

VBA-Tools is a companion add-in to the Unviewable+ application

Unviewable+ VBA Academy

Unviewable+ VBA Academy

All Unviewable+ customers are automatically enrolled in our VBA Academy to help you increase development productivity, improve the security features of your VBA applications, defend against known attacks and new threats. These tips are emailed privately to clients only. Please feel free to send us your feedback or VBA tips that may benefit all Unviewable+ users.

Customer Privacy

Customer Privacy

In a technological age where privacy is scarce, our software goes against the flow.  The Unviewable+ application and the companion VBA Tools add-in do not require a connection to the internet to ease any concerns from customers who are sensitive about their privacy and/or corporate espionage. This applies to perpetual licenses only.

The protection scheme is passive. No stealthy code runs in the background when locked Office files are opened. The Unviewable+ portable executable file (.exe) is signed with a digital certificate from Comodo CA or Sectigo and will not install anything on your computer under any circumstances.

​For more information, please read the software’s manual or download our notes on customer privacy.

Enterprise Features

Unviewable+ VBA Enterprise menu

Site and Global licenses offer protection support for:

  • Microsoft Access (simple locked level only)
  • Microsoft Project (without multi-layer protection)
  • Microsoft Visio
  • Autodesk AutoCAD (without multi-layer protection, up-to Medium level)
  • CorelDRAW (without multi-layer protection, up-to Medium level)

Customers who purchase Site or Global licenses will receive the obfuscation module (lite) in VBA source code (.bas), since add-ins are not available for Access, Project, Visio, AutoCAD & CorelDRAW. Please contact us for more details about Enterprise licenses.

Unviewable+ License Grid

Buy Perpetual Licenses

Unviewable+ VBA (written in Delphi) is available as a standalone portable windows application with perpetual licenses as shown below, which can be branded with your logo (instead of ours) in the About form. Branded applications are intended for enterprise internal use only [not for resale].

Picture

Let your brand be the hero: Unviewable+ application with customer logo in About form [NOT FOR RESALE]

Developer is the person who develops (and/or) maintains and finally protects macro-enabled Office files using the Unviewable+ application. Locked files can be distributed to any user without restrictions or royalties perpetually. Developers are

not

licensed to merely lock files developed by colleagues. A single site or global license is required for such use.

1 Site license: A software licensing agreement that grants the purchaser permission to use the software on a network and/or in several computers at a particular site or facility, with an unlimited number of software developers. The software is

not

licensed for use with files created by developers, who are not employed by the licensee.

Picture

1 Developer license US$100

Picture

1 Site license US$250 (unlimited developers)

Picture

Multi-site, Global license US$600

Picture

Global license & Source Code Price-upon-request

Buy Unviewable+ VBA

Please click button to visit our e-commerce store in FastSpring

Terms

We take your VBA security seriously and strive to improve our software. All application software updates are FREE for customers who buy standalone perpetual licenses.

Since the Delphi windows application is portable,

all sales are final

. No refunds are being offered for perpetual licenses and source code. 

The software is not licensed for use as a security service to the general public. 

Publisher: Esoteric Consulting Ltd, United Kingdom (Spreadsheet1.com)
Product URL
: http://www.spreadsheet1.com/unviewable-vba-project-app-for-excel.html
Software category: Microsoft Office 2007 or later
Operating system: Windows 7 or later
Date first published: March 2015
Latest version: 2.78 beta

Version Change Log

2.73 — Stable beta version
2.74 — Command line support added
2.78 — Support for Access, Project, Visio and AutoCAD files [Enterprise licenses only]

Other VBA Security Products

Защитить проект VBA

Зачастую, при создании проекта на VBA в Excel, хочется его надежно защитить (особенно, если он какой-то крупный). В первую очередь, это нужно для того, чтобы никто не «украл» Ваши личные интеллектуальные разработки, либо для того, чтобы никто не мог внести какие-либо изменения в код. В данной статье как раз будет рассказано о некоторых способах, с помощью которых можно защитить проект VBA: от самых простейших, до более сложных.

Установка пароля на проект VBA

Первый и наиболее простой способ защитить проект VBA — стандартная установка пароля. Для установки пароля, в открытом редакторе VBA, необходимо нажать «Tools» — «VBA Project Properties» и перейти на вкладку «Protection», как показано на скриншоте ниже:

Защитить проект VBA: свойства проекта

Далее, необходимо ввести пароль и подтвердить его. Если нужно закрыть проект от просмотра кода — установите галочку в поле «Lock project for viewing». И все, пароль установлен. Теперь, в следующий раз, когда вы зайдете в редактор VBA и попытаетесь открыть VBA-проект — необходимо будет ввести пароль:

Защитить проект VBA: стандартный пароль

Данный способ поможет защитить проект VBA только от простых пользователей: если очень захотеть, пароль можно легко взломать. Такая защита не является надежной.

Обфускация кода

Обфускация — это изменение (запутывание) кода программы с целью затруднения его восприятия и понимания. В случае с кодом VBA — удаление отступов, удаление комментариев и переименовывание переменных или даже самих процедур.

Например, имеется простейший код, который сравнивает две переменные и выводит сообщение:

Sub sravnenie()
Dim a As Double 
Dim b As Double
a = 50 'первая переменная
b = 30 'вторая переменная
If (a >= b) Then 'сравнение
    MsgBox a & " больше или равно " & b, "Сравнение"
Else
    MsgBox a & " меньше " & b, "Сравнение"
End If
End Sub

После обфускации получится следующий код:

Sub q3294ac481200c9f62b6a7dac981cea19()
Dim b17fea5c0191a5bc3c2640b8f16b14e98 As Double
Dim ea06f6764676da2a53039a8c582369215 As Double
b17fea5c0191a5bc3c2640b8f16b14e98 = 50
ea06f6764676da2a53039a8c582369215 = 30
If (b17fea5c0191a5bc3c2640b8f16b14e98 >= ea06f6764676da2a53039a8c582369215) Then
MsgBox b17fea5c0191a5bc3c2640b8f16b14e98 & " больше или равно " & ea06f6764676da2a53039a8c582369215, "Сравнение"
Else
MsgBox b17fea5c0191a5bc3c2640b8f16b14e98 & " меньше " & ea06f6764676da2a53039a8c582369215, "Сравнение"
End If
End Sub

Да, разобраться в нем можно, времени уйдет на это чуть больше, но стоит отметить, что здесь всего лишь 11 строк кода. Если строк будет в разы больше, то разобраться будет очень проблематично, код будет максимально сложным для восприятия.

Для того, чтобы защитить проект VBA с помощью обфускации, можно воспользоваться готовыми инструментами:

  • Сайт для обфускации кода VBA
  • Инструмент для обфускации на Python

Обфускация — эффективный способ защиты VBA (и не только VBA). Его также можно использовать с первым способом: если пароль взломают, то с анализом и интерпретацией кода придется довольно долго потрудиться.

Важно! При обфускации кода проекта не забывайте делать резервную копию исходного кода, иначе, при внесении изменений в проект, придется работать с уже измененной версией, что будет довольно проблематично (а уж без комментариев, которые вы наверняка оставляли, тем более).

Изменение бинарного файла (Project is unviewable)

Еще один эффективный способ защитить проект VBA — небольшое изменение бинарного кода самого файла Excel. Что для этого нужно?

Сначала, необходимо сохранить исходный файл в формате .xlsb (рекомендуется именно этот формат), либо в формате .xlam, если это надстройка. После чего, необходимо сменить расширение файла на .zip и открыть его через архиватор (Winrar или 7-Zip). Затем, нужно зайти в папку «xl» и найти там файл vbaProject.bin. Файл необходимо куда-нибудь перенести/скопировать, например, на рабочий стол.

Защитить проект VBA: vbaProject.bin

Далее, нужно открыть vbaProject.bin через текстовый редактор Notepad++ (именно через него, так как через стандартный блокнот не получится) и найти там строчки, содержащие «CMG», «DPB» и «GC» (они находятся почти в самом низу). Все символы, находящиеся в кавычках после них, необходимо заменить на символ «F», как это сделано на примере ниже:

Защитить проект VBA: бинарный файл

Сохраняем файл vbaProject.bin, закрываем, переносим его обратно в архив в ту же папку «xl». Меняем обратно расширение с .zip на .xlsb или .xlam (в зависимости от того, в каком расширении файл был сохранен), и все, готово. Теперь, при попытке просмотреть/изменить модули нашего проекта, мы будем видеть сообщение «Project is unviewable»:

Защитить проект VBA: Project is unviewable

Данный способ поможет эффективнее защитить проект VBA от взлома более опытными пользователями. Но даже эту защиту можно взломать, если очень захотеть.

Важно! Не забудьте сделать резервную копию исходного файла, в противном случае, вы больше не сможете просматривать и редактировать свой код.

Создание надстройки .dll

Еще один из способов, с помощью которого можно защитить проект VBA — создание .dll надстройки. Про данный способ я расскажу вкратце, так как сам я .dll-надстройки не создавал. Суть заключается в том, что код ваших макросов вы пишете на другом языке программирования, например на C++, а затем компилируете его в .dll или .exe файл, который затем подключается к Excel. Исходный код из скомпилированного файла извлечь крайне трудно.

Интересную тему, с которой можно начать небольшое погружение в создание .dll-надстройки, можно прочитать на форуме PlanetaExcel.

Использование стороннего софта

В интернете продается различный софт для защиты проекта, в котором могут сочетаться все перечисленные выше функции: обфускация, изменение бинарного кода и еще какие-либо дополнительные настройки, ограничивающие доступ к исходному коду. Вот некоторых из них:

  • XLS Padlock (139€)
  • VBASH (80$)
  • Unviewable+ (100$ и выше, в зависимости от лицензии)
  • VbaCompiler (299$ стандартная лицензия) — создает .dll-файл (используется язык C)

Стоит отметить, что файлы, защищенные с помощью VBASH и самой дешевой версией Unviewable можно довольно быстро взломать. Вероятно, стоимость этого программного обеспечения «слегка» завышена и, возможно, следует пользоваться другими способами. А вот с помощью VbaCompiler защитить проект VBA можно очень надежно, так как он автоматически создает .dll-надстройку с использованием языка C. Но стоимость данного ПО довольно высокая.

Приобретать данный софт или нет — целиком и полностью ваше решение, но следует понимать, что вклад в защиту проекта должен быть финансово оправдан. Для защиты проекта от обычных пользователей достаточно использовать те методы, о которых я написал в этой статье. Нужно помнить о том, что не существует стопроцентной защиты от взлома: если человек реально захочет взломать ваш проект, он его взломает.

You may think it’s easy – just open VB Editor (ALT + F11),  go to Tools > VBAProject Properties…, switch to Protection tab, check Lock project for viewing, set a password, hit OK and save your file. But is your code really safe now? No, it’s not. There are several methods or third-party software that can crack this protection in seconds. I have described two of them on my blog – here and here.

So is there a way to lock your VBA project for good? Yes, there is. For example Unviewable+ or Secure++ – both created by Petros Chatzipantazis from Spreadsheet1.com. How do they work? Usually when you try to expend protected VBA project you will be prompted for a password.

vba01

If you can see above window it means the file can be cracked. Using mentioned software you can make your project unviewable. Then, trying to expend VBA project, you should see below message.

vba02

This operation is irreversible so keeping the editable copy of your file is recommended! Now there is no way to crack VBA project and see what’s inside.

But software offered by Petros is quite expensive – you need to pay $100 for a single developer license. But you can have the same effect for free. How? Just follow the steps described below.

You will need two freeware programs:

  1. WinRAR
  2. Notepad++

Download and install both of them. Now make a copy of the Excel file you want to make unviewable (remember – once you do it there is no way back!) and change it’s extension to .zip. Right-click on the archive and go to Open with > WinRAR archiver – you should see below window.

vba03

Now double-click on xl folder and extract vbaProject.bin file. To do this you can either select the file and hit Extract To button or simply drag & drop the file onto your Desktop. Once you have it extracted, right-click on the file, go to Open with > Choose default program… – new window should appear. Hit Browse… – now navigate to the directory where Notepad++ is installed (“C:/Program Files (x86)/Notepad++/” in my case), choose notepad++.exe and hit Open.

vba03a

If you want to make Notepad++ a default program for all *.bin files check Always use the selected program to open this kind of file. Then hit OK.

vba04

vbaProject.bin file should now open in Notepad++. It will look somewhat like this.

vba05

Now scroll down until you find the section with CMG=, DPB= and GC=.

vba06

For Excel workbook files (tested on .xlsb) you can replace the CMG, DPB and GC strings between parenthesis with any even number of “F”s greater than or equal to the number of characters in the original strings and for Add-in files (tested on .xlam) you need to replace them with the exact same number of “F”s as the number of characters in the original strings.

vba07

Now Save the changes (CTRL + S), close Notepad++ and drag & drop the file back in the archive to replace the original with the updated one. When new window appears just hit OK.

vba08

You can be sure that the file was updated when it’s Modified date is changed.

vba09

Now you can close WinRAR and change the extension from .zip back to original Excel file extension (.xlsb, .xlam, etc.). Now when you open the file, go to VB Editor and try to expand the VBA project. Instead of password prompt you should see a message saying that the Project is unviewable.

vba02

You project is now uncrackable. No one (even you) can see or edit the VBA code.

Hope that helps!

Project is unviewable — как разлочить

tanver

Дата: Среда, 09.03.2016, 18:02 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 59


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Добрый день.

Прошу подсказать, что делать.
Неожиданно при попытке открыть проект стало открываться сообщение «Project is unviewable», как разлочить.

Пользователь (т.е. Я) защит и паролей не устанавливал.
Заранее благодарю за помощь.

Татьяна.

PS файл несколько раз пере сохранялся. Не открывается код только в 2 последних версиях.


Благодарю. С уважением Татьяна В.

 

Ответить

Manyasha

Дата: Среда, 09.03.2016, 18:17 |
Сообщение № 2

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

tanver, скорее всего у Вас файл находится в общем доступе.
Рецензирование — Доступ к книге — снимите галку «Разрешить изменять файл нескольким пользователям одновременно».


ЯД: 410013299366744 WM: R193491431804

 

Ответить

Udik

Дата: Среда, 09.03.2016, 18:19 |
Сообщение № 3

Группа: Друзья

Ранг: Старожил

Сообщений: 1588


Репутация:

192

±

Замечаний:
0% ±


Excel 2016 х 64

Попробуйте для начала открыть опенофисом, он парольную защиту не замечает (вдруг она сама поставилась). B) .


вот вам барабан
яд 41001231307558 wm R419131876897
udik1968@gmail.com

 

Ответить

tanver

Дата: Среда, 09.03.2016, 18:22 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 59


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Общего доступа галочки нет.


Благодарю. С уважением Татьяна В.

 

Ответить

tanver

Дата: Среда, 09.03.2016, 18:34 |
Сообщение № 5

Группа: Пользователи

Ранг: Участник

Сообщений: 59


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

openoffice -надо скачать. Попробую. Спасибо

 

Ответить

Manyasha

Дата: Среда, 09.03.2016, 18:50 |
Сообщение № 6

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

tanver, попробуйте поставить, а затем снять общий доступ.
Вдруг поможет.


ЯД: 410013299366744 WM: R193491431804

 

Ответить

tanver

Дата: Четверг, 10.03.2016, 10:40 |
Сообщение № 7

Группа: Пользователи

Ранг: Участник

Сообщений: 59


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Добрый день, всем.

попробовали вчера назначить и отменить общий доступ. Не помогло.
и открывать в openoffice. Не смогли открыть даже сам файл.

Но сегодня доступ к VBA Project открылся сам, как ни в чем не бывало, наверно был какой-то сбой в файле или компьютере.

Всем спасибо!
Татьяна

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Unusual words word list
  • United say the word
  • Underline the correct word people hunts hunt wild animals
  • Typing russian in word
  • Underline options in word