PowerShell – Change Registry Key Permissions

email me

$regPath = "HKLM:\SOFTWARE\JavaSoft"

Try  {
        Get-ItemProperty $regPath -ErrorAction Stop        
        $regACL = Get-ACL $regPath
        $regRule= New-Object System.Security.AccessControl.RegistryAccessRule("Everyone","ReadPermissions","Allow")
        #("Everyone","FullControl","Allow")
        $regACL.SetAccessRule($regRule)
        Set-Acl $regPath $regACL
        Write-Host "Success!"
      }

Catch {
            
         Write-Host "Failed!"
      }

Notes

$x = $regACL.AccessRightType.IsPublic
if ($x -eq "True" ) {write-host "Success"}

$regKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\JavaSoft",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
$regACL = $regKey.GetAccessControl()
$regRule = New-Object System.Security.AccessControl.RegistryAccessRule ("User","FullControl","Allow")
$regACL.SetAccessRule($regRule)
$regKey.SetAccessControl($regACL)

Script Engine Example in Batch – v2

email me

This is version two of this: I wrote this to install a ‘prepared’ package to a single computer, or to a list of computers. It’s low tech to get around the numerous problems associated with remote installation using PowerShell, VBScript, or desktop management applications.

cls
@Echo off
Title Remote Engine by Eddie Jackson
color 0a
Setlocal EnableDelayedExpansion


:: SET COMMAND
set fileName=Sequence.cmd
set fileOpt=
set workDir=c:\windows\system32
set hidden=No

Set PCList=computers.txt
:: or
Set PC=



:: INTERNAL 
:BEGIN
c:
cd "%~dp0"
set Script=False
for %%i in (%fileName%) do set cmdExt=%%~xi
set Interact=-i
if [%cmdExt%]==[.cmd] set Script=True
if [%cmdExt%]==[.CMD] set Script=True
if [%cmdExt%]==[.bat] set Script=True
if [%cmdExt%]==[.BAT] set Script=True
if [%cmdExt%]==[.vbs] goto VBS
if [%cmdExt%]==[.VBS] goto VBS
if [%hidden%]==[Yes] set Interact=

set cmdPath=%workDir%\%fileName%

:: CREATES DATE AND TIME TIMESTAMP
:: sets a static timestamp
for /F "tokens=2-4 delims=/- " %%p in ('date/T') do set mdate=%%r%%p%%q
for /F "tokens=1-2 delims=:- " %%p in ('time/T') do set mtime=%%p%%q
Set Report=logs\%mdate%_%mtime%_%report%.txt
md logs>nul
cls
if not [%PC%]==[] goto SINGLE
goto MULTI


:: PROGRAM ROUTINE
:MULTI
Echo.
Echo [Entering multi computer mode]
Echo.

if not exist "%PCList%" (
Echo Computers text file not found^^!
echo.
pause
exit
)

Set cmdRem=PAExec.exe \\%%a -s %Interact% -w %workDir% "%cmdPath%" %fileOpt%

for /f "tokens=* delims= " %%a in (%PCList%) do (

echo Contacting %%a...
ping %%a -w 250 | find "Reply">nul
if errorlevel 1 (echo %%a,Offline >>"%Report%"
) else ( 
echo %%a,Online >>"%Report%"

if %Script%==True copy /y %fileName% \\%%a\c$\windows\SysWOW64\%fileName%>nul

:: LAUNCH REMOTE COMMAND
echo Launching %cmdPath% on %%a...
%cmdRem%>nul && Echo %%a,Success >>"%Report%" || Echo %%a,Failed >>"%Report%"
echo.
)
)
goto END


:SINGLE
Echo.
Echo [Entering single computer mode]
Echo.

Set cmdRem=PAExec.exe \\%PC% -s %Interact% -w %workDir% "%cmdPath%" %fileOpt%

echo Contacting %PC%...
echo.
ping %PC% -w 250 | find "Reply">nul
if errorlevel 1 (echo %PC% is Offline^^!
) else ( 
echo %PC% is Online^^!
echo.

if %Script%==True copy /y %fileName% \\%PC%\c$\windows\SysWOW64\%fileName%>nul

:: LAUNCH REMOTE COMMAND
echo Launching %cmdPath% on %PC%...
echo.
%cmdRem%>nul && Echo Success^^! || Echo Failed^^!
echo.
goto END
)

:: EXIT
:END
Echo.
Echo Done^^!
pause
endlocal
exit /b 0


:VBS
Echo VBScripts are NOT SUPPORTED^^!
echo.
pause
exit

 

 

Notes

Run GPUpdate on List of Servers

FOR /F “tokens=*” %%A IN (C:\script\servers.txt) DO WMIC /Node:%%A Process call create “cmd.exe /c gpupdate”

$List = ‘server1′,’server2′,’server3′,’server4’
foreach ($server in $List) {psexec \\$server gpupdate}


Move to current directory

c:
cd “%~dp0”


Execute EXEs dynamically

@ECHO OFF
FOR /f “tokens=*” %%A IN (‘dir /b *.exe’) DO (
ECHO Filename: “%%A”
:: “%%A” /SILENTINSTALLOPTIONS
:: or
:: start “” “%%A”
)
pause

 

tags: Batch current directory, dir /b output, script engine, MrNetTek

LANDesk Client Elevated Repair – Proof of Concept

email me

