Bypassing Restricted Execution Policy in Code or in Script

by oising 10. February 2012 23:34

Many businesses are averse to moving away from a restricted execution policy because they don't really understand it. As Microsoft will tell you, It's not a security boundary - it's just an extra hoop to jump through so you don't shoot yourself in the foot by running something you shouldn’t. If you want to run ps1 scripts in your own application, simply host your own Runspace and use the base authorization manager which pays no heed to system execution policy, even if it’s controlled by group policy and immune to powershell –bypass and set-executiopolicy:

Bypassing in Code

InitialSessionState initial = InitialSessionState.CreateDefault(); 
 
// Replace PSAuthorizationManager with a null manager
// which ignores execution policy 
initial.AuthorizationManager = new 
      System.Management.Automation.AuthorizationManager("MyShellId"); 
 
// Extract psm1 from resource, save locally 
// ... 
 
// load my extracted module with my commands 
initial.ImportPSModule(new[] { <path_to_psm1> }); 
 
// open runspace 
Runspace runspace = RunspaceFactory.CreateRunspace(initial); 
runspace.Open(); 
 
RunspaceInvoke invoker = new RunspaceInvoke(runspace); 
 
// execute a command from my module 
Collection<PSObject> results = invoker.Invoke("my-command"); 
 
// or run a ps1 script     
Collection<PSObject> results = invoker.Invoke(@"c:\program files\myapp\my.ps1");

By using this null authorization manager, execution policy is completed ignored. Remember - this is not some "hack" because execution policy is something for protecting users against themselves. It's not for protecting against malicious third parties, like some kind of script firewall. Whatever could be put in a script, could be run by hand in a dozen different ways using invoke-expression, and even file based scripts can be executed this way: invoke-expression (get-content .\foo.ps1).

Bypassing in Script

Now this is a little more hackish because it involves manipulating powershell.exe internals at runtime. This is a useful one-liner (if you can memorise it) when you find yourself in one of those clients who has GPO controlled execution policy. It’s pushing it for a one-liner, I know, but hey:

function Disable-ExecutionPolicy {
    ($ctx = $executioncontext.gettype().getfield(
        "_context","nonpublic,instance").getvalue(
            $executioncontext)).gettype().getfield(
                "_authorizationManager","nonpublic,instance").setvalue(
        $ctx, (new-object System.Management.Automation.AuthorizationManager
                  "Microsoft.PowerShell"))
}

This function will swap out the powershell host’s AuthorizationManager implementation (PSAuthorizationManager) with the null, policy-ignoring version. Execution policy will be effectively unrestricted, regardless of enterprise, machine or user level attempts to set it to restricted. This is an in-memory bypass only – when powershell.exe is closed and restarted, it’s back to business (or lack thereof.)

Have fun!

Tags:

.NET | Developer | PowerShell 2.0 | PowerShell 3.0 | PowerShell | Reflection

PowerShell – Module Installation Best Practices

by oising 16. December 2011 11:47

I’m seeing a few errant companies have their installers throw their modules into ${env:systemroot}\WindowsPowerShell\1.0\Modules but this is not the right place. The only things that should go there are core operating system modules from Microsoft. So, where should you install them?

How to: Install a module for all users

  1. Create the folder ${env:programfiles}\YourProduct\PowerShell\Modules\
  2. Place your module (or modules) under this folder
  3. Add the folder from step 1 to the system scoped environment variable PSModulePath; consider embedding %ProgramFiles% to keep the environment string as short as possible
  4. Profit.

How to: Install a module for the current user

  1. Test for, and create if necessary the folder which is the result of this call (or equivalent in managed code): join-path ([environment]::GetFolderPath("MyDocuments")) WindowsPowerShell\Modules
  2. Copy your module or (modules) to folder at above
  3. Profit.

It’s as easy as that.

Tags:

Modules | PowerShell | PowerShell 2.0 | PowerShell 3.0 | PowerShell ISE | Best Practice

PowerShell 3.0–Now with a legible registry provider!

by oising 9. October 2011 13:21

I don’t need to say anything to accompany these pictures. A screenshot or three is worth a thousand words:

PS C:\> gi hklm:\software\microsoft\windows\currentversion

    Hive: Registry::HKEY_LOCAL_MACHINE\software\microsoft\windows

