Authentication failed or partial success with ckosshtunnel and AuthenticatePk - chilkat

I'm having an issue where I can connect via publickey to an ssh server via command line:
ssh -N -L 12345:127.0.0.1:22 -i /Users/kylehankinson/.ssh/id_rsa USER#HOST
But if I try the same thing via code:
CkoSshKey * sshkey = [[CkoSshKey alloc] init];
sshkey.Password = #"blahblah";
NSString * privateKeyString = [sshkey LoadText: #"/Users/kylehankinson/.ssh/id_rsa"];
if(![sshkey FromPuttyPrivateKey: privateKeyString])
{
NSLog(#"Had failure: %#", sshkey.LastErrorText);
return;
}
CkoSshTunnel *ssh = [[CkoSshTunnel alloc] init];
success = [ssh Connect: #"HOST" port: #(22)];
if (success != YES)
{
NSLog(#"%#",ssh.LastErrorText);
return;
}
success = [ssh AuthenticatePk: #"USER"
privateKey: sshkey];
if(!success)
{
NSLog(#"%#",ssh.LastErrorXml);
return;
}
I receive the following error:
<ChilkatLog>
<AuthenticatePK>
<DllDate>Apr 16 2019</DllDate>
<ChilkatVersion>9.5.0.78</ChilkatVersion>
<UnlockPrefix>xxxxxxx</UnlockPrefix>
<Architecture>Little Endian; 64-bit</Architecture>
<Language>Cocoa Objective-C</Language>
<VerboseLogging>0</VerboseLogging>
<login>sshtunnel</login>
<sshAuthenticatePk>
<keyFingerprint>ssh-rsa 2048 xxxxxxxxx</keyFingerprint>
<requestUserAuthService>
<sendServiceRequest>
<svcName>ssh-userauth</svcName>
<SentServiceReq>ssh-userauth</SentServiceReq>
</sendServiceRequest>
<info>ssh-userauth service accepted.</info>
</requestUserAuthService>
<info>Using an RSA key.</info>
<info>Sent public-key request.</info>
<AuthList>publickey,password</AuthList>
<rsaSigLen>256</rsaSigLen>
<info>Sent public-key request with signature.</info>
<error>Authentication failed or partial success. (4)</error>
<PartialSuccess4>0</PartialSuccess4>
<AuthList>publickey,password</AuthList>
<error>Publickey authentication failed..</error>
</sshAuthenticatePk>
<error>Failed.</error>
</AuthenticatePK>
</ChilkatLog>
Any suggestions?

Thanks Kyle,
Here's a new build that fixes the problem:
https://chilkatdownload.com/prerelease/chilkat-9.5.0-macosx-objc-1408.zip
The source of the problem had to do with the private key blob format in the OpenSSH key format. The order of parsing RSA key parts was not correct. (If the key was loaded from the PuTTY private key format, .ppk, then there was no problem..)
PS> The above download link is temporary and will not be valid in the future..

Related

Google Application Credentials set and not found

I have an Amazon EC2 with Linux Instance set up and running for my Java Web Application to consume REST requests. The problem is that I am trying to use Google Cloud Vision in this application to recognize violence/nudity in users pictures.
Accessing the EC2 in my Terminal, I set the GOOGLE_APPLICATION_CREDENTIALS by the following command, which I found in the documentation:
export GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
Here comes my first problem: When I restart my server, and ran 'echo $GOOGLE_APPLICATION_CREDENTIALS' the variable is gone. Ok, I set it to the bash_profile and bashrc and now it is ok.
But, when I ran my application, consuming the above code, to get the adult and violence status of my picture, I got the following error:
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
My code is the following:
Controller:
if(SafeSearchDetection.isSafe(user.getId())) {
if(UserDB.updateUserProfile(user)==false){
throw new SQLException("Failed to Update");
}
} else {
throw new IOException("Explicit Content");
}
SafeSearchDetection.isSafe(int idUser):
String path = IMAGES_PATH + idUser + ".jpg";
try {
mAdultMedicalViolence = detectSafeSearch(path);
if(mAdultMedicalViolence.get(0) > 3)
return false;
else if(mAdultMedicalViolence.get(1) > 3)
return false;
else if(mAdultMedicalViolence.get(2) > 3)
return false;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
detectSafeSearch(String path):
List<AnnotateImageRequest> requests = new ArrayList<AnnotateImageRequest>();
ArrayList<Integer> adultMedicalViolence = new ArrayList<Integer>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(path));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
ImageAnnotatorClient client = ImageAnnotatorClient.create();
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.println("Error: "+res.getError().getMessage()+"\n");
return null;
}
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
adultMedicalViolence.add(annotation.getAdultValue());
adultMedicalViolence.add(annotation.getMedicalValue());
adultMedicalViolence.add(annotation.getViolenceValue());
}
for(int content : adultMedicalViolence)
System.out.println(content + "\n");
return adultMedicalViolence;
My REST application was built above a Tomcat8. After no success running the command:
System.getenv("GOOGLE_APPLICATION_CREDENTIALS")
I realize that my problem was in the Environment Variables to Tomcat installation. To correct this, I just created a new file setenv.sh in my /bin with the content:
GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
And it worked!

Query cached ACL of a directory for a disconnected Windows domain user via Authz API

I would like to explore the effective rights of a local directory for the currently logged on domain user. This link has given me a good starting point and works as expected.
Unfortunately, querying the ACL fails when I disconnect from the domain controller and log on with my cached domain user profile. When being confronted with this environment, the AuthzInitializeContextFromSid function in the example code returns FALSE and sets 1355 (ERROR_NO_SUCH_DOMAIN) as the last error code:
...
PSID pSid = NULL;
BOOL bResult = FALSE;
LUID unusedId = { 0 };
AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext = NULL;
pSid = ConvertNameToBinarySid(lpszUserName);
if (pSid != NULL)
{
bResult = AuthzInitializeContextFromSid(0,
pSid,
hManager,
NULL,
unusedId,
NULL,
&hAuthzClientContext);
if (bResult)
{
GetAccess(hAuthzClientContext, psd);
AuthzFreeContext(hAuthzClientContext);
}
else
{
//prints 1355 as last error code
wprintf_s(_T("AuthzInitializeContextFromSid failed with %d\n"), GetLastError());
}
...
}
Is it possible to query the (cached) ACL nonetheless? Surely they must be accessible some way or another, even if the domain controller is unreachable.

email settings imap RetrieveImap() Execution of request failed

I just started getting the error on 8/19/2015: Execution of request failed: https://apps-apis.google.com/a/feeds/emailsettings/2.0/myDomain/myUser/imap
The program has been running fine before 8/19.
The users are all new users and it fails on most of them, but a few do work.
I tried on a couple of accounts that have been around a while and it worked.
I double checked that the "Disable POP and IMAP access for all users." is not checked. I am not sure what to do.
The error happens on the RetrieveImap(userID).
OAuth2Parameters oA2Parm;
if (gCredential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result) {
oA2Parm = new OAuth2Parameters() {
AccessToken = gCredential.Token.AccessToken
};
} else {
eMsgImap = #"Error. setIMapTrue: can't get Access Token.";
return eMsgImap;
}
GoogleMailSettingsService gEmailSettingService;
AppsExtendedEntry ee;
GOAuth2RequestFactory rf = new GOAuth2RequestFactory("apps", "gMail APIs", oA2Parm);
gEmailSettingService = new GoogleMailSettingsService(gDomain, "gMail API");
while ....
ee = gEmailSettingService.RetrieveImap(userID);

After changing a key value from a machine2, Not getting the changed value from Machine1

I did a sample application & run the application from 2 different machines where both application is using AppFabric cache. I set the pollInterval="120" secs in both applications config file with below settings:
<localCache isEnabled="true"
sync="NotificationBased"
ttlValue="300"
objectCount="10"/>
<!--(optional) specify cache notifications poll interval-->
<clientNotification pollInterval="120" />
Also enabled Notification in cluster using powershell.
Now from Machine1 I read the key called key1 whose value is "Value1".
then from Machine2 I changed the value of key1 to "Changed".
then from Machine2 I read the key called key1 whose value is now displayed as "Changed".
then after the poll interval period which is 2 mnts I read the key called key1 from Machine1, whose value is now displayed still as "Value1". Why it's not displaying "Changed".
Why the change is not detected by the application in Machine1? Why the local cache invalidation not occurring?
At Ahmed Ilyas:>
show the code you are using to read and write to the cache. you also have not explained how you configured AppFabric and these machines. are they joined to the cluster?
I have done reading through AFC Read-Through API. which is done in separate project. Write to cache is done just by Put() method. As this is a sample project, so I though no need to update the database only update at cache cluster.
The above config settings for each application running in 2 machines.
I have allowed access for these 2 machines by granting access to them in cache cluster. 1 machine is both AFC server & cache client(i.e Machine1).
Hope this helps you to answer. Find the code below:
public class CacheUtil
{
private static DataCacheFactory _factory = null;
private static DataCache _cache = null;
static CacheUtil()
{
if (_cache == null)
{
// Declare array for cache host(s).
DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1];
servers[0] = new DataCacheServerEndpoint("H1011.hoboo.net", 22233);
// Set the local cache properties. In this example, it
// is timeout-based with a timeout of 300 seconds(5mnts).
DataCacheLocalCacheProperties localCacheConfig;
TimeSpan localTimeout = new TimeSpan(0, 5, 0);
localCacheConfig = new DataCacheLocalCacheProperties(60, localTimeout, DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
// Setup the DataCacheFactory configuration.
DataCacheFactoryConfiguration factoryConfig = new DataCacheFactoryConfiguration();
//factoryConfig.ChannelOpenTimeout = new TimeSpan(0, 0, 0);
//factoryConfig.Servers = servers;
//factoryConfig.LocalCacheProperties = localCacheConfig;
_factory = new DataCacheFactory();
//_factory = new DataCacheFactory(factoryConfig);
_cache = _factory.GetCache("default");
}
}
public static DataCache GetCache()
{
if (_cache != null) return _cache;
try
{
RuntimeContext.WriteAppFabricErrorLog(new AppFabricLogger()
{
CacheKey = "Connected to AppFabric Cache Server.",
CacheData = "Connected to AppFabric Cache Server.",
ErrorString = "Connected to AppFabric Cache Server."
});
}
catch (Exception ex)
{
//Suppress Error
}
return _cache;
}
}
Other class which has Get():>
public static object Get(string pName)
{
object cachedItem = null;
try
{
//Check configuration settings for AppFabric.
bool appFabricCache;
bool.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppFabricCache"], out appFabricCache);
if (appFabricCache)
{
//Get data from AppFabric Cache Server.
cachedItem = CacheUtil.GetCache().Get(pName);
}
else
{
//Get data from Local Cache Server.
cachedItem = RuntimeContextOlderVersion.Get(pName);
}
}
catch (Exception Ex)
{
//If failes, write reason to log file.
WriteAppFabricErrorLog(new AppFabricLogger()
{
CacheKey = pName,
CacheData = "Get Method",
ErrorString = Ex.ToString()
});
}
return cachedItem;
}
#stuartd
Yes I have enabled notifictions. You can see that in my appconfig.
For Staurt:>
PS C:\Windows\system32> get-cacheconfig
cmdlet Get-CacheConfig at command pipeline position 1
Supply values for the following parameters:
CacheName: default
CacheName : default
TimeToLive : 10 mins
CacheType : Partitioned
Secondaries : 0
MinSecondaries : 0
IsExpirable : True
EvictionType : LRU
NotificationsEnabled : True
WriteBehindEnabled : False
WriteBehindInterval : 300
WriteBehindRetryInterval : 60
WriteBehindRetryCount : -1
ReadThroughEnabled : True
ProviderType : SampleProvider.Provider,SampleProvider, Version=1.0.
0.0, Culture=neutral, PublicKeyToken=cde85af3c5f6411
e
ProviderSettings : {"DBConnection"="Database=Test123;Server=..**.
**;uid=****;pwd=*****;connection timeout=5000"}

WMI Remote connection

I have an issue regarding WMI connection through asp.net from Computer A (windows 2003 server) to Computer B (Windows XP)..
The error is as follows:
RPC server is unavailable..
There are a few steps that you must take in order to successfully leverage WMI connectivity. The basics are you must allow remote management on the target box of course. If you can’t RDP into it, chances are, you can’t remote manage anything else. This can also include Windows firewall issues too. Make sure your request can even get in at all.
Next, start simple. Can you even poll for the running processes on that box? Try to output all the running processes on the target box with System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetProcesses("machine-name"). If you can at least get some information on the box then the RPC message you are getting has to do with incorrect arguments being passed in, perhaps?
Anyways, I recently wrote a web application that allowed the users to find a server on the LAN and kill a target process there or start a new one. I did it in C# so the code snippet below is just what I used. It's not the best but its working in production right now:
public static class RemoteProcessAccess
{
public static void KillProcessByProcessID(string NameOfServer, string DomainName, string LogIn, string Password, int processID)
{
//#1 The vars for this static method
#region /// <variables> ...
string userName;
string password;
string machineName;
string myDomain;
Hashtable hs = new Hashtable();
ManagementScope mScope;
ConnectionOptions cnOptions;
ManagementObjectSearcher objSearcher;
ManagementOperationObserver opsObserver;
ManagementClass manageClass;
DirectoryEntry entry;
DirectorySearcher searcher;
DirectorySearcher userSearcher;
#endregion
//#2 Set the basics sent into the method
machineName = NameOfServer;
myDomain = DomainName;
userName = LogIn;
password = Password;
cnOptions = new ConnectionOptions();
cnOptions.Impersonation = ImpersonationLevel.Impersonate;
cnOptions.EnablePrivileges = true;
cnOptions.Username = myDomain + "\\" + userName;
cnOptions.Password = password;
mScope = new ManagementScope(#"\\" + machineName + #"\ROOT\CIMV2", cnOptions);
//#3 Begin Connection to Remote Box
mScope.Connect();
objSearcher = new ManagementObjectSearcher(String.Format("Select * from Win32_Process Where ProcessID = {0}", processID));
opsObserver = new ManagementOperationObserver();
objSearcher.Scope = mScope;
string[] sep = { "\n", "\t" };
//#4 Loop through
foreach (ManagementObject obj in objSearcher.Get())
{
string caption = obj.GetText(TextFormat.Mof);
string[] split = caption.Split(sep, StringSplitOptions.RemoveEmptyEntries);
// Iterate through the splitter
for (int i = 0; i < split.Length; i++)
{
if (split[i].Split('=').Length > 1)
{
string[] procDetails = split[i].Split('=');
procDetails[1] = procDetails[1].Replace(#"""", "");
procDetails[1] = procDetails[1].Replace(';', ' ');
switch (procDetails[0].Trim().ToLower())
{
//You could look for any of the properties here and do something else,
case "processid":
int tmpProc = Convert.ToInt32(procDetails[1].ToString());
//if the process id equals the one passed in....
//(this is redundant since we should have limited the return
//by the query where above, but we're paranoid here
if (tmpProc.Equals(processID))
{
obj.InvokeMethod(opsObserver, "Terminate", null);
}
break;
}//end process ID switch...
}//end our if statement...
}//end our for loop...
}//end our for each loop...
}//end static method
}
Look at KB875605 ("How to troubleshoot WMI-related issues in Windows XP SP2")
You could enable the RPC server on any target machine by running this on the target's command prompt:
[/code]
netsh firewall set service RemoteAdmin
[/code]
Worked for me at least. :)
Try to use wmic command line to get information from the remote computer, also you can install the code of Services+ and try to connect and debug your connection to the server, most likely it is firewall problem or RPC services is down or disabled.