I created a LANDesk Repair tool which can be used by any user to repair, reinstall, and fix issues related to the LANDesk client. The magic part of this is that it uses a public URL to download the LANDesk setup file, and then launches in an elevated mode using Microsoft’s SecureSubstring (the secure part was written in C#).

The advantage of having something like this, versus a package compiled with the LD setup file (172MB), is that the package is much smaller (less than a meg) and—if and when you change the LD setup—there is no need to recompile the package with the updated source file. Just drop the new source file at the URL, and anyone using the Repair Tool will automatically get the updated source file; this works for on site and off site users.

Originally, I just wanted to create a proof-of-concept prototype, but it worked so well, it was implemented.

Screenshot of my HTA

 

' ---------------------------------------------------------------' 
' Author:   Eddie Jackson
' File:     LANDesk_Repair.exe
' Purpose:  To repair or reinstall LANDesk
' Version:  1.0
' Date:     4/11/2017
'
' Usage:    Installed to C:\AFolderOfYourChoice
'           Accessed from Start Menu
' Notes
' Exit codes are 0 success, 1 no source file, 2 failed download
' ---------------------------------------------------------------' 


Option Explicit

'global declarations
Dim varHTTP, varBinaryString, setupFile, setupURL, uninstallFile, ComputerName, CurDir
Dim objShell, oldLANDesk, newLANDesk, msgFile, fso, objWMIService, cmd, colProcesses, Elevate



'Sequencing...
InitializeVariables()
CheckURL()
Download(setupFile)
Verify(setupFile)
Uninstall(oldLANDesk)
Install(newLANDesk)
ExitSequence(0)




sub InitializeVariables()
	on error resume next	
	
	'computer name
	ComputerName = "."

	CurDir = "C:\AFolderOfYourChoice"
	
	'message file
	msgFile = CurDir & "\ldmsg.dat"

	Set objShell = CreateObject("WScript.Shell")
	Set fso = CreateObject("Scripting.FileSystemObject")	
 
	Set varHTTP = CreateObject("Microsoft.XMLHTTP")
	Set varBinaryString = CreateObject("Adodb.Stream")
	
	setupFile = "Client_From_ldlogon_AdvanceAgent_Folder.exe"
	uninstallFile = "UninstallWinClient_From_LANDesk.exe"
	
        'tool I created to do elevation
        Elevate = CurDir & "\Elevate.exe -app" & " "
        'reference: http://eddiejackson.net/wp/?p=13815
	
	oldLANDesk = Elevate & chr(34) & CurDir & "\" & uninstallFile & chr(34) & " " & chr(34) & "/NOREBOOT /FORCECLEAN" & chr(34)
	newLANDesk = Elevate & chr(34) & CurDir & "\" & setupFile & chr(34)
	setupURL = "http://YourGateway_CSA_or_DMZ/" & setupFile

	varHTTP.Open "GET", setupURL, False
	varHTTP.Send
end sub


sub CheckURL()
    on error resume next
	'launch splash	
	Msg("Searching for download file...")	
	Splash()
	
	Select Case Cint(varHTTP.status)		
		Case 200, 202, 302			
			Msg("Found LANDesk download file!")			
			Exit Sub
		Case Else			
			Msg("LANDesk setup could not be found!")			
			ExitSequence(1)
	End Select
end sub


sub Download(dFile)
		on error resume next
		Msg("Downloading LANDesk file...")	
		With varBinaryString
			.Type = 1 'my type has been set to binary
			.Open
			.Write varHTTP.responseBody
			.SaveToFile ".\" & dFile, 2 'if exist, overwrite
		End With
		varBinaryString.close		
		Msg("LANDesk setup has been downloaded...")		
end sub


sub Uninstall(uCommand)
		on error resume next
		Msg("Removing old LANDesk setup...")	
		
		objShell.Run uCommand,0,True
		Wait(20)
		
		Monitor(uninstallFile)	
		Msg("LANDesk has been removed...")
end sub


sub Verify(vDownload)
	on error resume next
	Msg("Verifying file integrity...")
	
	If (fso.FileExists(CurDir & "\" & vDownload)) Then
		Msg("Download was successful!")
	Else
		Msg("Download failed!")
		ExitSequence(2)
	End If

end sub


sub Install(iCommand)
		on error resume next
		Msg("Installing LANDesk Client...")
		
		objShell.Run iCommand,0,True
		Wait(20)
		
		Monitor(setupFile)		
		Msg("LANDesk Client has been installed!")		
end sub


sub Wait(time)
	on error resume next
    time =  time * 1000
	WScript.Sleep time
end sub


sub Monitor(procName)

'secondary method to make sure wait for exit works
		Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")		
		cmd = 1
		
		Do While cmd = 1			
			Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '" & procName & "'")
			If colProcesses.Count = 0 Then
				on error resume next
				'Process is not running
				cmd = 0
				Wait(4)
			Else
				'Process is running
				cmd = 1
				Wait(30)		
			End If
		Loop				
end sub


sub Msg(message)
	on error resume next
	objShell.Run "cmd /c echo " & message & ">" & msgFile,0,true
	Wait(4)
end sub


sub Splash()
	on error resume next
	'a simple animation I made (ldhta.exe is mshta.exe)
        'you'll have to create your own little animation here
	objShell.Run CurDir & "\ldhta.exe " &  CurDir & "\ldprogress.hta",9,false
	Wait(8)
end sub


sub ExitSequence(errorcode)	
	Msg("Exiting...")
	Wait(4)
	objShell.Run "taskkill /f /im ldhta.exe",0,true	
	WScript.Quit(errorcode)
end sub

C# – Elevation of Applications, Runas (Jump)

email me

This is a work in progress, but I have created a program to elevate a specified application. The idea is, you need to run an application under a restricted user profile, but cannot because it requires admin privileges—this gets around that. The program also bypasses UAC! Written in C#. I use the SecureStringProcessStartInfo, and MemoryStream classes to do exactly what I needed—securely elevate an application. Originally written for Windows 7 (back in 2014) to only elevate executable files, but I’m adding support for Windows 10 and scripting languages as well.

Current Features
   
 --Accepts executables
 --Accepts batch files
 --Accepts any passed parameters for program
 --Accepts an AES string for password
 --Accepts an encrypted reg key for password
 --Option to wait for program to exit
 --Create tighter try/catches (done 04/11/2017)
 --Remove second console window on batch files (done 04/14/2017) 
 --Create more methods from existing code (done 04/11/2017)
 --Add logging in registry (done 11/29/2017)
 --Add logging in event log (done 11/29/2017)
 --Add VBScript support (done 12/15/2017)

Future Ideas

 --Add a required pin number for internal script use
 --Add domain support 

 

AES Information

AES has three fixed 128-bit block ciphers with cryptographic key sizes of 128, 192 and 256 bits. Key size is unlimited, whereas the block size maximum is 256 bits. The AES design is based on a substitution-permutation network (SPN) and does not use the Data Encryption Standard (DES) Feistel network.

In 1997, the NIST initiated a five-year algorithm development process to replace DES and Triple DES. The NIST algorithm selection process facilitated open collaboration and communication and included a close review of 15 candidates. After an intense evaluation, the Rijndael design, created by two Belgian cryptographers, was the final choice.

AES replaced DES with new and updated features:

  • Block encryption implementation
  • 128-bit group encryption with 128, 192 and 256-bit key lengths
  • Symmetric algorithm requiring only one encryption and decryption key
  • Data security for 20-30 years
  • Worldwide access
  • No royalties
  • Easy overall implementation

 

How doe AES work?

 

What does the diagram mean?

• AES is a block cipher with a block length of 128 bits.

• AES allows for three different key lengths: 128, 192, or 256 bits.

• Encryption consists of 10 rounds of processing for 128-bit keys, 12 rounds for 192-bit keys, and 14 rounds for 256-bit keys.

• Except for the last round in each case, all other rounds are identical.

• Each round of processing includes one single-byte based substitution step, a row-wise permutation step, a column-wise mixing.

• To appreciate the processing steps used in a single round, it is best to think of a 128-bit block as consisting of a 4 × 4 matrix of bytes, arranged as follows:

• Therefore, the first four bytes of a 128-bit input block occupy the first column in the 4 × 4 matrix of bytes. The next four bytes occupy the second column, and so on.  more on AES…

 

Screenshot of Jump tool in action

 

Screenshot of elevation working

 

The Code (click to view source code)


using System;
using System.IO;                      // used by MemoryStream
using System.Diagnostics;             // used by Process
using System.Linq;                    // used by ToArray
using System.Security;                // used by SecureString
using System.Text;                    // used by Encoding
using System.Security.Cryptography;   // used by aes
using Microsoft.Win32;                // used by registry
using System.Collections.Generic;     // used by List (quotes)
using System.Text.RegularExpressions;

namespace Jump
{
    class JumpUtil
    {

        //////////////////////////////////////////////////
        // See all class declarations at the bottom
        //////////////////////////////////////////////////

        //////////////////////////////////////////////////
        // See notes at the bottom
        //////////////////////////////////////////////////


        static void Main(string[] args)

        {

            // CONSOLE HEADER
            //----------------------------------------------------
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("\nJump v1.0.0.1 December 2017");
            Console.WriteLine("\nLaunch Windows-based applications in elevated mode");
            Console.WriteLine("\nEddie Jackson | mrnettek@gmail.com | eddiejackson.net");
            Console.WriteLine("\nUsage: -app \"notepad.exe\" -opt \"name.txt\" -secure \"rEqnfiteGwLsktuW==\" -wait\n");

            // QUOTE
            // returns the random quote
            SubQuote();


            // BEGIN
            // load items into array
            // this loads arguments from the command line into an array
            foreach (string s in args)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    array = args[i].ToString();
                }

                // contains contents of array
                arrayString = arrayString + s.ToString() + " ";
            }
            // END - LOAD ITEMS INTO ARRAY            


            // SPACES
            // initialized to detect spaces and assign variables accordingly 
            // regex wasn't working properly when I added spaces
            string inputstring = arrayString.ToString();
            string[] inputstringarray = inputstring.Split(' ');



            // APP
            // does the command line contain the -app parameter?
            if (arrayString.Contains(parameterApp))
            {
                // found the -app parameter
                returnIndex = Array.IndexOf(inputstringarray, parameterApp);
                returnedApp = args[returnIndex + 1];                
               
                //returnedApp = FindNextValue(arrayString, parameterApp);  // regex doesn't work right. Disabled for now.
                if (returnedApp != parameterSecure &&
                    returnedApp != parameterOpt &&
                    returnedApp != parameterWait &&
                    returnedApp != "")
                {
                    appName = returnedApp;
                }
            }
            else
            {
                // the -app parameter is completely missing
                Messenger(Message1);
                Environment.Exit(6);
            }


            // OPTION
            // does the command line contain the -opt parameter?
            // I use string[] and IndexOf to read spaces in the options parameter
            // regex wasn't working properly when I added spaces
            if (arrayString.Contains("-opt"))
            {
                // found the -opt parameter
                returnIndex = Array.IndexOf(inputstringarray, parameterOpt);

                // return what follows the -opt parameter
                returnedOpt = args[returnIndex + 1];
                // accommodate extra spaces in file name - useful for vbs files
                if (returnedOpt == parameterSecure) {
                        returnedOpt = args[returnIndex + 0];
                    }

                // make sure returnedOpt isn't the AES variable
                if (returnedOpt.Contains("=="))
                {                    
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("\n\nMissing data from the -opt parameter!\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Environment.Exit(6);
                }               

                // validate return option meets conditions
                if (
                    returnedOpt != parameterSecure &&
                    returnedOpt != parameterApp &&
                    returnedOpt != parameterWait &&
                    returnedOpt != "")
                {
                    // set options
                    appOpt = returnedOpt;               

                }
                else {

                    
                    // check for data following -opt parameter
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("\n\nMissing data from the -opt parameter!\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Environment.Exit(6);
                }

            }



            // SECURE
            // does the command line contain the -secure parameter?
            if (arrayString.Contains(parameterSecure))
            {
                // found the -secure parameter
                returnedSecure = FindNextValue(arrayString, parameterSecure);
                if (returnedSecure != parameterApp &&
                    returnedSecure != parameterOpt &&
                    returnedSecure != parameterWait &&
                    returnedSecure != "")
                {
                    appPassword = (Decrypt(returnedSecure.ToString()));
                }
                else {

                    // check for data following -secure parameter
                    Messenger(Message2);
                    Environment.Exit(6);                    
                }
            }
            else
            {
                // the -secure parameter is completely missing                
                Messenger(Message6);                
                Environment.Exit(6);
            }
         

            // WAIT
            // does command line contain the -wait parameter?
            if (arrayString.Contains(parameterWait))
            {
                // found the -wait parameter
                appWait = "True";
            }
            else
            {
                // did not find the -wait parameter
                appWait = "False";

            }
            
            
            // DETERMINE FILE TYPE 
            // mostly made for handling batch files
            // had no issues with EXEs
            //----------------------------------------------------
            string retVBS = "FALSE";
            string retBAT = "FALSE";            
            string extension = Path.GetExtension(appName);

            if (extension.ToLower() == ".cmd") { retBAT = "TRUE"; }
            if (extension.ToLower() == ".bat") { retBAT = "TRUE"; }
            if (extension.ToLower() == ".vbs") { retVBS = "TRUE"; }            


            // BEGIN - ELEVATED APP LAUNCH            
            // use SecureString
            //----------------------------------------------------

            SecureString securePassword = new SecureString();
            Array.ForEach(appPassword.ToArray(), securePassword.AppendChar);
            securePassword.MakeReadOnly();

            // instantiate process from Process
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                // set up default properties
                UserName = appUser,
                Domain = "",
                Password = securePassword,
                LoadUserProfile = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };


            // CMD, BAT
            // IF A BATCH FILE, DO THIS
            // the reason I created this was because there is
            // an EXTRA black window when launching batch files 
            // using SecureString :: quite annoying MS hasn't 
            // done something about this
            //----------------------------------------------------
            if (retBAT == "TRUE")
            {
                try
                {
                    // DOES THE FILE EXIST???
                    if (!File.Exists(appName))
                    {
                        Messenger(Message10);
                        Environment.Exit(4);
                    }

                    startInfo.FileName = @"C:\Windows\SysWOW64\Wscript.exe";
                    startInfo.Arguments = "_hide.vbs";

                    string path = "_hide.vbs";
                    string text0 = "On error resume next:";
                    File.WriteAllText(path, text0);

                    // builds the vbscript
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        string text1 = "";
                        string text2 = "";

                        if (appOpt != "")
                        {
                            // with option                            
                            text1 = "Set WshShell = CreateObject(\"WScript.Shell\"):";
                            text2 = "WshShell.Run chr(34) & " + "\"" + appName + "\"" + " & chr(34) & \" \" & chr(34) & " + "\"" + appOpt + "\"" + " & chr(34)" + ",0, true";
                                                       
                        }
                        else {
                            // without option                            
                            text1 = "Set WshShell = CreateObject(\"WScript.Shell\"):";
                            text2 = "WshShell.Run chr(34) & " + "\"" + appName + "\"" + " & chr(34)" + ",0, true";
                                                      
                        }

                        // writes the vbs to file
                        sw.WriteLine(text1);
                        sw.WriteLine(text2);
                    }

                    // instantiates the process
                    process = Process.Start(startInfo);

                    // checks to see if -wait is true
                    if (appWait == "True") { process.WaitForExit(); }

                    Console.ForegroundColor = ConsoleColor.Green;                    
                    Console.WriteLine("\nGreat Success!\n");
                    Console.ForegroundColor = ConsoleColor.White;

                    System.Threading.Thread.Sleep(1000);

                    // if this gets lost, I'll probably just add a %temp% path
                    if (File.Exists("_hide.vbs"))
                    {
                        File.Delete("_hide.vbs");
                    }
                    Audit();
                    Environment.Exit(0);
                }

                catch (Exception)
                {
                    Messenger(Message8);
                }
            }



            // VBS
            // IF A VBSCRIPT FILE, DO THIS
            //----------------------------------------------------
            if (retVBS == "TRUE")
            {
                try
                {
                    // DOES THE FILE EXIST???
                    if (!File.Exists(appName))
                    {
                        Messenger(Message10);
                        Environment.Exit(4);
                    }

                    startInfo.FileName = @"C:\Windows\SysWOW64\Wscript.exe";

                    if (appOpt != "")
                    {
                        //startInfo.Arguments = appName + " " + "\"" + appOpt + "\"";
                        startInfo.Arguments = "\"" + appName + "\"" + " " + "\"" + appOpt + "\"";
                        process = Process.Start(startInfo);                        
                        
                    }
                    else
                    {
                        startInfo.Arguments = "\"" + appName + "\"";
                        process = Process.Start(startInfo);
                    }

                    

                    if (appWait == "True") { process.WaitForExit(); }

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\nGreat Success!\n");
                    Console.ForegroundColor = ConsoleColor.White;

                    System.Threading.Thread.Sleep(1000);
                    
                    Audit();
                    Environment.Exit(0);                    
                }
                catch (Exception)
                {
                    Messenger(Message8);
                }
            }


            // EXE
            // IF AN EXECUTABLE FILE, DO THIS
            //----------------------------------------------------

            // does app exist?                

            try
            {
                // I have added a little bit of extra logic for EXEs, specifically 'system' EXEs that may be in Windows or System32 folders
                // I append the .EXE and relative system paths just as an extra feature to find 'known' EXEs. Otherwise, EXEs like ping, 
                // calc, notepad, net, reg, etc., would fail without the path being explicitly defined
                if (!File.Exists(appName) && (!File.Exists(appName + ".exe")))
                {
                    if (!File.Exists("C:\\Windows\\" + appName + ".exe") && (!File.Exists("C:\\Windows\\" + appName)))
                    {
                        if (!File.Exists("C:\\Windows\\system32\\" + appName + ".exe") && (!File.Exists("C:\\Windows\\system32\\" + appName)))
                        {
                            Messenger(Message10);
                            Environment.Exit(4);
                        }
                    }
                }


                startInfo.FileName = appName;                
                if (appOpt != "") { startInfo.Arguments = "\"" + appOpt  + "\""; }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Elevating...");
                Console.ForegroundColor = ConsoleColor.White;

                process = Process.Start(startInfo);                

                if (appWait == "True") { process.WaitForExit(); }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("\nGreat Success!\n");
                Console.ForegroundColor = ConsoleColor.White;
                Audit();
                Environment.Exit(0);
            }

            catch (Exception)
            {
                Messenger(Message8);
            }


        }
        // END - ELEVATED APP LAUNCH


        // RETURN NEXT VALUE        
        public static string FindNextValue(string inputArray, string inputSearch)
        {
            sNext = "";

            if (arrayString.Contains(inputSearch))
            {

                string[] sRegX = Regex.Split(inputArray, @"[^’a-zA-Z0-9\\\:\=\-\._]+");

                int index = Array.IndexOf(sRegX, inputSearch);
                if (index < sRegX.Count() - 1)
                    sNext = sRegX[index + 1];
            }

            return sNext;
        }

        
        // BASIC LOGGING
        static void Audit()
        {
            // create registry key

            string reg1 = "HKEY_CURRENT_USER";
            string reg2 = @"SOFTWARE\Jump\";
            string regPath = reg1 + @"\" + reg2;
            string UName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            string regVal = appName + " " + UName;
            
            DateTime dt = DateTime.Now;
            Registry.SetValue(regPath, dt.ToString(), regVal, RegistryValueKind.String);

            
            // log event

            string sSource;
            string sLog;
            string sEvent;

            sSource = "Jump.exe";
            sLog = "Application";
            
            sEvent = appName + " was installed using the Jump tool by " + UName;

            if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);

            EventLog.WriteEntry(sSource, sEvent);

            // output to console
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("{{{ Security log has been updated }}}\n");
            Console.ForegroundColor = ConsoleColor.Gray;
        }
                    


        
        // Just show header of jump util

        static void Help()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Environment.Exit(0);
        }

        // import and show message
        static void Messenger(string message)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\n{0}\n", message);
            Console.ForegroundColor = ConsoleColor.White;
            Environment.Exit(2);
        }


        // returns random quote
        static void SubQuote()
        {
            QuoteGenerator quoteGenerator = new QuoteGenerator();
            string retQuote = quoteGenerator.ReturnRandomQuote();
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("{0}\n", retQuote);
            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.White;
        }

       
       
        // decoding
        public static string Decrypt(string strData)
        {
            try
            {
                if ((strData.Length % 4) == 0)
                {
                    //aes string length is good
                    return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(strData)));
                }

                Messenger(Message9);
                Environment.Exit(6);             
                return null; 

            }
            catch (Exception)
            {
                Messenger(Message9);
                Environment.Exit(6);                
                return null; // prevents return error message
            }         
}

        // decrypt
        public static byte[] Decrypt(byte[] strData)
        {

            try
            {
                PasswordDeriveBytes passbytes =
                new PasswordDeriveBytes(strPermutation,
                new byte[] {            bytePermutation1,
                                        bytePermutation2,
                                        bytePermutation3,
                                        bytePermutation4
                //Reference: https://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
            });
                

                MemoryStream memstream = new MemoryStream();
                Aes aes = new AesManaged();
                aes.Key = passbytes.GetBytes(aes.KeySize / 8);
                aes.IV = passbytes.GetBytes(aes.BlockSize / 8);
                //Reference: https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged(v=vs.110).aspx

                CryptoStream cryptostream = new CryptoStream(memstream,
                aes.CreateDecryptor(), CryptoStreamMode.Write);
                cryptostream.Write(strData, 0, strData.Length);
                cryptostream.Close();
                return memstream.ToArray();
                //Reference: https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream(v=vs.110).aspx
            }
            catch (Exception)
            {
                Messenger(Message8);
                Environment.Exit(6); // exits in case the password fails
                //return strData;
                return null; // prevents return error message
            }

        }

        class QuoteGenerator
        {
            Random random = new Random();
            List<string> Quotes = new List<string>();

            public QuoteGenerator()
            {
                Quotes.Add("Intelligence is the ability to adapt to change - Stephen Hawking");
                Quotes.Add("Nothing endures but change - Heraclitus");
                Quotes.Add("Dream big and dare to fail - Normal Vaughan");
                Quotes.Add("If it doesn’t challenge you, it won’t change you - Fred DeVito");
                Quotes.Add("Genius is talent set on fire by courage Henry Van Dyke");
                Quotes.Add("Energy and persistence conquer all things - Benjamin Franklin");
                Quotes.Add("The secret of getting ahead is getting started - Mark Twain");
                Quotes.Add("The measure of who we are is what we do with what we have - Vince Lombardi");
                Quotes.Add("With self-discipline most anything is possible - Theodore Roosevelt");
                Quotes.Add("The price of greatness is responsibility - Winston Churchill");
                Quotes.Add("Action is the foundational key to all success - Picasso");
                Quotes.Add("Try not to become a man of success, but rather a man of value - Albert Einstein");
                Quotes.Add("Learning never exhausts the mind - Leonardo da Vinci");
            }

            public string ReturnRandomQuote()
            {
                int quoteCount = Quotes.Count;
                int randomNumber = random.Next(0, (quoteCount - 1));
                return Quotes[randomNumber];
            }
        }


        // the admin user account name
        public const string appUser = "Administrator";        

        // use these permutations - change these
        public const string strPermutation = "eqyshqfqhjk";
        public const int bytePermutation1 = 0x11;
        public const int bytePermutation2 = 0x19;
        public const int bytePermutation3 = 0x17;
        public const int bytePermutation4 = 0x11;

        public const string strRegHive = "HKEY_LOCAL_MACHINE";
        public const string strRegKey = @"SOFTWARE\Serial\";
        public const string strRegPath = strRegHive + @"\" + strRegKey;
        public const string strRegVal = "Serial1";

        // general console messages
        public const string Message1 = "Slow down there, Skippy. Did you forget the -app parameter?";
        public const string Message2 = "Ohhh, man...did you forget to add the AES string?";
        public const string Message3 = "Yo, where is the -opt parameter? Use -opt.";
        public const string Message4 = "Wait a minute. Looks like -wait is missing.";
        public const string Message5 = "Hey, dude, you forgot to enter an app name.";
        public const string Message6 = "Houston, we have a problem. Did you forget to add the -secure parameter?";
        public const string Message7 = "Too much, man...too much. You have too much in the command line.";
        public const string Message8 = "Hold on, Chief. This isn't good...the app wasn't elevated.";
        public const string Message9 = "Come on man...the AES string is too short.";
        public const string Message10 = "The file seems to have taken a vacation. It can't be found!";        

                
        // the array, working space
        public static string array = "";

        // the items in the array
        public static string arrayString = "";

        // appVar(i) becomes appName, appOpt, appWait, appPassword            
        public static string appPassword = "";
        public static string appName = "";
        public static string appOpt = "";
        public static string appWait = "";
        private static string sNext;

        public static string parameterApp = "-app";
        public static string parameterWait = "-wait";
        public static string parameterOpt = "-opt";
        public static string parameterSecure = "-secure";        
        public static string returnedApp = "";
        public static string returnedSecure = "";
        public static string returnedOpt = "";
        public static int returnIndex;
    }

}

