Configure registry permission tool - windows

I have to write a key value pair in the registry. This is done using a tool. This fails sometimes.
Is there any windows utility available which can set the permissions of the registry? If the specific user does not have permission to the registry, I should be able to configure the permissions accordingly - from an administrator account.
I have the only option of invoking it during system startup to set the parameters.

try this
bool flag1 = false;
try
{
new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
// Your Work
}
catch (Exception obj1) //when (?)
{
}
finally
{
System.Security.Permissions.RegistryPermission.RevertAssert();
}
return flag1;

Look at the Regini.exe tool. See here for more details: How to change registry values or permissions from a command line or a script

Related

Multiple Using AppleScript with administrator privileges

I have several commands that have to be run using admin:
Such as silently installing packages, creating folders as administrators, restarting some services, etc.
I think when using the administrator to run the shell command for the first time, after the user successfully enters the administrator password, it is no longer necessary for subsequent times.
I see similar questions not ask for authentication again for five minutes ,but not satisfied.
- (void)setUpScript {
// call this once
NSDictionary *error = nil;
NSString *copyScript = #"do shell script \"/bin/cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop \" with administrator privileges";
self.myAppleScript = [[NSAppleScript alloc] initWithSource:copyScript];
}
- (void)runScript {
// call this as needed; shouldn't need reauthorization
if ([self.myAppleScript executeAndReturnError:&error]) {
NSLog(#"myAppleScript Success!");
} else {
NSLog(#"myAppleScript Failure!");
}
}
As i see this code.The variable "myAppleScript" it is fixed.I need to change its script content.But if I reinitialize "myAppleScript", the key window appears.Am I understanding it wrong?
The documentation: Technical Note TN2065 explains it clearly
Once a script is correctly authenticated, it will not ask for authentication again for five minutes.

How can I redirect the standard output from cmd.exe

This has proven difficult to search as most results are all about redirecting from WITHIN cmd.exe rather than the output of cmd.exe itself.
I have a simple C# example showing a working and non-working test of redirecting process output and just printing the outputted values.
void Main()
{
// Calling nslookup directly works as expected
ProcessStartInfo joy = new ProcessStartInfo("nslookup", #"google.com 8.8.8.8");
// Calling nslookup as a command to cmd.exe does not work as expected
ProcessStartInfo noJoy = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("%COMSPEC%"), #"/C nslookup google.com 8.8.8.8");
Console.WriteLine($"*** Running \"{joy.FileName} {joy.Arguments}\"...");
Console.WriteLine();
Run(joy);
Console.WriteLine();
Console.WriteLine($"*** Running \"{noJoy.FileName} {noJoy.Arguments}\"...");
Console.WriteLine();
Run(noJoy);
}
void Run(ProcessStartInfo startInfo)
{
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
Process proc = new Process();
proc.StartInfo = startInfo;
proc.EnableRaisingEvents = true;
proc.Exited += ReceiveExitNotification;
proc.ErrorDataReceived += ReceiveStandardErrorData;
proc.OutputDataReceived += ReceiveStandardOutputData;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.ExitCode.Dump();
}
void ReceiveStandardOutputData(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
void ReceiveStandardErrorData(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
void ReceiveExitNotification(object sender, EventArgs e)
{
Console.WriteLine("Exited");
}
And here's the output I'm getting from the above
*** Running "nslookup google.com 8.8.8.8"...
Non-authoritative answer:
Server: dns.google
Address: 8.8.8.8
Name: google.com
Addresses: 2607:f8b0:4002:c08::8b
2607:f8b0:4002:c08::64
2607:f8b0:4002:c08::65
2607:f8b0:4002:c08::66
172.217.10.206
null
null
Exited
0
*** Running "C:\windows\system32\cmd.exe /C nslookup google.com 8.8.8.8"...
null
null
Exited
0
The choice of nslookup in the example is arbitrary, I've tried many others including commands with side effects so I can be sure it's being executed as expected.
I have tried with synchronous reads but no change.
I have no reason to believe it's C# or .NET related. I may try a direct CreateProcess() test to confirm.
For context, it's a batch file from which I'm actually looking to get the output, that's why the intermediate cmd.exe process is needed.
Further context, it's actually an MSBuild Exec task from which I'm trying to get the output, so I have limited control of the actual invocation, but I've watched the task run in the debugger and narrowed it down to this issue.
TLDR; The code example in the question works just fine on any normal machine.
So as it turns out this is a permissions issue. This is a company computer and I have restricted rights, however they have software installed that gives administrative rights to particular processes. cmd.exe is one of those processes, so by default it launches as admin and so I cannot read the output stream from my non-elevated process.
Some ideas that almost work around the issue:
From a cmd.exe prompt I can run set __COMPAT_LAYER=RUNASINVOKER then run a second cmd.exe which runs unelevated, but this doesn't really help as I still can't get that stream. Setting the __COMPAT_LAYER environment variable seems to only affect processes launched from cmd.exe (from not CreateProcess() which .NET's Process.Start() uses).
RunAs.exe has a /trustlevel switch with which I can run an unelevated command, but then my Process object is for runas which does not handle any redirection or even stay open for the life of the child process, so still no good.
But in my case I think the simplest solution is best. Copy cmd.exe to another directory and add that to the top of the path. This fixes the elevation issue and even works as a final solution to my actual problem by working event with my limited access to the invocation call through the MSBuild task.

Report back to EC2 that UserData Script Failed

If my UserData Powershell script for an EC2 instance fails how do I report back to EC2 that the machine was not provisioned correct and should be rebuilt?
The EC2 instance is part of an AutoScale Group, and I have found this Set-ASInstanceHealth command but I've found nothing in the documentation to tell me if it's correct to set this within the UserData?
After talking with the AWS Support it seems to call Set-ASInstanceHealth at this point is completely valid. Below is a snippet of PowerShell code explaining the usage in case it's useful to anyone else.
function Get-CurrentEC2InstanceId() {
return Invoke-RestMethod http://169.254.169.254/latest/meta-data/instance-id
}
Try {
# Not do something stupid
}
Catch {
$instanceId = Get-CurrentEC2InstanceId
Set-ASInstanceHealth -InstanceId $instanceId -HealthStatus "Unhealthy"
}

Multiple script commands through SSH on Juniper OS

My question is concerning networking equipments, especially Juniper OS.
I would like to execute a lot of commands through SSH on the switch.
And not manually, with a script.
But, when I push a command through SSH (example : 'configure') to manipulate software configuration, it changes the prompt indeed.
And the next command, available only in this level of configuration, doesn't work, because the level up is for sure not registrated since last command, so new command = come back to inital prompt.
Example in Ruby with net/ssh :
ssh = Net::SSH.start("X.X.X.X", LOGIN, :password => PASSWORD)
ssh.exec!("configure") # -> Entering configuration mode
ssh.exec!("set system services telnet") # -> error: unknown command: set
ssh.close
On Juniper ILC, there isn't '&' or ';' to add mutlipe commands.
Is it possible to insert a carriage return in this kind of command and then put all commands in one request ?
Otherwise how can I execute several commands, keeping the link between them ?
Thanks in advance.
Ok, the only solution I found is to concatenate the instructions into one connection.
Example :
ssh.exec!('configure;
set system services telnet;
delete system services web-management;
set system login class READ permissions view-configuration;
set system login class READ allow-commands show;
...
commit;')
Hope this will help somebody, don't hesitate to improve it !
I know it's about Ruby but i hope my investigation results in Java could be useful. I used construction like this in eBay/parallec(i think in JSch it'll work too) :
public static void sshVmWithPassword() {
ParallelClient pc = new ParallelClient();
pc.prepareSsh().setTargetHostsFromString(HOST)
.setSshCommandLine("show version;\nshow log")
.setSshUserName(USERNAME)
.setSshPassword(PASSWORD)
.execute(new ParallecResponseHandler() {
public void onCompleted(ResponseOnSingleTask res,
Map<String, Object> responseContext) {
System.out.println("Responose:" + res.toString()
+ " host: " + res.getHost()
+ " errmsg: " + res.getErrorMessage());
}
});
pc.releaseExternalResources();
}

Are Windows Services Restricted from Reading from %WINDIR% (C:\Windows)?

I've got an application running as a Windows service that wants to read a file specified by a relative path. Since the service is running under C:\Windows\system32 (on Server 2003 and Windows 7), I figure it should be reading the file from there. However, the file read always fails.
I put together some simple test code to try to open a file for reading, using an absolute path. While the service succeeds for files such as C:\Temp\foo.txt, it always fails for files like C:\Windows\foo.txt and C:\Windows\system32\foo.txt . GetLastError() returns 2.
Am I running into an access issue? I couldn't find authoritative documentation on this. Is there any workaround?
Update:
The file test code is generic and straightforward:
std::ofstream out;
//...
std::string fileName("C:\\Windows\\system32\\Foo.txt");
hFile = CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
out << "Could not create file handle! (" << GetLastError() << ")" << std::endl;
}
else {
out << "Successfully opened file!" << std::endl;
CloseHandle(hFile);
}
Try running the windows service from Local System account. By default the service may be running from "Network Service" account.
To change the settings, Open Windows Service Manager (Run-> services.msc) and double-click your service. On property window select 2nd Tab "Log On" and change it to run with Local System account.
Error code 2 is ERROR_FILE_NOT_FOUND so it's likelier that the path you give simply does not exist or the file does not exist in that path. Without the relevant flags from CreateFile it's hard to give you a better answer.
But generally - under default conditions - a service would be allowed to read in that folder.
One more thing came to mind. How do you obtain the path (C:\Windows in your case)? The proper means are to use the API (e.g. GetWindowsDirectory) for this and not hardcode it.

Resources