JScript: How to get elevated privileges (admin rights) - jscript

Writing to certain folders and sections of the registry is only possible if a program runs elevated. Since you can't give JScript files a manifest that tells the OS which privileges the application wants, the question is do you work around that?

The solution is to check if you are running elevated on every start of the script and if you are not, then start a new instance of the script elevated and terminate the old instance.
EnsureElevatedPrivileges();
WScript.Echo("Running elevated now!");
function EnsureElevatedPrivileges() {
if (!WScript.Arguments.Named.Exists("elevate")) {
new ActiveXObject("Shell.Application").ShellExecute(WScript.FullName, "\"" + WScript.ScriptFullName + "\" /elevate", "", "runas", 1);
WScript.Quit();
}
}

Related

npm open is not working while deploying it in server?

I have a nodejs code where at some point it uses a new tab for showing results.I got npm-open where it show my result in a new tab of the browser.But when i deploy it in a linux server, its neither opening a new tab nor throwing any error?
open( req.protocol + '://' + req.get('host')+"/view-document/?logos="+ logos+"&comp_name="+result_3[0].name +"&emp_name="+empname+"&start_date="+sdates+"&end_date="+edates+"&position="+designation+"&template=template1"+"&emp_id="+emp_id+"&issue_date="+issue_date+"&title="+title, function (err) {
if ( err ) {
res.redirect("/view-document/?logos=" + logos+"&comp_name="+result_3[0].name +"&emp_name="+empname+"&start_date="+sdates+"&end_date="+edates+"&position="+designation+"&template=template1"+"&emp_id="+emp_id+"&issue_date="+issue_date+"&title="+title);
return;
}
});
How could it?
The open command is a way to make your script interact with the OS it is running on, telling it to open a URL, image, etc. If you run your script on your local machine, this is fine and works as expected.
If you run your script on a server, there is no way it can communicate its request to your local machine. Think about it – should a random webpage/server have the ability to interact with the OS on client machines?
To make something like this work, you will need to split your script into two parts:
the parts that should reside on the server
the utility script which will communicate with the server and, when needed, run the open command

Elevating NodeJS ChildProcess created with child_process.fork()

I'm developing an electron application which downloads software. For users who target "Program Files" however, the installation needs to run with administrator permissions.
I'm creating a child process in which the installer runs using child_process.fork(), and am depending on the IPC connection for the ability to send and receive messages.
Unfortunately however, I can't find any way to elevate this process. Some libraries (such as node-windows) use child_process.exec() under the hood, but this doesn't create the IPC connection.
What is the best way to go about this?
The simplest option is to run the whole app as administrator.
You can force (or, politically correct,remind) user to run as admin.
E.g. in electron-builder with "requestedExecutionLevel": "requireAdministrator"
If you want to elevate only child process, you can either make this child process smart enough to ask for elevation, or use an 'elevator', extra program which will ask for the elevation.
Node-windows does that with VBS script
electron-react-boileplate does that with pre-compiled program elevate
Also node-powershell supports executing commands, if necessary, with elevation (basic powershell).
As for IPC, what are you after? child_process.exec buffers the output, while child_proces.spawn gives it to you in a stream-like manner (see child process)
You just need to provide a callback with the correct arguments.
Example from child process:
const { exec, spawn } = require('child_process');
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});

Application throws an error when launched from task scheduler