/*NOTES

       SPACES IN THE DECRYPT STRING
       64-bit encoding does not work well with spaces in the string for some odd reason. 
       Add the following: stringToDecrypt = stringToDecrypt.Replace(" ","+");
       before this line "int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);"
       to replace blank spaces with '+'. Plus sign will be interpreted as a space when you call the FromBase64String method.

       EXTRA BLACK WINDOW (CONSOLE WINDOW)
       When using SecureString, and passing a username and password to a BATCH file process, an EXTRA black window appears.
       The window is tied to the batch file :-( , and from what I can tell, cannot be so easily hidden. Yes, you can hide the main
       process window, but not the child window. If you close the child window, it kills the batch file. Arrrrrg.
       I was able to create a workaround using VBS output and hiding the batch process, but I will be looking for a better solution.

*/



 

Screenshot of Visual Studio (click to zoom)

* no longer uses a password – I’m passing in an AES string

Fun Fact

It would take a supercomputer 1 billion billion years to crack the 128-bit AES key using brute force attack. This is more than the age of the universe (13.75 billion years).

VBScript – Translating Characters that have been Substituted

email me

This is the second part of a substitution program I wrote (this is the decoder portion); the first part was in C# (the encoder). Originally, I wrote both parts in C#, but had people asking me for something that did not require compiling to use in their scripts, so I created this VBScript. The idea is…the encoded string is accepted by the script and then translated into its original form.

