System.UnauthorizedAccessException - question

Started by stanl, July 23, 2023, 10:42:58 AM

Previous topic - Next topic

stanl

This is more for general feedback. But was playing around with iterating folder->subfolder with size in MB.  I know WB can set Erromode On or off, but also want to capture any folders where 'access is denied'... I asked Claude who responded with a Powershell script.. try=>catch using System.UnauthorizedAccessException as the catch error.


Unfortunately, although the basic script would work, could not capture the folders that were not accessible to the file I was writing output to. Googled it and seems others had consternation.  One remedy was to use the more general Win Exception.Message which is a property of that class...


Even running as Admin, some folders on local PC/laptop may still show as access denied, but cannot be iterated by script. Yes, you can turn error handing off, or with PS - $erroractionPreference="SilentlyContinue" - but will still noy capture folders with access denied.


I found there is a generic Exception class with a .message property. But I ccanot figure out how to handle that.


Back to the question: I might have tested with PS, but need this as a WB solution. Is going into .NET classes via CLR worth the effort, or can standard WB errorhandling perform

       
  • Generate an Array of all folder starting from... C:\
  • ForEach folder iterate sib-folders and calculate spaced used in MB
  • If folder/subfolder cannot be accessed, indicate folder name + "access denoed"

td

It will take some work but you should be able to modify Detlev's script to your needs:

https://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/nftechsupt.web+WIL~Extenders/File~Searcher/File~And~Folder~Extender+Disk~Scan~Sample.txt

The C:\Program Files\WindowsApps directory is the most common directory that causes admin access problems. I imagine Microsoft markets this as a security "feature". Of course, you can add error handling to the script to work around this. I have ownership of the directory and all sub-directories on my system, so it is not an issue.

But alas, the script does not have all the latest and greatest, new and improved Mircosoft stuff so you might not find it interesting.

"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

The 'needs' are not critical... just an ask from a user I have created scripts for for years. More of a challenge - iterate folders with access denied....


Turns out it is a time-consuming, not really important. Correct me if I am wrong, but most scripts look at access denied when trying to copy files or other ordinary tasks.


Not WB but I found:




function SearchUnique ($Folder) {
    try {
        Get-ChildItem -Path $folder -Directory -ErrorAction Stop| foreach {
            SearchUnique $_.FullName
        }
        #uncomment next line to show all folders
        #$folder
    }
    catch{
        "Unable to access $folder"
    }   
}
SearchUnique 'C:\Windows'



which produced this on my laptop... Again, not worth the time.... and if I had another 2 hours to hurry up and wait, could elaborate virus scan quarantine and other folders...




Unable to access C:\Windows\appcompat\Programs
Unable to access C:\Windows\InfusedApps
Unable to access C:\Windows\LiveKernelReports
Unable to access C:\Windows\Logs\SystemRestore
Unable to access C:\Windows\Minidump
Unable to access C:\Windows\ModemLogs
Unable to access C:\Windows\Prefetch
Unable to access C:\Windows\Provisioning\Autopilot
Unable to access C:\Windows\Resources\Themes\aero\VSCache
Unable to access C:\Windows\security\audit
Unable to access C:\Windows\security\cap
Unable to access C:\Windows\ServiceProfiles\LocalService
Unable to access C:\Windows\ServiceProfiles\MSSQL$SQLEXPRESS
Unable to access C:\Windows\ServiceProfiles\MSSQLFDLauncher$SQLEXPRESS
Unable to access C:\Windows\ServiceProfiles\MSSQLLaunchpad
Unable to access C:\Windows\ServiceProfiles\MSSQLLaunchpad$SQLEXPRESS
Unable to access C:\Windows\ServiceProfiles\NetworkService
Unable to access C:\Windows\ServiceProfiles\SQLTELEMETRY
Unable to access C:\Windows\ServiceProfiles\SQLTELEMETRY$SQLEXPRESS
Unable to access C:\Windows\ServiceProfiles\TEMP
Unable to access C:\Windows\ServiceState
Unable to access C:\Windows\System32\Com\dmp
Unable to access C:\Windows\System32\config
Unable to access C:\Windows\System32\Configuration
Unable to access C:\Windows\System32\drivers\DriverData
Unable to access C:\Windows\System32\DriverState
Unable to access C:\Windows\System32\ias
Unable to access C:\Windows\System32\LogFiles\HTTPERR
Unable to access C:\Windows\System32\LogFiles\WMI\RtBackup
Unable to access C:\Windows\System32\MsDtc
Unable to access C:\Windows\System32\networklist
Unable to access C:\Windows\System32\RsFx
Unable to access C:\Windows\System32\SleepStudy
Unable to access C:\Windows\System32\spool\PRINTERS
Unable to access C:\Windows\System32\spool\SERVERS
Unable to access C:\Windows\System32\sru
Unable to access C:\Windows\System32\Tasks
Unable to access C:\Windows\System32\Tasks_Migrated
Unable to access C:\Windows\System32\WDI
Unable to access C:\Windows\SystemTemp
Unable to access C:\Windows\SysWOW64\Com\dmp
Unable to access C:\Windows\SysWOW64\config
Unable to access C:\Windows\SysWOW64\Configuration
Unable to access C:\Windows\SysWOW64\Msdtc
Unable to access C:\Windows\SysWOW64\networklist
Unable to access C:\Windows\SysWOW64\sru
Unable to access C:\Windows\SysWOW64\Tasks
Unable to access C:\Windows\Tasks\ImCleanDisabled

