why pwcb.getPassword is null in this code - axis2

I try to add the rampart security to my axis2 web service using rampart module.
So here is what I have made:
I have stored in a database the hashed value of "bobWWW" password and the salt
In my PWCBHandler.java class
•I select the stored in the database password and hash
•I try to hash with same algorithm pwcb.getPassword() with the same stored salt
•check if this new hashed password is equal to the stored password
But I constantly was receiving nullpointerexception so I decide to check and wrote this code
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I see that pwcb.getPassword() is empty. So here is the code of PWCBHandler.java
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
try {
pasandsalt = getdataforChecking();
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
passwordforchecking = hash(pwcb.getPassword(),Base64.decodeBase64(pasandsalt[1]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if((pwcb.getIdentifier().equals("bob")) && (passwordforchecking.equals(pasandsalt[0])) )
{
return;
}
}
And here is my soaprequest with the sequeiry header
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soapenv:Envelope " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:nilo=\"http://nilo\">"+
"<soapenv:Header>"+
'<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" soapenv:mustUnderstand="1">'+
'<wsse:UsernameToken xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="123">'+
'<wsse:Username>bob</wsse:Username>'+
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>'+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
"</soapenv:Header>"+
"<soapenv:Body>" +
"<nilo:getdataForChecking>" +
'<nilo:data>'+tranXml+'</nilo:data>' +
' </nilo:getdataForChecking>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';

According to your soap headers i can see you are using a Plain text password instead of Password Digest. You might need to change the rampart configuration
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>
this might be helpful to you. http://wso2.com/library/240/

Related

Find the algorithm of SSL Symmetric Encryption

Is there a way we could find what is the algorithm used to encrypt HTTPS requests between server and client after SSL handshake. looking at the network calls, server certificate or browser settings etc.
Using java you can try this.
private void printSSLDetails(){
String https_url = "https://www.google.com/";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
//dumpl all cert info
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : "
+ cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : "
+ cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

GoogleIdTokenVerifier.verify always returns null

I am trying to validate a JWT Token sent by Google to my application . I am using the below code to validate the JWT token but verifier.verify(token) always returns null even if the token is valid. I have tested the token in another NodeJS code i have and it works fine in NodeJS but in the below java code i am not able to validate the token . Any help in letting me know why verifier.verify(token) returns null is appreciated.
public static boolean isRequestFromGoogle(String audience, String token) {
//HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
//JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(httpTransport,
jsonFactory).setAudience(Collections.singletonList(audience)).build();
try {
System.out.println("token is " + token);
System.out.println("verifier is " + verifier.toString());
GoogleIdToken idToken = verifier.verify(token);
if (idToken == null) {
System.out.println("idToken is null");
return false;
}
Payload payload = idToken.getPayload();
String issuer = (String) payload.get("iss");
String proj = (String) payload.get("aud");
System.out.println("Issuer is" + issuer);
System.out.println("Project is" + proj);
return issuer.equals("https://accounts.google.com");
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}

How to get the method name and line number in Exception in ASP Core 5

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

Renci.SshNet : "server response does not contain ssh protocol identification"

I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client. When the user tries to connect to download some files from the SFTP server he gets the message shown below:
Server response does not contain ssh protocol identification
It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop. The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem. I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
{
try
{
SftpClient SFTP;
if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
{
SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
}
else
{
SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
}
SFTP.Connect();
DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + #"\PLOG");
ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
Directory.Delete(Directory.GetCurrentDirectory() + #"\PLOG", true);
SFTP.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Getting PLOGS");
}
}
void DownloadDirectory(SftpClient Client, string Source, string Destination)
{
var Files = Client.ListDirectory(Source);
foreach (var File in Files)
{
if (!File.IsDirectory && !File.IsSymbolicLink)
{
DownloadFile(Client, File, Destination);
}
else if (File.IsSymbolicLink)
{
//Ignore
}
else if (File.Name != "." && File.Name != "..")
{
var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
DownloadDirectory(Client, File.FullName, Dir.FullName);
}
}
}
void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
{
using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
{
Client.DownloadFile(File.FullName, FileStream);
}
}
Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
{
myClient = new SshClient(Host, Port, Username, Password);
myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
myClient.HostKeyReceived += myClient_HostKeyReceived;
myClient.ErrorOccurred += myClient_ErrorOccurred;
}
void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
}
void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
{
e.CanTrust = true;
}
public async void Connect()
{
Task T = new Task(() =>
{
try
{
myClient.Connect();
}
catch (System.Net.Sockets.SocketException)
{
MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
MessageBox.Show(ex.Message, "SSH Authentication Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
MessageBox.Show(ex.GetType().ToString());
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
});
T.Start();
await T;
if (T.IsCompleted)
{
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
}
public void Disconnect()
{
try
{
myClient.Disconnect();
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
public void SendData(string Data)
{
try
{
if (Data.EndsWith("\r\n"))
{
RunCommandAsync(Data, SshCommandRx);
}
else
{
RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
}
//SshCommand Command = myClient.RunCommand(Data);
//OnDataReceived(this, new DataEventArgs(Command.Result));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
private async void RunCommandAsync(String Data, SshCommandCallback Callback)
{
Task<SshCommand> T = new Task<SshCommand>(() =>
{
try
{
SshCommand Command = myClient.RunCommand(Data);
return Command;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
return null;
}
});
T.Start();
await T;
if (T.IsCompleted)
{
Callback(this, T.Result);
}
}
private void SshCommandRx(SshConnection C, SshCommand Command)
{
if (Command != null)
{
string Rx = Command.Result;
//if (Rx.StartsWith(Command.CommandText))
//{
// Rx = Rx.Remove(0, Command.CommandText.Length);
//}
while (Rx.EndsWith("\r\n\r\n") == false)
{
Rx += "\r\n";
}
OnDataReceived(this, new DataEventArgs(Rx));
}
}
I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.

NullReferenceException was unhandledby user code

I am making a registration page and while using an input tag to upload image of the user, it is giving an error while running the website: "NullReferenceException was unhandledby user code". Please help me to sort this out. The method which is giving error is:
protected void Button2_Click(object sender, EventArgs e)
{
var path = "Memberimg";
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Memberimg") + "\\" + fn;
if ((f1.PostedFile != null) && (f1.PostedFile.ContentLength > 0))
{
try
{
f1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
You are referring to f1.PostedFile before checking to see if it is null, in the line with:
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);