This script could be utilized for encoding and decoding if you reverse (or create a function to reverse) the translation sequences (permutations).

Note, you want to make sure you change the sequences, to provide a level of uniqueness for your environment.

 

Option Explicit

Dim strShift, strPassword, WshShell, bufferLength, i, retValue

Set WshShell = WScript.CreateObject("WScript.Shell")


'Verify if reg key exists
KeyExists "SOFTWARE\Wow6432Node\ZWT", "ZWT1"
if retValue = "False" then WScript.Quit(1)

'Return Password
Translate()

'strPassword is translated password
'this will be what is used for elevated apps
msgbox strPassword

WScript.Quit()


'do not edit below this line unless changing permutations
'---------------------------------------------------
sub Translate()

'clip or output file could be used to grab output
CreateObject("WScript.Shell").Run "cmd /c RegRead.exe | clip", 0, True

strShift = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")
strShift = trim(strShift)
strShift = replace(strShift,chr(13),"")

Dim buffer()
bufferLength = Len(strShift)
ReDim buffer(bufferLength)
For i = 1 To Len(strShift)
buffer(i) = Mid(strShift,i,1)

Do While True
if buffer(i) = "O" then buffer(i) = "A" : exit do
if buffer(i) = "K" then buffer(i) = "B" : exit do
if buffer(i) = "I" then buffer(i) = "C" : exit do
if buffer(i) = "R" then buffer(i) = "D" : exit do
if buffer(i) = "B" then buffer(i) = "E" : exit do
if buffer(i) = "H" then buffer(i) = "F" : exit do
if buffer(i) = "P" then buffer(i) = "G" : exit do
if buffer(i) = "W" then buffer(i) = "H" : exit do
if buffer(i) = "J" then buffer(i) = "I" : exit do
if buffer(i) = "V" then buffer(i) = "J" : exit do
if buffer(i) = "G" then buffer(i) = "K" : exit do
if buffer(i) = "A" then buffer(i) = "L" : exit do
if buffer(i) = "C" then buffer(i) = "M" : exit do
if buffer(i) = "T" then buffer(i) = "N" : exit do
if buffer(i) = "N" then buffer(i) = "O" : exit do
if buffer(i) = "Q" then buffer(i) = "P" : exit do
if buffer(i) = "U" then buffer(i) = "Q" : exit do
if buffer(i) = "E" then buffer(i) = "R" : exit do
if buffer(i) = "F" then buffer(i) = "S" : exit do
if buffer(i) = "Y" then buffer(i) = "T" : exit do
if buffer(i) = "D" then buffer(i) = "U" : exit do
if buffer(i) = "Z" then buffer(i) = "V" : exit do
if buffer(i) = "S" then buffer(i) = "W" : exit do
if buffer(i) = "L" then buffer(i) = "X" : exit do
if buffer(i) = "M" then buffer(i) = "Y" : exit do
if buffer(i) = "X" then buffer(i) = "Z" : exit do