I have a custom application which uses Microsoft.Office.Interop.Excel.Application to open and save excel file. I have a batch which fires the app with all the required parameters. That batch completes the task successfully when run manually but when I tried to schedule the same in task scheduler I got the following error msg logged from ma app:
Microsoft Office Excel cannot access the file
'E:\tasks\extractSPdocs\downloads\Last_Minute_IT_DATA_DUMP_201404250000.xls'.
There are several possible reasons:
The file name or path does not exist. The file is being used by
another program. The workbook you are trying to save has the same
name as a currently open workbook.
I know the error is thrown from the following code section:
try
{
excelfile = new Microsoft.Office.Interop.Excel.Application();
excelfile.DisplayAlerts = false;
var wb = excelfile.Workbooks.Open(dirpath + "\\" + csvname);
wb.SaveAs(dirpath + "\\" + csvname.Substring(0, csvname.LastIndexOf('.')), Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
csvname = csvname.Substring(0, csvname.LastIndexOf('.')) + ".xlsx";
csvext = ".xlsx";
}
The task is created with the same account I am using (local admin).
It is set to run with highest privileges and to start in the batch file directory.
The OS is Windows Server 2008.
I do not know why this is failing but suspect this has something to do with the context in which the scheduler launches my application which then subsequently launches Excel. Can anybody suggest a solution?
I have found a solution here http://justgeeks.blogspot.co.uk/2012/10/troubleshooting-microsoft-excel-cannot.html
the trick is you have to craete this folder:
C:\Windows\SysWOW64\config\systemprofile\Desktop
I must admit I do not quite understand why this folder is required for excel to open files when launched by task scheduler but it works.
Actually I haven't tried the answer by #Maju but this Superuser question has a solution which worked for me: you have to config DCOM. I set the identity to run Excel to the identity which I'm using in the Task Scheduler.
https://superuser.com/questions/579900/why-cant-excel-open-a-file-when-run-from-task-scheduler
I added the following directory c:\windows\syswow64\config\systemprofile\desktop

How to debug ASP permission problems with WScript.Shell object?

I have to run command line operation from some legacy ASP application.
Here is my code:
<%
cmd = "%comspec% /c echo Hello"
set wsh = CreateObject("WScript.Shell")
ireturn = wsh.Run(cmd, 0, true)
set wsh = nothing
%>
And here is result I am receiving:
Microsoft VBScript runtime error
'800a0046'
Permission denied
/test.asp, line 6
Do you have any idea how to make IIS6 to run this code?
Note: Of course I don't have to run echo command but I want to exclude any additional causes of the problem.
Update: I tried most things tomalaks mention however nothing helped. Maybe I can alter question a little. How can I debug this problem?
ASP usually is denied access to anything potentially dangerous, such as cmd.exe. Check file permissions on cmd.exe to see if that is true for you (I suppose it is).
If you really must use cmd.exe to do part of the page processing, either change file permissions on cmd.exe (not recommended for an Internet-facing web-server), or make sure that the ASP page runs credentials that are not denied access to that file.
To achieve this, use the IIS management console to remove "anonymous access" to the ASP page and use Windows-integrated authentication instead (if feasible), or leave "anonymous access" on and enter a fixed set of credentials that should be used instead of the default "IUSR_...".
Alternatively, if you use cmd.exe just to start a program that outputs something to STDOUT, you can try starting the program directly, without wrapping it in a cmd.exe call. Again, the user the ASP page runs under needs access to that program's executable.

Sharepoint: executing stsadm from a timer job + SHAREPOINT\System rights

I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have SHAREPOINT\System SharePoint privileges.
I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run stsadm.
Another problem with running the timer service under local administrator is that this user won't necessarily have SHAREPOINT\System SharePoint privileges which I also need for this SharePoint job. It turns out that SPSecurity.RunWithElevatedPrivileges won't work in this case. Reflector shows that RunWithElevatedPrivileges checks if the current process is owstimer (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under NT AUTHORITY\NetworkService windows account which which has SHAREPOINT\System SharePoint privileges, and thus there's no need to elevate privileges for a timer job).
The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password.
It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case):
The application failed to initialize properly (0x0c0000142).
Click OK to terminate the application.
Event Viewer registers nothing except the popup.
The local administrator user is my account and when I just run stsadm interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account.
Any suggestions are appreciated :)
I'm not at work so this is off the top of my head, but: If you get a reference to the Site, can you try to create a new SPSite with the SYSTEM-UserToken?
SPUserToken sut = thisSite.RootWeb.AllUsers["SHAREPOINT\SYSTEM"].UserToken;
using (SPSite syssite = new SPSite(thisSite.Url,sut)
{
// Do what you have to do
}
The SharePoint Timer jobs runs with the SharePoint Firm Admin credentials since, the information get into the SharePoint Config Database. Thus the application pool will not have the access.
For testing the timer job in dev environment, we can temporarily change the application pool account to the application pool account being used for Central Administration.
Other applications if run this way (i.e. from a timer job with explicit credentials) are failing the same way with "The application failed to initialize propely". I just worte a simple app which takes a path of another executable and its arguments as parameres and when run from that timer job it fails the same way.
internal class ExternalProcess
{
public static void run(String executablePath, String workingDirectory, String programArguments, String domain, String userName,
String password, out Int32 exitCode, out String output)
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
StringBuilder outputString = new StringBuilder();
Object synchObj = new object();
DataReceivedEventHandler outputAppender =
delegate(Object sender, DataReceivedEventArgs args)
{
lock (synchObj)
{
outputString.AppendLine(args.Data);
}
};
process.OutputDataReceived += outputAppender;
process.ErrorDataReceived += outputAppender;
process.StartInfo.FileName = #"C:\AppRunner.exe";
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.Arguments = #"""" + executablePath + #""" " + programArguments;
process.StartInfo.UserName = userName;
process.StartInfo.Domain = domain;
SecureString passwordString = new SecureString();
foreach (Char c in password)
{
passwordString.AppendChar(c);
}
process.StartInfo.Password = passwordString;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
output = outputString.ToString();
}
}
AppRunner basically does the same as the above fragment, but without username and password

Resources