Local account is not able to access windows credentail manager - windows-credential-provider

We have java application(spring boot application) which is running as a windows service. We are thinking to move hardcoded db credentials from config file windows Credential manager.
Since our application running as a windows service under Local account unable to fetch the windows credentials manager password information.
We tried executing jar file using command line and its working. But when we launch application(as a windows service) it's failing to fetch the password.
We tried executing the jar file as a separate java process(the below mentioned code) but it's not working.
private static void testProcess() {
try {
LOGGER.error("testProcess started");
String home = System.getenv(CloudConnectUtilityConstants.CT_HOME_PATH);
runProcess("java" + " " + "-jar " + " " + home + "windows.credential.manager.jar");
LOGGER.error("test process end");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
LOGGER.error(command + " exitValue() " + pro.exitValue());
}
Is there any way access windows credential manager under Local system account?

Related

How to access a file server share from an ASP.NET Core web API application published in IIS within the same domain?

I need access to files that are in a files server in my LAN from my Angular app.
I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN
Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I don´t know how to do it.
When I try this
[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
string[] files = Directory.GetFiles(#"\\192.168.100.7\ofertashistorico");
return files;
}
I get this error
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'
It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.
I also do not know how to manage the issue of the credentials necessary to access said resource
Any idea, please?
Thanks
I am using below code and it works for me. Please check it.
Steps:
Navigate to the path like : \\192.168.2.50\ftp
Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.
You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.
Test Result
Sample code
[HttpGet("directorio")]
public IActionResult GetDirectoryContents()
{
string networkPath = #"ftp:\\192.168.2.50";
string userName = #"Administrator";
string password = "Yy16";
#region FtpWebRequest
var networkCredential = new NetworkCredential(userName, password);
var uri = new Uri(networkPath);
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = networkCredential;
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
}
#endregion
return Ok();
}

Trying to connect websocket to a client endpoint that is secure throws error: XNIO000100: 'https' URL scheme chosen but no SSL provider given

I'm trying to create a websocket in java that listens to a local application on the endpoint f.ex. "wss://localhost.localapp.com:8080/".
The application do send through that websocket information about what is happening.
When I run the web-application and it tries to connect to the secure websocket it throws this error:
XNIO000100: 'https' URL scheme chosen but no SSL provider given
Here is my code for connecting to the client endpoint:
#ClientEndpoint
public class ClientEndpoint {
private Logger logger = Logger.getLogger(getClass().getName());
public ClientEndpoint() {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(this, new URI("wss://localhost.localapp.com:8080/"));
} catch (DeploymentException | URISyntaxException | InterruptedException | IOException e) {
System.out.println("Connection error occured!: " + e);
}
}
#OnOpen
public void onOpen(Session session) {
this.logger.info("New websocket session opened: " + session.getId());
}
#OnClose
public void onClose(Session session) {
this.logger.info("Websoket session closed: " + session.getId());
}
#OnMessage
public void onMessage(Session session, String message) throws IOException, EncodeException {
this.logger.info("Message recieved: " + message);
}
#OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
}
}
So the errors happends on this code line:
container.connectToServer(this, new URI("wss://localhost.localapp.com:8080/"));
And the stack trace output this:
ERROR localhost jboss7.1 [RunnerReadFacade] Application was stopped due to exception. Transaction is rollbacked.: java.lang.IllegalArgumentException: XNIO000100: 'https' URL scheme chosen but no SSL provider given
at org.xnio.http.HttpUpgrade$HttpUpgradeState.doUpgrade(HttpUpgrade.java:253)
at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$100(HttpUpgrade.java:165)
at org.xnio.http.HttpUpgrade.performUpgrade(HttpUpgrade.java:129)
at io.undertow.websockets.client.WebSocketClient$ConnectionBuilder.connectImpl(WebSocketClient.java:323)
at io.undertow.websockets.client.WebSocketClient$ConnectionBuilder.connect(WebSocketClient.java:211)
at io.undertow.websockets.jsr.ServerWebSocketContainer.connectToServerInternal(ServerWebSocketContainer.java:463)
at io.undertow.websockets.jsr.ServerWebSocketContainer.connectToServerInternal(ServerWebSocketContainer.java:457)
at io.undertow.websockets.jsr.ServerWebSocketContainer.connectToServer(ServerWebSocketContainer.java:211)
How should I solve this?
With JavaScript I do not need a SSL provider and can simply create the connection with the websocket just by running:
websocket = new WebSocket("wss://localhost.localapp.com:8080/");
Why does the error only occure to Java?
UPDATE:
This probably cannot be done because the application is on your local computer and the server is not local.
But could this be done if you would use a local server?
You can either switch to Programmatic Client Endpoint or define Thread local SSL Context. See details at https://issues.jboss.org/browse/THORN-2131 (wsstest-master.zip includes demo app). 'Implement io.undertow.websockets.jsr.WebsocketClientSslProvider and add a META-INF/services entry' didn't work for me.