if buffer(i) = "o" then buffer(i) = "a" : exit do
if buffer(i) = "k" then buffer(i) = "b" : exit do
if buffer(i) = "i" then buffer(i) = "c" : exit do
if buffer(i) = "r" then buffer(i) = "d" : exit do
if buffer(i) = "b" then buffer(i) = "e" : exit do
if buffer(i) = "h" then buffer(i) = "f" : exit do
if buffer(i) = "p" then buffer(i) = "g" : exit do
if buffer(i) = "w" then buffer(i) = "h" : exit do
if buffer(i) = "j" then buffer(i) = "i" : exit do
if buffer(i) = "v" then buffer(i) = "j" : exit do
if buffer(i) = "g" then buffer(i) = "k" : exit do
if buffer(i) = "a" then buffer(i) = "l" : exit do
if buffer(i) = "c" then buffer(i) = "m" : exit do
if buffer(i) = "t" then buffer(i) = "n" : exit do
if buffer(i) = "n" then buffer(i) = "o" : exit do
if buffer(i) = "q" then buffer(i) = "p" : exit do
if buffer(i) = "u" then buffer(i) = "q" : exit do
if buffer(i) = "e" then buffer(i) = "r" : exit do
if buffer(i) = "f" then buffer(i) = "s" : exit do
if buffer(i) = "y" then buffer(i) = "t" : exit do
if buffer(i) = "d" then buffer(i) = "u" : exit do
if buffer(i) = "z" then buffer(i) = "v" : exit do
if buffer(i) = "s" then buffer(i) = "w" : exit do
if buffer(i) = "l" then buffer(i) = "x" : exit do
if buffer(i) = "m" then buffer(i) = "y" : exit do
if buffer(i) = "x" then buffer(i) = "z" : exit do

