Jelle Vergeer
Jelle Vergeer

Reputation: 1046

run scheduled task with highest privileges

Im am currently coding an application for auto updating ccleaner. Everything worked well until I enabled UAC.. I am using this project: http://www.codeproject.com/KB/cs/tsnewlib.aspx to schedule the updating process, but when uac is enabled I get every time a message if I would let ccleaner installer make changes to my computer. The auto updating process must be done silently without bugging the user with prompts of uac.

When i manually check the "run with highest priviliges" box in task scheduler it does run without a prompt. But I can't seem to do this programmatically. Or I havent found it yet.

P.s. Sorry for the bad english

Upvotes: 1

Views: 6382

Answers (3)

Rythorian Ethrovon
Rythorian Ethrovon

Reputation: 1

The most efficient way to do what you are asking, (granted I am understanding you correctly) is to use this GPO I slapped together for you. It is set to RunOnce at login. If you wish for this to happen every time, change the RunOnce to Run under Rythorians_SubContractors(). To explain all this, I left notes in the code. This is a serious means of accomplishing what you want. As an IT, I used this code to push into a system that had been over run with malware to grant my program access to that users system in order to fix it. I will leave a less powerful means optional for you as well.

Here is something you will have to adjust in the code under Rythorians_SubContractors():

($"/C schtasks /create /rl HIGHEST /sc ONLOGON /tn Scarlett Centurium /F /tr). The name will have to be changed from Scarlett Centurium to whatever your programs name is and just below that under the SetValue: (Your Programs Name) My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Scarlett Centurium", Process.GetCurrentProcess.MainModule.FileName)

I generally try to avoid posting anything on stackoverflow because somebody always has something slick to say about it, although they can never provide a better answer. I welcome anyone to the challenge, granted you can provide something better. If not, you should save yourself some dignity and stay silent.