Spring-Boot client authentication configuration.

First off, I'm new to Spring-Boot and SSL in general, but I've spent several days researching and am basically trying to get a simple Spring-Boot application configured with Client Authentication.
I've set up a connector like so:
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = getKeyStoreFile();
File truststore = keystore;
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(sslPort);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
protocol.setClientAuth("need");
return connector;
}
catch (IOException ex) {
throw new IllegalStateException("cant access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
And a controller that looks like so:
#RequestMapping("/test/{identifier}")
#ResponseBody
ResponseEntity<String> test(HttpServletRequest request, #PathVariable String identifier) {
return new ResponseEntity<String>("hello: " + identifier, HttpStatus.OK)
}
However, once I launch my application I can use a browser to navigate to localhost:sslport/hello/test/xxxx and get a response without any type of client certificate loaded. I was expecting to be prompted for a client certificate.
Spring boot uses tomcat (embedded) web container by default.
As it is called out tomcat doc, we have to set it to true to enforce the propagation of valid certificate chain from the client before accepting a connection. Setting want will allow the client to provide a certificate but not absolutely required.
I doubt if "need" makes any meaning for the container.
protocol.setClientAuth("need");

Setting commit author in SharpSvn .NET library throws SvnRepisitoryIOException exception

If you have experience with using the SharpSvn .NET library, I could use your expertise in setting the commit author during an SVN commit. I've tried a few things, but they all throw an SvnRepisitoryIOException unless the user is saved in TortoiseSVN. However, I want to use different user credentials depending on the situation. If I've saved a user's default credentials, TortoiseSVN remembers them in Settings > Saved Data > Authenticated Data, and is able to commit a file using that authenticated user as the commit author. If you click "Clear" here, SharpSVN won't know who to authenticate during a commit.
Assume you have these directives in your class: using SharpSvn;
using SharpSvn.Security; I'm using the free version of VisualSVN server for Windows. And I have two users, one being named "user1" and password of "pass1" to keep things simple in the examples below that failed.
How can I prevent this exception from being thrown and commit using different users for the author (in my log of the commit)?
Attempt #1:
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Clear a previous authentication
client.Authentication.DefaultCredentials = new System.Net.NetworkCredential("user1", "pass1");
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}
Attempt #2:
using (SvnClient client = new SvnClient())
{
client.SetProperty(("", "svn:author", "user1");
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}
Attempt #3:
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Clear predefined handlers
client.Authentication.UserNamePasswordHandlers
+= delegate(object obj, SharpSvn.Security.SvnUserNamePasswordEventArgs args)
{
args.UserName = "user1";
args.Password = "pass1";
};
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}
After getting the stack trace when running the application as an administrator, I was able to catch the exception using the framework and accept the non trusted certificate issuer.
*Unhandled Exception: SharpSvn.SvnRepositoryIOException: Commit Failed (details follow): ===> SharpSvn.SvnRepositoryIOException: Unable to connect to a repository at URL 'https://mycomputer/svn/demo_repo/demo_project/trunk/file.txt' --> SharpSvn.SvnRepositoryIOException: OPTIONS of '': Server certificate verification failed: issuer is not trusted (https://mycomputer)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, SvnException error, Object targets)
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, svn_error_t* error, Object targets)
.....*
New Code:
client.Authentication.Clear(); // Clear predefined handlers
client.Authentication.UserNamePasswordHandlers
+= delegate(object obj, SharpSvn.Security.SvnUserNamePasswordEventArgs args)
{
args.UserName = "user1";
args.Password = "pass1";
};
client.Authentication.SslServerTrustHandlers​ +=
delegate(object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = true; // Save acceptance to authentication store
};
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);

OperaDriver getting timed out waiting for opera launcher

