Network address inaccessible if ran by the Task Scheduler - windows

I have a C# program that does this:
Directory.Exists(#"\\PcName\SomeDir");
and prints whether that path is accessible (exists) or not.
This is the problem: I run this app via the Task Scheduler right after log-in (auto-log-in user), using the "On Login" trigger, and it returns false, although that path IS accessible! (I manage to open that path using the explorer.exe few seconds before my app starts). It is marked to:
Run with highest privileges
If I run it manually it runs OK, even when I right click the task and select "Run" via the Task Scheduler!
If I deselect "Run with highest privileges", there is no problem, but it must be ran with highest privileges (accesses registry and whole lot other stuff)
It runs under same user if I run it manually or automatically by the task scheduler - I made sure using Process Explorer
It happens on certain machines (Win8x64, admin-privileges-user with no password, auto-log-in, workgroup machines, not domain), but not on anothers (same: Win8x64, admin-privileges-user with no password, auto-log-in, workgroup machines, not domain).
Even if I insert Thread.Sleep(TimeSpan.FromMinutes(1)); or enter 1-min delay in the task (in the Task Scheduler) it still says this path does not exist

Problem solved. I had to "impersonate", although I’m not really sure why: if I use the scheduler without restarting, it accesses the remote share – exactly the same settings, one to one. Only after restart it fails to access the share (and a moment later, again – same settings, it is able to access).
The only difference in running it immediately after restart is that the app-process’s parent is services.exe and not explorer.exe as usual. My guess is that it has to log in immediately after the restart, so it must use services.exe (explorer.exe is not supposed to exist at that stage, if I'm not mistaken).
Below is the solution in C#, roughly, to whom it may concern:
// LogonUser is a "P/Invoked" API:
// http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html
// this solution works only with the LOGON32_LOGON_NEW_CREDENTIALS as the 4th parameter:
using (var h = LogonUser(username, domain, password,
LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
LogonProvider.LOGON32_PROVIDER_DEFAULT))
{
using (var winImperson8Ctx = WindowsIdentity.Impersonate(h.DangerousGetHandle())) {
return Directory.Exists(path); // now works fine...
}
}

Related

How to download a file using BITS in a Packer provisioner?

I'm writing a provisioning script in PowerShell for a Packer-built Windows image on a CI pipeline. This process involves downloading several large files. I'm under the impression that BITS is faster than Invoke-WebRequest, so I've decided to use BITS to asynchronously download these large files.
The problem is that BITS will only process jobs for users that are interactively logged on...
BITS transfers files only when the job's owner is logged on to the computer (the user must have logged on interactively). BITS does not support the RunAs command.
...unless the job was submitted by a service account.
You can use BITS to transfer files from a service. The service must use the LocalSystem, LocalService, or NetworkService system account. These accounts are always logged on; therefore, jobs submitted by a service using these accounts always run.
But even then, there's a wrinkle:
If a service running under a system account impersonates the user before calling BITS, BITS responds as it would for any user account (for example, the user needs to be logged on to the computer for the transfer to occur).
This is an issue because the provisioning script runs as the Administrator account, which is not a service account and therefore must be logged in interactively to use BITS. This happens to be Packer's behavior, so I can't change this. I'm wrong, I can change this. See my final answer. How can I do the following in one PowerShell script?
Submit a BITS job as Administrator using a service account's credentials. I assume I need to pass something in to Start-BitsTransfer's -Credential parameter?
Store the BITS job in a local variable (jobs will be started at different places in the script)
Await the completion of the BITS job so I can start using the file I downloaded (jobs will be awaited at different places in the script)
You could use psexec to run a secondary script with SYSTEM rights by the administrator content and have the primary script identify the exit code of the psexec process to confirm it has successfully executed.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.1
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec#:~:text=PsExec%20is%20a%20light-weight,to%20manually%20install%20client%20software.
https://weblogs.asp.net/soever/returning-an-exit-code-from-a-powershell-script
It turns out there's a solution to this, although it's specific to Packer. I didn't mention much about my use of it because I didn't think it was that important.
Contrary to my initial belief, Packer's PowerShell provisioner lets you run the provisioning script with elevated privileges as any user...
elevated_user and elevated_password (string) - If specified, the PowerShell script will be run with elevated privileges using the given Windows user.
provisioner "powershell" {
elevated_user = "Administrator"
elevated_password = build.Password
}
...including service users.
If you specify an empty elevated_password value then the PowerShell script is run as a service account. For example:
provisioner "powershell" {
elevated_user = "SYSTEM"
elevated_password = ""
}
After adjusting my Packer template's provisioner block accordingly, I can now confirm that Start-BitsTransfer and friends work as expected. No need to pass complicated arguments or play tricks with sessions.

Unable to run a COM application through Jenkins if no user is logged in

I am running a Jenkins server on a Windows 10 computer, as a service. In one of the Jenkins-jobs I have to perform tests using a COM application. The same computer is also used by the developers in their daily work over RDP, and the Jenkins-job in question is run in the night when no regular developer is using it. But if no user is logged in on the computer or using RDP, the script in the job fails to start the COM application with the following message:
The server process could not be started because the configured
identity is incorrect. Check the username and password.
I found that the issue seems to be that the identity for the COM application is taken from the current interactive user, and if there is none, it fails, see
https://support.microsoft.com/en-my/help/305761/com-server-application-that-uses-interactive-user-identity-fails-to-lo
I cant seem to be able to solve my issue. I see two options:
Make sure that a user is logged in when the job is executed
Figure out how to run the COM application without an interactive user
For 1 i see the following solutions and why they do not work:
Autologin on Windows start, and leave logged-in: Will not work since we use the computer in our daily work through RDP, which means that the local logged in user will be kicked out since we are only allowed one session at a time.
Log in using RDP and then exit using the script tscon.exe 0 /dest:console which will leave the session open. Will not work since we are 15 people in the team using that machine over RDP, and people will forgett to use this command when they log of by the end of the day.
For 2, i am unable to find a way to do this.
Can I in Windows schedule a user to automaticall be logged in before the job starts? Can i use a second computer and scedule an RDP-session to the first computer, before the job is executed?
Since nobody was able to provide a good solution I will input my workardound as an answer and possible solution. What I ended up doing was using a second computer (running Windows) and schedule a task on that computer that every night (before the Jenkins-job starts) opens an RDP-session to the computer running Jenkins. This way the Jenkins job, and the COM-application, has an active user that it can use.
This is how I achieved this:
Login to the second computer (i.e. the one not running Jenkins) and open the RDP (Remote Desktop Connection) dialog and click Show Options
Enter the details for the first computer (i.e. the one running Jenkins). Make sure to uncheck Always ask for credentials (you will need to save the credentials to be able to automate this).
Save the configuration to an .rdp-file, using Save As...
IMPORTANT: Press connect to connect to the first computer, enter the password and make sure to save it. Also accept any certificates e.t.c. to prevent future warnings/dialogs.
Create a bat-file containing the following
mstsc C:\Path\To\saved_rdp_file.rdp
Create a task in Windows Sceduler that calls the bat-file created in step 5 every night.
Optional: If you want to close the rdp-session when Jenkins is done, create a second bats-script and scedule that as well, containing:
tasklist /FI "imagename eq mstsc.exe" | find "mstsc.exe" && taskkill /f /im mstsc.exe || echo process "mstsc.exe" is not running

How to run a VB6 app from a scheduled task without users being able to run it

We have a legacy VB6 application that automatically emails reports. It runs from a scheduled task on a server. Occasionally a user will run the exe - it's in a folder that we can't lock them out of, and it has to remain in that folder for reasons too complicated to go into here. Is there a way to prevent users from running the exe while still letting it run from the scheduled task? I can modify the source code for the exe, so that's an option if someone can help me figure out how.
I'm going to call your existing app AppChild and a new VB6 (or other program language) program AppParent.
Modify AppChild to test for a command line parameter at either Sub Main() or at the first form loaded in the Form_Load() event. If the command line parameter isn't there, AppChild terminates.
AppParent would be in a location not accessible to the other users. The Scheduled task runs AppParent which runs AppChild and passes the required command line parameter. This could be secured somewhat by passing a calculated hash and decoding it in AppChild if needed.
Or, if the users don't have access to the Scheduled Tasks, you could just run AppChild , passing the required parameter from the Scheduled Task. If the users do have access to the Scheduled Task this won't work because they could then see the passed parameter and create a shortcut which passes the required parameter.
You didn't state which OS the server is running but you may have problems using network resources if you try to run the Scheduled Task without a logged in user. Task Manager got a major update to handle security issues to prevent hackers from running tasks without a logged in user. Essentailly, network resources, .e.g. eMail, are not available unless a user is logged in.
https://technet.microsoft.com/en-us/library/cc722152(v=ws.11).aspx
The only way I found around that problem is to run a machine with a user with the correct permissions logged in all the time.
Are you sure you cannot lock the user out?
You could restrict access to the folder so that the user cannot access it and set up the scheduled task to use an account with access to the folder.
Although the users can't be locked out of the folder (perhaps the reports end up in there?), in Windows you can set the permissions on a per file basis. Make a new user that has the full rights (the same as your users). Schedule the VB6 app to run with that user. Remove the rights for the regular users to see the app. You do this by changing the permissions on just the VB6 app.

WNetGetUniversalName failing when called from a scheduled task

I have a (win32) program that is run through a scheduled task.
When run, my software should map a number of local drive letters to UNC resources, verify that the mappings have been successful, run a few other tasks and then unmap the drives.
When running under the context of a local user, all works fine. However, when I run it through the system task scheduler, the verify task fails.
The verify tasks takes the drive letter, checks if the drive is a network drive (through GetDriveType) then, if the drive if of type DRIVE_REMOTE, calls WNetGetUniversalName and compare the result with the expected mapping.
When run from a regular user context, this works. But when the process is called through the task scheduler, WNetGetUniversalName fails with error 87: The parameter is incorrect.
After trying to isolate the issue, I came to the following conclusions:
The issue is not linked to user rights: even when the user is made a member of both the local administrators group and the domain administrators group, the error remains.
The parameters I pass to the functions are ALWAYS the same: It's the drive letter concatenated with :\.
I have tried repeating the call after a short wait (100ms): same symptoms.
The mapping (made through WNetAddConnection2) actually succeeds.
The issue is not dependent on where the executable is located: same thing happen if it's on the local machine or run from an UNC path.
The issue occurs whether the scheduled task has been set to "run with highest privilege" or not.
Here is the exact call I use:
APIResult := WNetGetUniversalName(PWideChar(pathToCheck), UNIVERSAL_NAME_INFO_LEVEL, #RemoteNameInfo, Size);
I'm out of ideas about what to check next.
Edit Right now, I have reverted to a different behavior: All drives status is checked (GetDriveType), if it's a network drive, it's unmaped, checked again and then mapped. This seems to work but it's slower (of course) and it feels less secure.

GetProcessesByName() and Windows Server 2003 scheduled task

Does anybody know what user privileges are needed for the following code needs to successfully execute as a scheduled task on Windows Server 2003:
System.Diagnostics.Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
When NOT running as scheduled task i.e. under a logged in user, as long as the user is a member of "Performance Monitor Users", this code will not throw an exception.
When running as a scheduled task under the same user account, it fails.
The only way I can get it to work is to run it as a member of the Local Administrator group.
Any ideas?
My humblest apologies. The user I was using was NOT a member of "Performance Monitor Users" group.
This is necessary for .NET Framework 1.1 implementation of System.Diagnostics.
I have added the user to this group, and all is well.
What user rights assignments have you given the account that is running as a scheduled task? You'll need to give the account in question 'Log on as a batch job' in your local security settings.
Update: Does your app write to any files and if so does the scheduled task user have enough rights?
I just knocked up a test app that writes the process names from the Process[] array returned by Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) to a file and it works just fine as a scheduled task...even running under the identity of a user that is only a member of the Users group (not even a member of 'Performance Monitor Users'.
The folder it writes to is assigned modify rights to SYSTEM, Administrators and the scheduled task user.
Any chance of pasting your code or at least a small enough snippet that demonstrates the exe failing as a scheduled task so we can help diagnose the problem?
Cheers
Kev
One issue that I have seen with reading the process name is that access to the performance counters can get disabled.
Crack open your registry and see if this key is there:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance]
"Disable Performance Counters"=dword:00000001
You can either set it to zero or deleted it.
Taken from MSDN:
Permissions LinkDemand - for full
trust for the immediate caller. This
member cannot be used by partially
trusted code.

Resources