Name                           Property
----                           --------
currentversion                 SM_GamesName             : Games
                               SM_ConfigureProgramsName : Set Program Access and Defaults
                               CommonFilesDir           : C:\Program Files\Common Files
                               CommonFilesDir (x86)     : C:\Program Files (x86)\Common Files
                               CommonW6432Dir           : C:\Program Files\Common Files
                               DevicePath               : C:\windows\inf
                               MediaPathUnexpanded      : C:\windows\Media
                               ProgramFilesDir          : C:\Program Files
                               ProgramFilesDir (x86)    : C:\Program Files (x86)
                               ProgramFilesPath         : C:\Program Files
                               ProgramW6432Dir          : C:\Program Files
                               SM_AccessoriesName       : Accessories
                               PF_AccessoriesName       : Accessories

Now here’s the corresponding view in the Registry Editor:

image

Awesomesauce!

Tags:

PowerShell 3.0 | PowerShell | Monad

PowerShell 2011 Scripting Games

by oising 9. March 2011 16:47
2011 Scripting Games

The 2011 Scripting Games begin on April 4, 2011 and run through April 15, 2011. What is the Scripting Games, you may ask? Well simply put, the Scripting Games are the premier learning event of the year for IT Pro’s and others who wish to master Windows PowerShell. Comprising 10 events, a registered contestant has seven days to create a solution to a scenario driven problem and post their code to a MVP maintained script repository for evaluation by a panel of internationally recognized judges. Daily leaderboards and prize drawings help to maintain the suspense throughout the two-week international event.

During the 2011 Scripting Games hundreds of contestants will submit thousands of scripts that will be reviewed by dozens of judges. Hundreds of thousands of spectators from all around the world will view the games themselves. Last year, participants from more than 100 countries participated in the Scripting Games. With an emphasis on real world scripting scenarios and problems, the scripts will be of immediate value to both the participants and to the spectators.

Preparation for the 2011 Scripting Games is already underway, with a learning guide, step-by-step tutorials, videos and other resources being generated on a daily basis. The 2011 Scripting Games all in one page is the portal for the games themselves. The 2010 Scripting Games all in one page is still available, as are the events from the 2009 Scripting Games.

Tags:

Making Windows PowerShell ISE “Good Enough.”

by oising 14. February 2011 19:23

I don’t generally write a lot of big scripts, but when I do, I usually fire up the PowerShell 2.0 graphical IDE. However, every time I use it to develop a module I always get irritated by the lack of any session management. When I hack away on a module, I usually have a couple of files open. I rarely finish a module in one sitting either, so I’ll come back to it in a day or two. I don’t always leave ISE open though so when I fire it up again I have to navigate to the location (or locations) where my files are and re-open them. Another annoying situation is playing with assemblies either by loading some external ones, or by using Add-Type to create your own in-memory types/classes. Debugging these things can get annoying as once loaded or created, you have to quit ISE to “clean” memory of all your dabblings. Well, I lie when I say you have to quit ISE. Strictly speaking, you can create a new tab with CTRL+T, close the old one and load all of your scripts into the new tab. Tabs are isolated from one another and assemblies loaded in one are not available elsewhere. So, taking advantage of this trick, let me introduce:

ISE Session Tools Module v1.0

I have more features planned for v1.1 to give ISE a proper “project” based feel to it, but in the interest of shipping something, v1.0 has the following features:

  • AutoSaving of current session (files open in current tab.)
    • This can be disabled and manually controlled if desired.
  • Prompt to reload last session on ISE open
    • A hint is shown to you reminding you of some of the files you had open.
    • Press <enter> to accept the default of “Yes, reload my last session.”
  • Restarting of the current tab
    • Essentially cleaning memory and keeping your files open in the editor.
    • You get prompted for this action. Press <enter> to accept default of “Yes, restart this tab.”
  • All commands available under “Add-ons” menu for the mouse-fixated.

image

The commands exported by the module are:

  • Restart-PowerShellTab  (CTRL+ALT+R)
  • Export-PowerShellTab (CTRL+ALT+S)
  • Import-PowerShellTab (CTRL+ALT+L)
  • Enable-AutoSaveSession (CTRL+ALT+A)
  • Disable-AutoSaveSession (CTRL+ALT+X)

As you can see, they have hotkeys. This is possible because these commands are also bound to the “Add-ons” menu. I was careful to choose keys that do not interfere with IsePack if you like to use that module too.

image

Installing IseSessionTools

Extract the files  into a folder named “IseSessionTools” under <my documents>\WindowsPowerShell\Modules\. In my ISE $profile, I have the following lines at the end of the file:

Import-Module ISESessionTools
Enable-AutoSaveSession

If you want to clear your session, disable autosaving and delete the session file at ~\psise.session.clixml.

Download ISE Session Tools Module v1.0

Have fun!

Tags:

Eventing | Modules | Monad | PowerShell | PowerShell 2.0 | PowerShell ISE

About the author

Oisin Grehan lives in Montreal, Canada and builds all sorts of crap for all sorts of people.

Month List

Page List