if buffer(i) = "7" then buffer(i) = "0" : exit do
if buffer(i) = "4" then buffer(i) = "1" : exit do
if buffer(i) = "9" then buffer(i) = "2" : exit do
if buffer(i) = "5" then buffer(i) = "3" : exit do
if buffer(i) = "3" then buffer(i) = "4" : exit do
if buffer(i) = "6" then buffer(i) = "5" : exit do
if buffer(i) = "0" then buffer(i) = "6" : exit do
if buffer(i) = "1" then buffer(i) = "7" : exit do
if buffer(i) = "2" then buffer(i) = "8" : exit do
if buffer(i) = "8" then buffer(i) = "9" : exit do

if ASC(buffer(i)) = ASC("$") then buffer(i) = CHR(ASC("?")) : exit do
if ASC(buffer(i)) = ASC("?") then buffer(i) = CHR(ASC("$")) : exit do

if ASC(buffer(i)) = ASC("~") then buffer(i) = CHR(ASC("@")) : exit do
if ASC(buffer(i)) = ASC("@") then buffer(i) = CHR(ASC("~")) : exit do

if ASC(buffer(i)) = ASC("%") then buffer(i) = CHR(ASC("!")) : exit do
if ASC(buffer(i)) = ASC("!") then buffer(i) = CHR(ASC("%")) : exit do