I am trying to integrate OperaDriver for Java (ver. 0.11) into my test suite. Here's the code snippet:
DesiredCapabilities operaCapabilities = DesiredCapabilities.opera();
operaCapabilities.setCapability("opera.host", "127.0.0.1");
operaCapabilities.setCapability("opera.port", 7001);
operaCapabilities.setCapability("opera.profile", "");
webDriver = new OperaDriver(operaCapabilities);
The above code snippet fails to return a webdriver reference with a SocketTimeoutException Timeout waiting for launcher to connect on port 29392. I can see that the browser (opera ver. 11.62) is launched with speed dial tab loaded, and the launcher is also executing, but somehow OperaDriver seems to be unable to connect.
The exception I see is:
com.opera.core.systems.runner.OperaRunnerException: Timeout waiting for launcher to connect on port 29392
at com.opera.core.systems.runner.launcher.OperaLauncherRunner.<init>(OperaLauncherRunner.java:159)
at com.opera.core.systems.OperaDriver.<init>(OperaDriver.java:322)
at com.opera.core.systems.OperaDriver.<init>(OperaDriver.java:224)
at com.test.TestMain.main(TestMain.java:31)
Caused by: java.net.SocketTimeoutException: Accept timed out
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:408)
at java.net.ServerSocket.implAccept(ServerSocket.java:462)
at java.net.ServerSocket.accept(ServerSocket.java:430)
at com.opera.core.systems.runner.launcher.OperaLauncherRunner.<init>
(OperaLauncherRunner.java:140)
... 3 more
I have tried -1 for "opera.port" and also 7001, but the capability setting seems to be ignored, since it is attempting to connect with a random port each time. I have my firewalls temporarily turned off as well.
First, let's isolate the exception being hit here:
private final int launcherPort = PortProber.findFreePort();
...
public OperaLauncherRunner(OperaSettings s) {
super(s);
// Locate the bundled launcher from OperaLaunchers project and copy it to its default location
// on users system if it's not there or outdated
bundledLauncher =
OperaLaunchers.class.getClassLoader().getResource("launchers/" + launcherNameForOS());
if (bundledLauncher == null) {
throw new OperaRunnerException("Not able to locate bundled launcher: " + bundledLauncher);
}
if (settings.getLauncher() == launcherDefaultLocation() &&
(!settings.getLauncher().exists() || isLauncherOutdated(settings.getLauncher()))) {
extractLauncher(bundledLauncher, settings.getLauncher());
}
makeLauncherExecutable(settings.getLauncher());
// Find an available Opera if present
if (settings.getBinary() == null) {
settings.setBinary(new File(OperaPaths.operaPath()));
}
// Create list of arguments for launcher binary
ImmutableList<String> arguments = buildArguments();
logger.config("launcher arguments: " + arguments);
try {
launcherRunner = new OperaLauncherBinary(settings.getLauncher().getPath(),
arguments.toArray(new String[]{}));
} catch (IOException e) {
throw new OperaRunnerException("Unable to start launcher: " + e.getMessage());
}
logger.fine("Waiting for launcher connection on port " + launcherPort);
try {
// Setup listener server
ServerSocket listenerServer = new ServerSocket(launcherPort);
listenerServer.setSoTimeout((int) OperaIntervals.LAUNCHER_TIMEOUT.getValue());
// Try to connect
launcherProtocol = new OperaLauncherProtocol(listenerServer.accept());
// We did it!
logger.fine("Connected with launcher on port " + launcherPort);
listenerServer.close();
// Do the handshake!
LauncherHandshakeRequest.Builder request = LauncherHandshakeRequest.newBuilder();
ResponseEncapsulation res = launcherProtocol.sendRequest(
MessageType.MSG_HELLO, request.build().toByteArray());
// Are we happy?
if (res.isSuccess()) {
logger.finer("Got launcher handshake: " + res.getResponse().toString());
} else {
throw new OperaRunnerException(
"Did not get launcher handshake: " + res.getResponse().toString());
}
} catch (SocketTimeoutException e) {
throw new OperaRunnerException("Timeout waiting for launcher to connect on port " +
launcherPort, e);
} catch (IOException e) {
throw new OperaRunnerException("Unable to listen to launcher port " + launcherPort, e);
}
}
We learn a few things from this code:
private final int launcherPort =PortProber.findFreePort(); sets our launcherPort, and this variable is uniquely used to establish the connect.
Indeed, your configuration of opera.port is completely ignored in this block. That seems less than desirable, and it may indeed be a bug or an unexpected regression.
Once we establish the local port, a connection attempt is made immediately:
// Setup listener server
ServerSocket listenerServer = new ServerSocket(launcherPort);
listenerServer.setSoTimeout((int) OperaIntervals.LAUNCHER_TIMEOUT.getValue());
// Try to connect
launcherProtocol = new OperaLauncherProtocol(listenerServer.accept());
So, we have a tightly coupled binding to the local server. The port is ignored in favor of a free one on your system, but simultaneously, it should always be able to use that port.
If your firewall is indeed not preventing the connection (as you've discussed), let's assume you desire Opera to be connected to programmatically, instead of manually opening the connection.
According to some documentation, opera.host carries the following caveat:
opera.host (String) The host Opera should connect to. Unless you're
starting Opera manually you won't need this.
(Additional emphasis mine.)
Needless to say, the caveat concerns me. Likewise, despite its apparent inapplicability:
opera.port (Integer) The port to Opera should connect to. 0 = Random,
-1 = Opera default (for use with Opera > 12).
(Additional emphasis mine.)
In short: try running your application as illustrated here:
DesiredCapabilities capabilities = new DesiredCapabilities.opera();
capabilities.setCapability("opera.binary", "/path/to/your/opera");
capabilities.setCapability("opera.log.level", "CONFIG");
WebDriver driver = new OperaDriver(capabilities);
If this doesn't work, something else is wrong, either with your project or with your current Opera binary, be it version-related or otherwise.