td

On my Windows 11 system, I can access all the folders you list as restricted using a modified version of Detlev's script. I have not touched the permissions or ownership of any of the folders below "c:\Windows" but I am running a native application (WinBatch) as an elevated admin. 
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

I'm going to try to replicate the try...catch block with IntControl73 and a UDF.

td

The WinBatch regression test suite uses IntControl 73 with p1 set to option 2 to implement something like a try/catch block.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

This is interesting and probably really off-topic. I have written several scripts automating WinSCP to load or extract data from either SFTP servers, or using REST for API's.  Most have used service accounts, so the user|password were consistent. Now changes to using credentials where password change requirements are regular, so need to preface the scripts with credential dialog


Credentials cannot be stored in an .ini of other file as that violates security rules.





I can obtain credentials as an object but WinSCP needs each broken down as user|password. User is no problem, but password is returned as a security object and script will fail.


FUNNY THING:  In Powershell if your password has $ in it, it needs to be escaped.... lesson learned.


So, I guess bottom line is how WB can capture credentials as plain text from the prompt above

ChuckC

There will be situations where even if your script is running elevated as an administrator that you still get access-denied errors/exceptions when attempting to iterate through the file system.  The underlying issue has mostly to do with the way in which access checks are performed when a directory/file is being opened for access.  Unless the code that is calling one of the Win32 API CreateFile*() functions specifies that "backup semantics" should be used *AND* has the "backup" privilege and "security" privilege enabled to cause all access checks to be bypassed, it is possible to encounter restrictive permissions that will block an administrator from accessing a directory or file.

td

Quote from: stanl on July 30, 2023, 05:33:44 AM
...
So, I guess bottom line is how WB can capture credentials as plain text from the prompt above

Your PS cmdlet has the option to retrieve the password as plain text. It likely violates one or more security dictates so you may not be able to use it. But if you can, it might lead to something depending on how you are invoking the cmdlet.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

ChuckC

I entered 'user' as the username and 'password' as the password.


$creds = Get-Credential

PowerShell credential request
Enter your credentials.
User: user
Password for user user: ********

PS C:\> $creds

UserName                     Password
--------                     --------
user     System.Security.SecureString

PS C:\> $creds.Password.ToString()
System.Security.SecureString


PS C:\> $pw = ConvertFrom-SecureString -SecureString $creds.Password -AsPlainText
PS C:\> $pw
password


td

Quote from: ChuckC on July 30, 2023, 06:08:35 AM
There will be situations where even if your script is running elevated as an administrator that you still get access-denied errors/exceptions when attempting to iterate through the file system.  The underlying issue has mostly to do with the way in which access checks are performed when a directory/file is being opened for access.  Unless the code that is calling one of the Win32 API CreateFile*() functions specifies that "backup semantics" should be used *AND* has the "backup" privilege and "security" privilege enabled to cause all access checks to be bypassed, it is possible to encounter restrictive permissions that will block an administrator from accessing a directory or file.

Yes, I mentioned the access problem in a previous post and I wasn't making the case that the script can access all folders on the file system without intervention. I was specifically comparing the folders Stan found unavailable with my experience because I have not tweaked the permissions on those folders. As also mentioned I have adjusted permissions on the \program files\windowsapps subtree of the file system by taking ownership of the folder. That is the only tweak I needed to give the modified Detlav script read access to every folder on the system. Of course, your mileage may vary.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

Quote from: ChuckC on August 01, 2023, 04:34:23 AM
I entered 'user' as the username and 'password' as the password.


$creds = Get-Credential

PowerShell credential request
Enter your credentials.
User: user
Password for user user: ********

PS C:\> $creds

UserName                     Password
--------                     --------
user     System.Security.SecureString

PS C:\> $creds.Password.ToString()
System.Security.SecureString


PS C:\> $pw = ConvertFrom-SecureString -SecureString $creds.Password -AsPlainText
PS C:\> $pw
password


Thanks Chuck;


I used a .Net PtrToBstr function to get the password. I found that if $ was pat of the password it would have to be escaped $password = $password.Replace("$","`$")  in order to be entered into WinSCP automation. Hate to think that other special chars like / might cause some sort of regex issue  :-[

stanl

Chuck;


I tried your $password = ConvertFrom-SecureString -SecureString $creds.Password -AsPlainText in my script and the access to WinSCP failed with 'access denied'


This works for me, while a bit of a kludge


$credential = Get-Credential
$credential | Export-CliXml -Path 'C:\temp\cred.xml' -Force
$credential = Import-CliXml -Path 'C:\temp\cred.xml'
$user = $credential.UserName
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($credential.Password))
$password.Replace("$","`$")
If (Test-Path -Path  'C:\temp\cred.xml' ) {


    Remove-Item  'C:\temp\cred.xml'


}



Understand, not really about which is better... maybe it is just the security on the system I employ the scripts... and this is also not PS versus WB.  Point is unless I create the temp xml output then harvest the password from it, other attempts have the password coming up blank.


I was informed that changes are coming to remove service accounts for SFTP and allow only credentials so I had better
Quotesink my teeth into it