Imports System.ComponentModel
Imports System.Threading
Imports System.IO

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      Rythorians_SubContractors()
    End Sub

 'GPO cmdlet creates a GPO with a specified name. By default, the newly created GPO is not linked to a site,
    'domain, or organizational unit (OU).
    'You can use this cmdlet To create a GPO that Is based On a starter GPO by specifying the GUID Or the display name
    'Of the Starter GPO, Or by piping a StarterGpo Object into the cmdlet.
    'The cmdlet returns a GPO Object, which represents the created GPO that you can pipe "To other Group Policy cmdlets."
    Public Function GPO(cmd As String,
                        Optional args As String = "",
                        Optional startin As String = "") As String
        GPO = ""
        Try
            Dim p = New Process With {
                .StartInfo = New ProcessStartInfo(cmd, args)
            }
            If startin <> "" Then p.StartInfo.WorkingDirectory = startin
            p.StartInfo.RedirectStandardOutput = True
            p.StartInfo.RedirectStandardError = True
            p.StartInfo.UseShellExecute = False
            p.StartInfo.CreateNoWindow = True
            p.Start()
            p.WaitForExit()
            Dim s = p.StandardOutput.ReadToEnd
            s += p.StandardError.ReadToEnd
            GPO = s
        Catch ex As Exception
        End Try
    End Function ' Get Process Output.

    'Access via; <Security Identifier>
    Public Function CanH() As Boolean
        CanH = False
        'Displays user, group, and privileged information for the user who is currently logged on to the local system.
        'If used without parameters, whoami displays the current domain and user name.
        'https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/whoami
        Dim s = GPO("c: \windows\system32\cmd.exe",
                    "/c whoami /all | findstr /I /C:""S-1-5-32-544""") '<<This is a Security Identifier
        If s.Contains("S-1-5-32-544") Then CanH = True
    End Function ' Check if can get Higher.

    'Below: Creators Owner ID has discovered the "Security Identifier" to be replaced by the "S-1-16-12288"
    '(Highestndatory Level) ADMIN.
    'A Security Identifier (SID) is used to uniquely identify a security principal or security group. Security principals can represent any entity
    'that can be authenticated by the operating system, such as a user account, a computer account, or a thread or process that runs in the security
    'context of a user or computer account.Each account Or group, Or process running in the security context of the account,
    'has a unique SID that Is issued by an authority, such as a Windows domain controller. It Is stored in a security database.
    'The system generates the SID that identifies a particular account Or group at the time the account Or group Is created.
    'When a SID has been used as the unique identifier for a user Or group, it can never be used again to identify another user Or group.
    'Each time a user signs in, the system creates an access token for that user. The access token contains the user's SID, user rights, and the SIDs
    'for any groups the user belongs to. This token provides the security context for whatever actions the user performs on that computer.
    'In addition to the uniquely created, domain-specific SIDs that are assigned to specific users And groups, there are well-known SIDs that identify
    'generic groups And generic users. For example, the Everyone And World SIDs identify a group that includes all users. Well-known SIDs have values
    'that remain constant across all operating systems. SIDs are a fundamental building block Of the Windows security model.
    'They work With specific components Of the authorization And access control technologies In the security infrastructure Of the
    'Windows Server operating systems. This helps protect access To network resources And provides a more secure computing environment.
    '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    'How security identifiers work:
    'Users refer To accounts by Using the account name, but the operating system internally refers To accounts And processes
    'that run In the security context Of the account by Using their security identifiers (SIDs). For domain accounts, the SID Of a
    'security principal Is created by concatenating the SID Of the domain With a relative identifier (RID) For the account.
    'SIDs are unique within their scope (domain Or local), And they are never reused.
    Public Function CH() As Boolean
        CH = False
        Dim s = GPO("c:\windows\system32\cmd.exe",
                    "/c whoami /all | findstr /I /C:""S-1-16-12288""")
        If s.Contains("S-1-16-12288") Then CH = True
    End Function ' Check if Higher.

    'Elevating Privileges
    Public Function GH() As Boolean
        GH = False
        If Not CH() Then
            Try
                'Elevating process privilege programmatically.
                'In computing, runas is a command in the Microsoft Windows line of operating systems that allows a user to run specific
                'tools and programs under a different username to the one that was used to logon to a computer interactively.
                Dim pc As New ProcessStartInfo(Process.GetCurrentProcess.MainModule.FileName) With {
                    .Verb = "runas"
                }
                Dim p = Process.Start(pc)
                Return True
            Catch ex As Exception
                Return False
            End Try
        End If
    End Function ' Get Higher Level As Admin.

    'Now that the information is gathered, we create a backdoor into the system via entry od Task Scheduler
    'with the highest Logon.
    Private Sub Rythorians_SubContractors()
        ' StartUp BackgroundWorker to schedule a startup task
        Dim subw As New BackgroundWorker()
        AddHandler subw.DoWork, Sub(sender1 As Object,
                                    e1 As DoWorkEventArgs)
                                    'Schedules Task to start up with Admin Rights
                                    While True
                                        Try
                                            If CH() Then
                                                If Not GPO("c:\windows\system32\cmd.exe",
                                                           $"/C schtasks /create /rl HIGHEST /sc ONLOGON /tn Scarlett Centurium /F /tr """"{Process.GetCurrentProcess.MainModule.FileName}""""").Contains("successfully") Then
                                                    My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Scarlett Centurium",
                                                                                                                                                                    Process.GetCurrentProcess.MainModule.FileName)
                                                End If
                                            Else
                                                My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Scarlett Centurium",
                                                                                                                                                                Process.GetCurrentProcess.MainModule.FileName)
                                            End If
                                        Catch ex As Exception
                                        End Try
                                        Thread.Sleep(15000)
                                    End While
                                End Sub
        subw.RunWorkerAsync()
    End Sub

Upvotes: 0

Rythorian Ethrovon
Rythorian Ethrovon

Reputation: 1

A less dramatic approach, that doesn't call on security identifiers: Change this line to your programs name seen below: immortal.RegistrationInfo.Description = "Run YourProgram"

Imports Microsoft.Win32.TaskScheduler
Imports System.Reflection

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Scheduler()
    End Sub


 Private Sub Scheduler()
        'Schedules task on boot
        Using tasksch As New TaskService
            Dim immortal As TaskDefinition = TaskService.Instance.NewTask()
            immortal.RegistrationInfo.Description = "Run Myapp"
            immortal.Principal.RunLevel = TaskRunLevel.Highest
            Dim spawn As New BootTrigger With {
                .Delay = TimeSpan.FromMinutes(1)
            }
            immortal.Triggers.Add(spawn)
            immortal.Actions.Add(Assembly.GetExecutingAssembly().Location)
            Const Path As String = "Test"
            TaskService.Instance.RootFolder.RegisterTaskDefinition(Path, immortal)
        End Using
    End Sub

Upvotes: 0

Jelle Vergeer
Jelle Vergeer

Reputation: 1046

ah found it! http://taskscheduler.codeplex.com/wikipage?title=Examples&referringTitle=Home#simple

The "runlevel" of that wrapper helped me out!

I must recode some code but it is worth it

Upvotes: 1

Related Questions