1 / 83

Exploiting Perl on Windows with OLE/COM

The Fourth Annual Perl Conference, 2000. Exploiting Perl on Windows with OLE/COM. Roth Consulting. Tuesday, July 18, 2000. OLE: Object Linking and Embedding.

willis
Download Presentation

Exploiting Perl on Windows with OLE/COM

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Fourth Annual Perl Conference, 2000 Exploiting Perl on Windows with OLE/COM Roth Consulting Tuesday, July 18, 2000

  2. OLE: Object Linking and Embedding OLE is just the technology which allows an object (such as a spreadsheet) to be embedded (and linked) inside of another document (a word processor document). Exploiting Perl on Windows with OLE/COM

  3. Version 1 used DDE to communicate between applications. Version 2 uses COM instead of DDE (although DDE still exists for legacy reasons) Perl focuses more on COM than OLE. OLE: Object Linking and Embedding II Exploiting Perl on Windows with OLE/COM

  4. COM: Component Object Model Microsoft technology. Compare to CORBA COM is the protocol which allows OLE to work Rules of the road for programs to talk with each other Foundation of automation Permits non-related software components to work together Exploiting Perl on Windows with OLE/COM

  5. What is Automation? Automation is the ability to control an application from another process. Sometimes referred to as scripting. For example, Perl script starts Excel, loads spreadsheet, adds data, saves, quits Excel. Perl (and PerlScript) can make use of automation. Visual Basic for Applications (VBA) is a scripting language which makes use of automation. Windows Shell Host permits automation Exploiting Perl on Windows with OLE/COM

  6. Windows Shell Scripting • Referred to as WSH (pronounced as wish) • Comes with Windows 2000 and Windows ME • Allows plug-able shells such as PerlScript, VB, JavaScript Exploiting Perl on Windows with OLE/COM

  7. COM vs. OLE: A Fair Fight? They are totally different from each other OLE is like the ability to embed a letter within an envelope COM is like how to fold the letter, what size the envelope must be to fit the letter and other rules such as where to put the stamp and address on the letter (then where to take the letter) The Win32::OLE extension could (and maybe should) have been called Win32::COM Users may have confused it for an extension that manages serial ports Exploiting Perl on Windows with OLE/COM

  8. COM terms to know COM object: A chunk of memory which represents a particular COM interface COM collection: A group of similar COM objects controller process: Process or application which will play with COM objects. This process “controls” a COM server interface: Specific API that is built into a COM object automation: Ability to control COM objects without having to know how the COM object was designed Exploiting Perl on Windows with OLE/COM

  9. object model: The blueprints for a COM object COM server: The component that generates COM objects in-proc: In process; this COM server is typically a DLL that the controller process loads into it’s own memory space out-of-proc: Out of process; this COM server is a process separate from the controlling process. Could even be running on another machine COM terms to know II Exploiting Perl on Windows with OLE/COM

  10. COM Objects • A COM object is a set of functions and data • Functions • Called methods • Perform an action • Returns a result such as an numeric value, a string and array or another COM object • Example • Print() • GetAddress() Exploiting Perl on Windows with OLE/COM

  11. COM Objects II • Data • Called properties • Some properties are read/write so they can be both set and queried • Some properties are read-only so they can only be queried • Properties are really functions that are called get_PropertyName()/set_PropertyName() • Properties can be a numeric value, a string, an array or another COM object • Common example • Count • CurrentDate • Font Exploiting Perl on Windows with OLE/COM

  12. COM Collection Object • Special type of COM object which represents a bunch of other COM objects • COM Collection object is similar to a Perl array which contains a list of COM objects • A collection object typically has a name which is the plural of the type of COM object it represents • Fonts would represent a collection of Font COM objects • Documents would represent a collection of Document COM objects Exploiting Perl on Windows with OLE/COM

  13. What is an Object Model? Consider an object model to be the blueprint for the way an object oriented class works Just as a car manufacture creates a model of a car before designing it so does the author of a COM object The object model literally models the methods (functions) and members (variables) that a COM object has An object model defines a set of functions (methods) and variables (members or properties) Each set of functions are grouped together and is called an Interface Interfaces are API’s API => Application Programming Interface Exploiting Perl on Windows with OLE/COM

  14. What is an Object Model ? It’s the infrastructure, silly! All Active-X and OLE controls have such blueprints (or object models) The object model describes how another program can interact with a COM server. II Exploiting Perl on Windows with OLE/COM

  15. Interfaces, interfaces, interfaces! • COM defines interfaces into a program. • Each interface has an unique interface id (IID) to identify it from other interfaces: • {000209FF-0000-0000-C000-000000000046} • Aka GUID, CLSID, UUID, ProgID • Stored in Registry: HKEY_CLASSES_ROOT\CLSID • In theory an IID is so unique that no two interfaces will ever have the same ID; regardless of vendor, program or platform. Exploiting Perl on Windows with OLE/COM

  16. Each interface can have a class name in addition to an IID: “Word.Application” “Word.Document” Stored in Registry: HKEY_CLASSES_ROOT Interfaces, interfaces, interfaces II Exploiting Perl on Windows with OLE/COM

  17. COM’s Affair With The Registry • All COM interface info is stored in the Registry • Example (MS Word 2000): • HKEY_CLASSES_ROOT\Word.Application\CLSID Default = {000209FF-0000-0000-C000-000000000046} • HKEY_CLASSES_ROOT\CLSID\{000209FF-0000-0000-C000-000000000046} Exploiting Perl on Windows with OLE/COM

  18. Threading Models • Single Threading Model • Introduced in Win 16 (Windows 3.1) which did not support threads. • In NT 3.1 all COM interaction could only take place from one thread in a process. • Apartment Threading Model • AKA Single-Threaded Apartment Model (STA) • Supported by NT 3.5 and Windows 95. • Any thread could interact with COM objects. • A thread can only interact with COM objects created by the same thread. • Currently most common model. Exploiting Perl on Windows with OLE/COM

  19. Threading Models II • Free Threading Model • AKA Multi-Threaded Apartment Model (MTA) • NT 4.0, Windows 95 with DCOM service pack (installed with IE 4). • Any thread can interact with any COM object regardless of what thread created it. Exploiting Perl on Windows with OLE/COM

  20. Threading Models III • Neither client nor server needs to be aware of the other’s threading model (usually). • COM performs any necessary translations between clients and servers of different threading models. Exploiting Perl on Windows with OLE/COM

  21. Declaring A Threading Model • By default Win32::OLE uses the free-threaded (multi-thread apartment) model. • You can force Perl to use a particular threading model using the Win32::OLE->Initialize() function. • Must be called before any COM object is created. • Pass in one of the following values: • COINIT_APARTMENTTHREADED • Single threaded model • COINIT_OLEINITIALIZE • Single threaded model plus. Some COM servers that utilize specialized subsystems, such as Events, may require this. • COINIT_MULTITHREADED • Multi thread model (the default value) Exploiting Perl on Windows with OLE/COM

  22. Declaring A Threading Model II • Win32::OLE’s single threaded models create a hidden COM window with a message loop. • The message loop must be “spun” every so often. • Spin the message loop by calling: • Win32::OLE->SpinMessageLoop() • Failure to spin message loop may cause other processes to “pause” until another Win32::OLE call is made. • Some COM servers are more efficient if called using a particular threading model. • Events require a single threading model. Exploiting Perl on Windows with OLE/COM

  23. Events • Events are experimental and require that the Perl script run as in the single threaded apartment model. • This can be done by specifying the EVENTS import: use Win32::OLE qw( EVENTS ); • Events allow a COM object to callback into the Perl script when an event is fired. • Register the events of a COM object with the WithEvents() function: • Win32::OLE->WithEvents( $ComObj [, Handler [, Interface]] ); Exploiting Perl on Windows with OLE/COM

  24. Events II • The first parameter is a COM object that you want to monitor events for. • Second parameter is the event handler. This can either be a code reference or the name of a Perl module. • Code Reference: This code will be called each time an event is fired. • Module Name: A function by the same name of the event will be called in the specified module. If the function does not exist then the event is ignored. Exploiting Perl on Windows with OLE/COM

  25. Events III • Win32::OLE attempts to register itself with the default event interface for the specified COM object. • If the default event interface can not be determined then you must specify one as a string (the third parameter). • Example: Win32::OLE->WithEvents( $ComObj, \&MyEventHandler, ‘IMyEventInterfaceName’ ); This will cause all events from the IMyEventInterfaceName to call the MyEventHandler Perl subroutine. Exploiting Perl on Windows with OLE/COM

  26. Events IV • Example 2: Win32::OLE->WithEvents( $ComObj, \&Events ); sub Events { my( $Obj, $EventName, @Args ) = @_; print “Event $EventName occurred\n”; } • All parameters passed into the subroutine that are references are passed in as variants. You must use the Put() method to change the value. This is discussed later in the Variants section. Exploiting Perl on Windows with OLE/COM

  27. Events V • To disable events simply pass in the name of the object you desire to stop event processing: • Win32::OLE->WithEvents( $ComObj ); Exploiting Perl on Windows with OLE/COM

  28. General model of use • Basically there is a general model of use: 1) A typical controller process will request that a COM server generate a COM object. 2) The server is loaded or located, the request is submitted, a response is returned. 3) If request results in a valid COM object then controller process interacts with the object. 4) Destroy COM object. Exploiting Perl on Windows with OLE/COM

  29. What does all this mean? Let’s say we need to change the title and subject of a Microsoft Word document 1) Need to somehow run Word 2) Need to load up the document 3) Need to change the title and subject 4) Need to save the document 5) Need to quit Word Exploiting Perl on Windows with OLE/COM

  30. What does all this mean ? How would we implement such a system? 1) Request a Word application COM object 2) Call a function in the Word application COM object which loads a document. It returns a Word document COM object 3) Modify the Title and Subject properties from the Word document COM object 4) Call into the Word document COM object to save to disk 5) Destroy both the document and application COM objects II Exploiting Perl on Windows with OLE/COM

  31. Using Win32::OLE To use the Win32::OLE extension (thus be able to manipulate COM objects) you must first load the extension: use Win32::OLE; Exploiting Perl on Windows with OLE/COM

  32. Procuring a COM object • Request a new COM object $Obj = new Win32::OLE( “Word.Application” ); $Obj = Win32::OLE->new( “Word.Application” ); • Optional Second parameter is function to call when terminating the object • Some COM servers do not clean up after themselves such as Excel so you can pass in a second parameter which specifies a function to call when the object is destroyed $Obj = Win32::OLE->new( “Excel.Application”, \&TerminateExcelApp ); • Can be a string representing a method to call from within the COM object such as “Quit” Exploiting Perl on Windows with OLE/COM

  33. Procuring a COM object II • Requesting a COM object from a remote machine via DCOM • You must replace the first parameter with an anonymous array consisting of (in order): • The remote machine • The class of the COM object to be procured $Obj = Win32::OLE->new( [ “my.machine.com”, “Excel.Application” ], \&TerminateExcelApp ); Exploiting Perl on Windows with OLE/COM

  34. Procuring a COM object III • Request a COM object from the pool of already existing objects. • Usually works with non in-proc COM servers • Minimizes memory and processor overhead $Obj = Win32::OLE->GetActiveObject( “Word.Application” ); • Fails if the object does not already exist in memory Exploiting Perl on Windows with OLE/COM

  35. Procuring a COM object IV • Request a COM object from a file (aka a persistent COM object): $Obj = Win32::OLE->GetObject( ‘c:\mystuff.doc’ ); • Fails if: • file does not exist • unable to determine the file type • the application is not registered with the Registry • the application is not installed • something else goes drastically wrong Exploiting Perl on Windows with OLE/COM

  36. Procuring a COM object V • Some COM objects can not have multiple instances of itself therefore you need to use the GetActiveObject() function. • Many services such as IIS behave this way: $IIS = Win32::OLE->GetActiveObject( “IIS://localhost/” ); • Other COM objects that are allowed multiple instances (Excel, Word, Netscape, IE, etc) can be obtained via GetActiveObject() to conserve memory/processor overhead Exploiting Perl on Windows with OLE/COM

  37. Procuring a COM object VI A Trick: • If you use GetActiveObject() to conserve memory and the COM object can have multiple instances then upon the function failing you could request a new instance of the COM object: my $Obj;my $Class = “Word.Application”;if( ! $Obj = Win32::OLE->GetActiveObject( $Class ) ){ $Obj = Win32::OLE->new( $Class ) || die “Can not obtain a $Class object\n”;} Exploiting Perl on Windows with OLE/COM

  38. Persistent Objects • Many COM objects can save their state to a storage device. This is also known as serialization. • Persistent COM objects can be loaded back into memory. A process can then continue using the COM object. • The equivalent to using File/Open. Exploiting Perl on Windows with OLE/COM

  39. Persistent Objects II • Examples: • Word documents can save to DOC file. This is how a Word document COM object serializes. • A Photoshop COM object can export itself to a TIFF or GIF file. This is not serialization since reloading such a graphic file does not reconstitute the state of the Photoshop COM object. Saving the COM object as a .PSD file is serialization. Exploiting Perl on Windows with OLE/COM

  40. Persistent Objects III • Persistent COM objects loaded using the GetObject() function. $Obj = Win32::OLE->GetObject( "c:\\temp\\foo.doc" ); • Any COM object can be loaded in this way as long as an entry exists for it in the Registry. • COM tries to resolve the class of the persistent object. • Check current COM objects in memory for the object • Check the file’s classid (only in structured docs) • Compare registered document masks with file • Compare file extension with registered extensions Exploiting Perl on Windows with OLE/COM

  41. Querying a COM object’s type At this point we have a Word Application COM object (or we died and terminated the script)... • We can make sure the object is indeed a Word Application object with theWin32::OLE->QueryObjectType( $Obj ); • The function will return a text string representing the type of object: “Word_Application” • Usually this is only needed on objects that of an unknown type • If a function returns an unknown COM object use QueryObjectType()to determine its type Exploiting Perl on Windows with OLE/COM

  42. COM Object properties We can now mess around with the Word document COM objects properties... • One of a Word application COM objects many properties is the Visible property. This renders the Word application either visible or invisible to the user (by default it is invisible):$Word->{Visible} = 1; • Another property is a collection of documents that Word currently has open:$Docs = $Word->{Documents}; Exploiting Perl on Windows with OLE/COM

  43. COM Object properties II • Properties are really functions. Thus the following are equivalent: $Obj->{Visible};$Obj->Visible(); • Likewise to set a property, the following are equivalent: $Obj->{Visible} = 1;$Obj->Visible( 1 ); Exploiting Perl on Windows with OLE/COM

  44. COM Object properties Some properties are COM objects or COM collection objects: $Docs = $Obj->{Documents};$Doc1 = $Docs->Item( 1 );print $Doc1->{Path}; You can call a default method indirectly by passing in parameters. The above is equivalent to : $Doc1 = $Obj->Documents( 1 );print $Doc1->{Path}; NOTE: This makes the Documents property appear as a method, but it is only a property! III Exploiting Perl on Windows with OLE/COM

  45. Calling COM object methods In our Word example we have a COM object which represents the Microsoft Word program. Now we need to load a document The Word application COM object has an Open() method which will open and load a Word document The method returns a Word document COM object Method calls are made just like a call into a Perl object: $Doc = $Obj->Open( ‘c:\temp\myfile.doc’ ); Exploiting Perl on Windows with OLE/COM

  46. Calling COM object methods II • Some methods have optional parameters. This can pose a problem if you need to only specify some of them • Open() has the following syntax:Document* Open( FileName, [optional] ConfirmConversions, [optional] ReadOnly, [optional] AddToRecentFiles, [optional] PasswordDocument, [optional] PasswordTemplate, [optional] Revert, [optional] WritePasswordDocument, [optional] WritePasswordTemplate, [optional] Format ); Exploiting Perl on Windows with OLE/COM

  47. Calling COM object methods III • With optional parameters you can specify them by name, in any order • All required parameters must be placed first and in order • After the required parameters place all named parameters and values in an anonymous hash $Doc = $Word->Open( "c:\\temp\myfile.doc", { ReadOnly = > 1, AddToRecentFiles => 2 } ); Exploiting Perl on Windows with OLE/COM

  48. Chaining property and methods • You can chain multiple method calls into one line: $Path = $Word->{Documents}->Item( 1 )->{Path}; Becomes $Path = $Word->Documents( 1 )->{Path}; Exploiting Perl on Windows with OLE/COM

  49. Parameter placeholders • To skip a parameter in a method use undef $Obj->Blah( $Param1, undef, $Param2 ); Exploiting Perl on Windows with OLE/COM

  50. Destroying COM objects • When finished with a COM object it is best to destroy it using undef: undef $Doc;undef $Word; • Calling DESTROY() method: $Obj->DESTROY(); • When the COM object falls out of scope it will automatically be destroyed: sub Foo{ my $Obj = Win32::OLE->new( $Class ); $Obj->Blah();} Exploiting Perl on Windows with OLE/COM

More Related