if ASC(buffer(i)) = ASC("-") then buffer(i) = CHR(ASC("#")) : exit do
if ASC(buffer(i)) = ASC("#") then buffer(i) = CHR(ASC("-")) : exit do

if ASC(buffer(i)) = ASC("*") then buffer(i) = CHR(ASC("(")) : exit do
if ASC(buffer(i)) = ASC("(") then buffer(i) = CHR(ASC("*")) : exit do

if ASC(buffer(i)) = ASC("&") then buffer(i) = CHR(ASC("'")) : exit do
if ASC(buffer(i)) = ASC("'") then buffer(i) = CHR(ASC("&")) : exit do

if ASC(buffer(i)) = ASC("_") then buffer(i) = CHR(ASC(")")) : exit do
if ASC(buffer(i)) = ASC(")") then buffer(i) = CHR(ASC("_")) : exit do

if ASC(buffer(i)) = ASC("^") then buffer(i) = CHR(ASC("+")) : exit do
if ASC(buffer(i)) = ASC("+") then buffer(i) = CHR(ASC("^")) : exit do

if ASC(buffer(i)) = ASC("`") then buffer(i) = CHR(ASC(".")) : exit do
if ASC(buffer(i)) = ASC(".") then buffer(i) = CHR(ASC("`")) : exit do

