Friday, August 14, 2015

Lack of a typelib is not a security fault

Amazing discovery of the day: Microsoft Word pops up a security prompt for a perfectly good macro if a reference to a typelib can't be resolved.

Here's the scenario. I've built a managed DLL with a COM-visible component to be called from a MS Word macro. When managed DLLs are built in the usual way, they don't have a type library resource in them. Dynamic type discovery for created Automation objects is supported by the framework, but the regular typelib-in-file discovery would fail - for DLLs, it's looking for a custom resource of type "TYPELIB" with ID 1. That's why you can't open a managed DLL in OLEView and see the types.

You can, however, export a .TLB file from a managed DLL either with the "tlbexp" utility, or with "regasm". Both come with the .NET framework. Google it up.

Enter MS Word and Visual Basic for Applications aka VBA, it's tried and true macro language. In order to reference a component library during macro development, one needs the typelib registered; the "References" window of the VBA editor presents a list of typelibs. So on the dev machine, I have the typelib registered anyway.

The runtime environment is not the same as the dev environment, one would think. On the runtime machine, do you need the typelib registered, too? Trick question. In theory, no. Once CLSIDs/IIDs of all relevant objects are stored in the project, and enums are resolved to integers, it should be possible to call methods without a typelib. In fact, JavaScript has no problem with creating and invoking a component without a registered typelib. But not VBA.

When invoked on a machine where the managed coclass is registered, but the respective typelib is not, you get the following message:

"The macro cannot be found or has been disabled because of your Macro security settings."

It's really neither. It's a dependency to the macro that can't be found.

The remedy is obvious: use tlbexp to generate a typelib, ship it along with the DLL, register when installing. A TLB file can't register itself, so some manual registry fiddling would be in order.

No comments:

Post a Comment