I've recently discovered that by default, execution of powershell scripts is disabled. I was going to rely on it to safely remove a USB device from Windows, however if it's not enabled by default, I'd have to enable it first. Is it generally acceptable to do such things?
Alternative solutions are also welcome.
This question follows: https://superuser.com/questions/637854/safely-remove-a-usb-drive-using-bat-file/637878
I would not enable the execution of scripts globally on a machine just because your app wants to use it. That's an IT/Security policy decision, and they shouldn't be forced to accept your decision simply by using your software. If you're calling a PowerShell runspace from within a .NET app, you shouldn't need to worry about the execution policy since you can run your commands without calling to a separate .ps1 script. If you need to call powershell.exe and give it a script file, look at -ExecutionPolicy Bypass. About_Executionpolicies says this about Bypass:
- Nothing is blocked and there are no warnings or
prompts.
- This execution policy is designed for configurations
in which a Windows PowerShell script is built in to a
a larger application or for configurations in which
Windows PowerShell is the foundation for a program
that has its own security model.
MS used to deliver systems that were 'ready-to-exploit'. They got smarter about it, and take security much more seriously. So they now disable many features by default.
As for PowerShell, the default 'execution policy' by default did not allow scripts to be run. However, on a command line you could bypass the execution policy all together (ie. without changing it) as long you have permissions to do so:
PowerShell -ExecutionPolicy Bypass -file yourfile.ps1
If you are an administrator of the machine, it's perfectly OK to enable it and use it. If you are just an app-owner, you should probably consult with the administrator to change the policy, but as noted above, you may not need to.
Related
I was getting error when I try to use NPM commands on powershell (Win11) and I fixed it with this powershell command:
Set-ExecutionPolicy RemoteSigned
But I'm unsure if I can leave it like that for always is it safe to leave it like that? Or should I turn it back to default with this command:
Set-ExecutionPolicy Restricted
Putting this here as it is too long for a normal comment.
Please read the documents in PS Execution Policies.
about_Execution_Policies
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.2
PowerShell's execution policy is a safety feature that controls the
conditions under which PowerShell loads configuration files and runs
scripts. This feature helps prevent the execution of malicious
scripts.
Execution policies as per Microsoft are not a security boundary.
Execution policies can easily be bypassed as needed.
15 Ways to Bypass the PowerShell Execution Policy
https://www.netspi.com/blog/technical/network-penetration-testing/15-ways-to-bypass-the-powershell-execution-policy/
By default PowerShell is configured to prevent the execution of
PowerShell scripts on Windows systems. This can be a hurdle for
penetration testers, sysadmins, and developers, but it doesn’t have to
be. In this blog, I’ll cover 15 ways to bypass the PowerShell
execution policy without having local administrator rights on the
system. I’m sure there are many techniques that I’ve missed (or simply
don’t know about), but hopefully, this cheat sheet will offer a good
start for those who need it.
Should they be used, yes, but they are only a short hurdle to overcome by experienced folks, but regular users would not usually know that.
You can set restricted or remoteSigned for the host (MachinePolicy), but run scripts using whatever policy you choose for your user profile (Process or CurrentUser).
You can have multiple PS instances all running with different EP's.
Is it possible to get a C++ application running in Windows to request administrator privileges from the operating system at run time?
I know it can be done at compile time, but can't seem to find anywhere whether it can be done at run time.
Thanks for your help!
EDIT: What if I want the current instance to have elevated privileges? For example, I might have data stored in memory which I want to keep.
If you want the application to always elevate, you can give it a manifest, either by building one in (not compiling technically) or by putting an external manifest in the same folder as the exe. If you want to decide, as a person, to run it elevated, you right click the exe or short cut and choose Run As Administrator. If you are launching it from code, then as #vcsjones comments, you use the runas verb when you launch that process. For example:
ShellExecute( NULL,
"runas",
"c:\\windows\\notepad.exe",
" c:\\temp\\report.txt",
NULL, // default dir
SW_SHOWNORMAL
);
You can elevate a process only during its creation. When a process already runs, there's no way to change its security token: it either runs elevated or not.
If your application needs to perform an administrative task, and it usually runs non-elevated, you have to create another .exe which will request elevation with its manifest. To start a process elevated, you have to use ShellExecute or ShellExecuteEx function. From your main process you will need a way to pass the commands to that new process that will run elevated.
For more information about UAC, read Designing UAC Applications for Windows Vista series.
Not quite, but you can do the opposite—you can drop privileges if you already have them. So, you can have your program start out running as an Administrator, using one of the methods listed by Kate Gregory. Then, drop your unneeded privileges; see Dropping privileges in C++ on Windows for how to do that.
Add a manifest file into your EXE as described here.
http://msdn.microsoft.com/en-us/library/bb756929.aspx
Your process (and threads) have a token assinged to them. That token already have all your groups set up. Under UAC, the Administrator group is disabled. UAC will remove that disabled group so you end up with a full administrator token.
To acheive the same, you must have the TCB priviledge. In other words, to elevate a process at runtime, you will need help from a process running under the SYSTEM account, and Microsoft isn't providing one, nor an API to control the current UAC implementation. Otherwise, it would defeat the purpose.
For the sake of completness, there is a whitelist of process that can perform some elevated operations without prompting. In short, your executable needs :
To be signed by Microsoft
To perform predefined operations, like with IFileOperation
The best explanation I found is this hack. It has been fixed since then, but is sheds some light on the whole thing.
I am trying to do my first script. To simply get PowerShell to pull up a script typed up in notepad and saved as a .ps1 file titled "test" (have also tried Script, but know names have nothing to do with it):
Write-Host "Hello, World!"
In PowerShell I am typing
& "C:\Scripts\test.ps1"
As well as
./test.ps1
And am only met with this:
./test.ps1.txt : The term './test.ps1.txt' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ ./test.ps1.txt
+ ~~~~~~~~~~~~~~
+ CategoryInfo: ObjectNotFound: (./test.ps1.txt:String) [], CommandNotFoundException
Have tried renaming the file within PowerShell with
PS C:\Scripts> Rename-Item test.ps1.txt test.ps1
I have switched between RemoteSigned and Unrestricted, I have tried a code including executionpolicy bypass (I do apologize, I closed my window without writing that one down). As far as I know everything is up to date and I am running Windows 10, Windows PowerShell, and regular Windows Notepad.
First, I'd HIGHLY recommend using the Windows PowerShell ISE for writing scripts. It's free, and provides a pretty decent console/editor experience, given that it's free (there are allegedly better ones out there, but this has always done just fine for me). I use Visual Studio for other stuff, and while it is an EXPONENTIALLY better product (and should be), the PowerShell ISE is pretty feature-rich.
Next, if you're just getting started, you should check out Don Jone's "Learn PowerShell 3.0 in a Month of Lunches" book. It's two versions behind the most current, however, all of the information is still relevant, and once you've finished the book, you'll be able to seek help for anything else pretty easily on your own. It covers all the basics, and is a very good first step to learning the language.
Now, to answer your question: PowerShell scripts commonly have the .ps1 file extension. Other extensions are generally used for modules (.psm1) or other helper content that Windows PowerShell leverages. For most things, you'll stick to .ps1, and when you've reached a point where you start needing the other extensions, I suspect you will have no problems identifying which ones you need.
There are two ways generally call a PowerShell script. The first is from a normal command prompt, and telling PowerShell to execute your script. This is shown below:
powershell.exe -File MyScript.ps1
There are some additional parameters that I'd recommend you use, but usage is dependent on your requirements. Here's what I usually tag on mine:
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File MyScript.ps1
This will tell the PowerShell process to ignore any PowerShell profiles you have set up, which is ideal if you have a bunch of stuff in your profile script that does things like read console input (for your current situation, I'm going to assume you don't, but you may in the future). The other is that ExecutionPolicy one: RemoteSigned will tell PowerShell to basically ignore anything that's been downloaded from the interwebs, but allow anything originating inside your network to run free. Probably not the best practice, but this isn't a TERRIBLE policy if you can trust that your script repository is secured. If not, then go for something tighter than this (you can read up on execution policies by typing "Get-Help about_Execution_Policies" in the PowerShell prompt, or by visiting the TechNet page about them -- the content should be similar if not identical).
The second way is from inside of a Windows PowerShell script. It's actually much easier to do. Note that you must set your execution policy to something that will allow scripts to run, but thereafter, you're smooth sailing.
. .\MyScript.ps1
This is called "dot-sourcing" your script. The advantage of doing this from within Windows PowerShell is that if you've got something like a script full of functions, they get added to the current scope (Get-Help about_Scopes), which means they're now available in your current session. A good example would be defining a function called "Test-DomainConnection" in a script you distribute with your main script: You'd dot-source the script that is distributed with the main one (this is done usually when you separate your "standard" PowerShell functions from your main script), and then use the functions in the main script. There are pros and cons to this approach, but it seems to be generally recommended (there may be some community extensions out there that remove the need to manage this manually).
For additional information, you can call Get-Help about_Scripts from inside Windows PowerShell. Because you're using Windows 10, you may need to run Update-Help from an administrative PowerShell window before the help content is available on your local system.
If you have any more questions, feel free to message me :) I've been doing PowerShell for a while and may be able to help out.
Powershell processes in order (top-down) so the function definition needs to be before the function call:
How do i run task at boot time and wait for it's completion? I know chkdsk and some other programs are doing that, but how?
Update: i found a way. Native API, if anyone's curious.
Windows have a "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute" key, programs in it are executed before any subsystem is started, i.e. before win32,LSA, etc. The only API avaliable at that time is NativeAPI. Most of it's functions can compromise security and stability of the system (This API can close handles, hide registry keys and more). Of course, a lot of it's functions are undocumented, but guys at http://undocumented.ntinternals.net/ have documented a lot of them.
Here is another method (not sure if this "Native API" is the same but you can use the Windows Task Schedular. There is a On Computer Start on or a User Login option too.
How to install/wrapper (Just for more info): Windows Task Scheduler Installer
Is it possible to programmatically disable UAC in Vista? Or, can I make my application run unrestricted by the UAC setting in any way? FYI, the application needs to mount hard drives on the fly, which is why I can't ask for UAC permission each time...
Update:
I'm looking for something in line with what Kosi2801 mentioned, basically to ask the user to always start the program in an 'elevated' mode. I'd want the permission to be a 1 time thing, I'm not saying that I programmatically disable UAC without asking permission first. I'm sure there are lots of programs that need to operate in this mode (especially hardware-related programs) so there should be some type of way to accommodate it.
Set the EnableLUA DWORD value in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System to 0 and reboot.
this will disable UAC without a problem, i would do it to all your users, with or without permission is up to you, because the vista UAC is so horrid that i do believe the less people that have it on the better (in vista only) it is now better in win7.
have fun with my registry trick :)
works in win7 as well, let me know how you got along with it.
You can't programmatically disable UAC, but you can force the program to run with elevated privileges from the start, so it doesn't prompt each time.
That will cause it to prompt once on startup, but not each time it needs access.
To do this, you'll need to create a manifest file and set <requestedExecutionLevel level="requireAdministrator">
See MSDN for details.
The purpose of UAC is to prevent executing unwanted applications. If it was possible to disable it programatically it would be worthless.
I posted a somewhat granular (but ugly) solution here
http://stackoverflow.com/questions/5344021/bypass-uac-in-vbscript/34445992#34445992
It only works if you can kick off the application from the task scheduler. I have it running on two Windows 7 laptops. It is an administrative solution. You need administrator privilege to implement it. I use it for powershell and for my UPS power backup application. I suspect I'll find other uses.
I created a small application to do this, but basically there are 4 registry keys you need to set.
C# example:
Microsoft.Win32.Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System","EnableLUA", 0);
Microsoft.Win32.Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "ConsentPromptBehaviorAdmin", 0);
Microsoft.Win32.Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "PromptOnSecureDesktop", 0);
Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Action Center\\Checks\\{C8E6F269-B90A-4053-A3BE-499AFCEC98C4}.check.0", "CheckSetting", StringToByteArray("23004100430042006C006F00620000000000000000000000010000000000000000000000"), RegistryValueKind.Binary);
My application runs as a service every 5 minutes to "fight" Group Policy on this, which is an absolute annoyance for a developer machine.
https://github.com/zleight1/DisableUAC
Disabling UAC programmatically would defeat its purpose as this would then also be possible to be done by malware, worms, trojans and virusses and have no real security-effect at all.
You could require to run your application under the admin-account or (I think) let Microsoft somehow sign your application.
There may be other ways I'm not aware of, but none of them is programmatically!
UAC is a necessary evil alike the use of semaphores on a city. I suggest adapting to the new paradigm. I personally don't like UAC; but I understand the purpose and benefits. Unfortunately, we all created this monster. Lest's go back to 1983, do a short assessment of the changes throughout the years and then, we will understand. Of course, if the intent is for private use, anything is possible, as pointed above; but it would be risky and become a black hole liability.
That would defeat the object of UAC. So no, you can't.