if ASC(buffer(i)) = ASC(",") then buffer(i) = CHR(ASC("=")) : exit do
if ASC(buffer(i)) = ASC("=") then buffer(i) = CHR(ASC(",")) : exit do

if ASC(buffer(i)) = ASC("\") then buffer(i) = CHR(ASC("/")) : exit do
if ASC(buffer(i)) = ASC("/") then buffer(i) = CHR(ASC("\")) : exit do

if ASC(buffer(i)) = ASC(">") then buffer(i) = CHR(ASC("<")) : exit do
if ASC(buffer(i)) = ASC("{") then buffer(i) = CHR(ASC("}")) : exit do

if ASC(buffer(i)) = ASC("}") then buffer(i) = CHR(ASC("{")) : exit do
if ASC(buffer(i)) = ASC("<") then buffer(i) = CHR(ASC(">")) : exit do

if ASC(buffer(i)) = ASC("]") then buffer(i) = CHR(ASC("[")) : exit do
if ASC(buffer(i)) = ASC("[") then buffer(i) = CHR(ASC("]")) : exit do

if ASC(buffer(i)) = ASC(";") then buffer(i) = CHR(ASC(":")) : exit do
if ASC(buffer(i)) = ASC("|") then buffer(i) = CHR(ASC("|")) : exit do

if ASC(buffer(i)) = ASC(":") then buffer(i) = CHR(ASC("""")) : exit do
if ASC(buffer(i)) = ASC("""") then buffer(i) = CHR(ASC(":")) : exit do
exit do
loop
Next

strPassword = ""

For i = 0 to bufferLength
strPassword = strPassword & buffer(i)
Next

CreateObject("WScript.Shell").Run "cmd /c echo. | clip", 0, True

end sub


sub KeyExists(RegPath, RegKey)
	Const HKEY_LOCAL_MACHINE = &H80000002
	Dim strComputer, objRegistry, RegValue, objWshShell	

	Set objWshShell = CreateObject("WScript.shell")
	
	strComputer = "."
	Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

	objRegistry.GetStringValue HKEY_LOCAL_MACHINE,RegPath,RegKey,RegValue
	
	If Not IsNull(RegValue) Then
	    retValue = True
	Else
	    retValue = False
	End If	
end sub

Batch – LANDesk Local Admin Password Change (Obfuscation)

email me

Simple LANDesk Delivery Script (to be compiled)

This can be used by LANDesk to reset the local admin password. I have added the encrypted reg key for elevated apps.

Only deploy compiled scripts! I use ExeScript.

@echo on
title Local Admin Password Reset
cls
color 0a

call :SHIFTER

Set Cypher=tU2igtOeEfJxRfK43bDTDw==
set RegPath=HKLM\SOFTWARE\Wow6432Node\ZYT
set SysPath=C:\Windows\system32

:START
:: Set password using shifter variables
%SysPath%\NET USER Administrator "%P4%%P1%%P2%%P5%%P2%%P6%%P3%%P6%" && goto NEXT || goto END

:NEXT
:: Remove old cypher
%SysPath%\REG DELETE "%RegPath%" /f /REG:64
goto END

:: Add new cypher. Used for SecureString - Elevated apps
%SysPath%\REG ADD "%RegPath%" /v ZYT1 /t REG_SZ /d "%Cypher%" /f /REG:64

:END
exit /b 0

:SHIFTER
:: Scramble the password here
set P0=a
set P1=g
set P2=#
set P3=0
set P4=A
set P5=I
set P6=e
set P7=B
set P8=v
set P9=D

VBScript – Check to See if Web File exists, Download It

email me

Dim varHTTP, varBinaryString, varFileName, varLink

set objShell = CreateObject("WScript.Shell")
 
Set varHTTP = CreateObject("Microsoft.XMLHTTP")
Set varBinaryString = CreateObject("Adodb.Stream")

varFileName = "Foo.exe"
varLink = "http://TheWebURL/" & varFileName
varHTTP.Open "GET", varLink, False
varHTTP.Send


'Sequencing...
CheckFile()
DownloadFile()

'add other stuff to do here


sub CheckFile()
	Select Case Cint(varHTTP.status)
		Case 200, 202, 302 
			'it exists
			msgbox "File exists!"
			Exit Sub
		Case Else
			'does not exist			
			msgbox "File does not exist!"
			WScript.quit
	End Select
end sub

sub DownloadFile()
		With varBinaryString
			.Type = 1 'my type has been set to binary
			.Open
			.Write varHTTP.responseBody
			.SaveToFile ".\" & varFileName, 2 'if exist, overwrite
		End With
		varBinaryString.close
		msgbox "Download complete!"
end sub

 
Notes

200 – OK (standard successful http request)
202 – Accepted (request accepted for processing, but not completed)
302 – Found (via redirection)