How do I get the ip address of the remote endpoint of a socket of type boost::asio::ssl::stream<boost::asio::ip::tcp::socket> - ssl

How do I get the ip address of the remote endpoint of a socket of type boost::asio::ssl::stream. I want to print peer ip like this- but it doesnt work
std::cout << "Peer IP: " << socket_.remote_endpoint().address().to_string()

I figured it out
It should be
std::cout << "Peer IP: " << socket_.lowest_layer().remote_endpoint().address().to_string() << std::endl;

Related

Ceph RGW unable to upload object if JaegerTracing is implemented

OS : ubuntu 18.04
ceph : octopus
jaeger : master
When I implement jaegertracer in the function that is responsibe for writing file to ceph via RGW, I am unable to upload my file Im getting this error
Warning: failed to create container 'mycontainer': HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /auth (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f5076b7a990>: Failed to establish a new connection: [Errno 111] Connection refused',))
But when I remove my tracer from the code it uploads the file successfully
source code
void librados::IoCtxImpl::queue_aio_write(AioCompletionImpl *c)
{
auto yaml = YAML::LoadFile("tracerConfig.yaml");
auto config = jaegertracing::Config::parse(yaml);
auto tracer=jaegertracing::Tracer::make(
"Writing",
config,
jaegertracing::logging::consoleLogger()
);
opentracing::Tracer::InitGlobal(
static_pointer_cast<opentracing::Tracer>(tracer)
);
auto span = opentracing::Tracer::Global()->StartSpan("Span1");
get();
ofstream file;
file.open("/home/abhinav/Desktop/write.txt",std::ios::out | std::ios::app);
file<<"Writing /src/librados/IoCtxImpl.cc 288.\n";
file.close();
std::scoped_lock l{aio_write_list_lock};
ceph_assert(c->io == this);
c->aio_write_seq = ++aio_write_seq;
ldout(client->cct, 20) << "queue_aio_write " << this << " completion " << c
<< " write_seq " << aio_write_seq << dendl;
aio_write_list.push_back(&c->aio_write_list_item);
opentracing::Tracer::Global()->Close();
}
When I remove the tracer it compiles fine again
The issue was related to yaml file parsing

How to pass data in Poco HTTPRequest

This is regarding to my project, Where I am write Poco SSL client to communicate with a server.
I am able to do (i) Basic Auth (ii) Cert exchange. But after sending post request I am facing "Error 500".
Let me explain it=>
I have a working curl:
curl -d '{"name":"com.my.session.value"}' -H 'Content-Type: application/json' -H 'Accept: application/json' -E MyCert.pem --key MyKey.pem -u testuser -k -vvv https://<server-ip>:<port>/Internal/directory/path
using this I am able to print data on console. So tried to write same in Poco/C++:
// I have handler for keyPassparse, cert, invalid-cert-handler and used them in below line
SSLManager::instance().initializeClient(parse_str, Cert, ptrContext);
URI uri(argv[1]);
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort());
session.setKeepAlive(true);
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, uri.getPath(), Poco::Net::HTTPMessage::HTTP_1_1);
HTTPBasicCredentials cred("testuser", "secret");
//Here I tried to add headers and data
cred.authenticate(req);
req.add("Content-Type","application/json");
req.add("Accept","application/json");
req.add("data","com.my.session.value"); // try-1 to add data
req.setKeepAlive(true);
std::ostream& myOStream = session.sendRequest(req);
std::string body("name=com.my.session.value"); // try-2 to add data
myOStream << body;
Poco::Net::HTTPResponse response;
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
}
This is always returning Error:500 (Internal server error)
Which means my data section is not reaching properly.
Please suggest me a way to pass proper "data" section to server.
Thanks in advance.
I found the solution for this:
1) I sent data as json:
Poco::JSON::Object obj;
obj.set("name", "com.my.session.value");
std::stringstream ss;
obj.stringify(ss);
2) Content herders should not be added by "add", used below for them:
req.setContentType("application/json");
req.setContentLength(ss.str().size());
3) Now sending body like this:
std::ostream& myOStream = session.sendRequest(req);
obj.stringify(myOStream);
Approach used:
I wrote code for http.
Sent same data by curl and exe, captured packets for both.
Compared and fixed gaps one by one.
I hope this will help someone in future.

Error:: AWS authentication requires a valid Date or x-amz-date header

I am using Command Line Tool for uploading files from Amazon S3 to CloudSearch for Indexing using the command-
cs-import-documents -d searchdev3 --source s3://mybucket/html
It is giving error-
Connecting to CloudSearch in region [us-east-1]
AWS authentication requires a valid Date or x-amz-date header (Service: Amazon S
3; Status Code: 403; Error Code: AccessDenied; Request ID: 506FD29F73XXXXXX)
How can I track where the problem is occurring?
UPDATE
When run with --verbose I received below output-
Looking up DocServiceEndpoint for domain searchdev3 using config service at null
Connecting to CloudSearch in region [us-east-1]
Sending to endpoint [https://cloudsearch.us-east-1.amazonaws.com/] for region [u
s-east-1]
Connection request: [route: {s}->https://cloudsearch.us-east-1.amazonaws.com][to
tal kept alive: 0; route allocated: 0 of 50; total allocated: 0 of 50]
Connection leased: [id: 0][route: {s}->https://cloudsearch.us-east-1.amazonaws.c
om][total kept alive: 0; route allocated: 1 of 50; total allocated: 1 of 50]
Connecting to cloudsearch.us-east-1.amazonaws.com:443
CookieSpec selected: best-match
Auth cache not set in the context
Proxy auth state: UNCHALLENGED
Sending request: POST / HTTP/1.1
>> "POST / HTTP/1.1[\r][\n]"
>> "Host: cloudsearch.us-east-1.amazonaws.com[\r][\n]"
>> "Authorization: AWS4-HMAC-SHA256 Credential=XXXXXXXX/20151130/us-
east-1/cloudsearch/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signa
ture=e93cd0c22189084ff55c1084[\r][\n]"
>> "X-Amz-Date: 20151130T103603Z[\r][\n]"
>> "User-Agent: aws-internal/3[\r][\n]"
>> "Content-Type: application/x-www-form-urlencoded; charset=utf-8[\r][\n]"
>> "Content-Length: 73[\r][\n]"
>> "Connection: Keep-Alive[\r][\n]"
>> "[\r][\n]"
>> POST / HTTP/1.1
>> Host: cloudsearch.us-east-1.amazonaws.com
>> Authorization: AWS4-HMAC-SHA256 Credential=XXXXXXXX/20151130/us-e
ast-1/cloudsearch/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signat
ure=e93cd0c22189084ff55c1084
>> X-Amz-Date: 20151130T103603Z
>> User-Agent: aws-internal/3
>> Content-Type: application/x-www-form-urlencoded; charset=utf-8
>> Content-Length: 73
>> Connection: Keep-Alive
>> "Action=DescribeDomains&Version=2013-01-01&DomainNames.member.1=searchdev3"
<< "HTTP/1.1 200 OK[\r][\n]"
<< "x-amzn-RequestId: 2907d340-974e-11e5-a6e5-33953f55803d[\r][\n]"
<< "Content-Type: text/xml[\r][\n]"
<< "Content-Length: 1635[\r][\n]"
<< "Date: Mon, 30 Nov 2015 10:36:05 GMT[\r][\n]"
<< "[\r][\n]"
Receiving response: HTTP/1.1 200 OK
<< HTTP/1.1 200 OK
<< x-amzn-RequestId: 2907d340-974e-11e5-a6e5-33953f55803d
<< Content-Type: text/xml
<< Content-Length: 1635
<< Date: Mon, 30 Nov 2015 10:36:05 GMT
<< "<"
<< "D"
<< "e"
<< "s"
<< "cribeDomainsResponse xmlns=""
<< "http://cloudsearch.amazonaws.com/doc/2013-01-01/">[\n]"
<< " <DescribeDomainsResult>[\n]"
<< " <DomainStatusList>[\n]"
<< " <member>[\n]"
<< " <Created>true</Created>[\n]"
<< " <RequiresIndexDocuments>false</RequiresIndexDocuments>[\n]"
<< " <SearchInstanceType>search.m1.small</SearchInstanceType>[\n]"
<< " <DomainId>613875336225/searchdev3</DomainId>[\n]"
<< " <DocService>[\n]"
<< " <Endpoint>doc-searchdev3-ytmgti5ijnobqprgg65e4yxrhe.us-east-1.clou
dsearch.amazonaws.com</Endpoint>[\n]"
<< " </DocService>[\n]"
<< " <SearchPartitionCount>1</SearchPartitionCount>[\n]"
<< " <Deleted>false</Deleted>[\n]"
<< " <SearchService>[\n]"
<< " <Endpoint>search-searchdev3-ytmgti5ijnobqprgg65e4yxrhe.us-east-1.c
loudsearch.amazonaws.com</Endpoint>[\n]"
<< " </SearchService>[\n]"
<< " <DomainName>searchdev3</DomainName>[\n]"
<< " <Processing>true</Processing>[\n]"
<< " <SearchInstanceCount>1</SearchInstanceCount>[\n]"
<< " <ARN>arn:aws:cloudsearch:us-east-1:613875336225:domain/searchdev3</A
RN>[\n]"
<< " <Limits>[\n]"
<< " <AvailableInstanceTypes>[\n]"
<< " <member>search.m1.small</member>[\n]"
<< " <member>search.m3.medium</member>[\n]"
<< " <member>search.m3.large</member>[\n]"
<< " <member>search.m3.xlarge</member>[\n]"
<< " <member>search.m3.2xlarge</member>[\n]"
<< " </AvailableInstanceTypes>[\n]"
<< " <MaximumReplicationCount>5</MaximumReplicationCount>[\n]"
<< " <MaximumPartitionCount>10</MaximumPartitionCount>[\n]"
<< " </Limits>[\n]"
<< " </member>[\n]"
<< " </DomainStatusList>[\n]"
<< " </DescribeDomainsResult>[\n]"
<< " <ResponseMetadata>[\n]"
<< " <RequestId>2907d340-974e-11e5-a6e5-33953f55803d</RequestId>[\n]"
<< " </ResponseMetadata>[\n]"
<< "</DescribeDomainsResponse>[\n]"
Connection [id: 0][route: {s}->https://cloudsearch.us-east-1.amazonaws.com] can
be kept alive indefinitely
Connection released: [id: 0][route: {s}->https://cloudsearch.us-east-1.amazonaws
.com][total kept alive: 1; route allocated: 1 of 50; total allocated: 1 of 50]
Creating S3 source reader
Connection request: [route: {s}->https://mybucket.s3.amazonaws.com][total
kept alive: 0; route allocated: 0 of 50; total allocated: 0 of 50]
Connection leased: [id: 1][route: {s}->https://mybucket.s3.amazonaws.com]
[total kept alive: 0; route allocated: 1 of 50; total allocated: 1 of 50]
Connecting to mybucket.s3.amazonaws.com:443
CookieSpec selected: best-match
Auth cache not set in the context
Proxy auth state: UNCHALLENGED
Sending request: GET /?prefix=html HTTP/1.1
>> "GET /?prefix=html HTTP/1.1[\r][\n]"
>> "Host: mybucket.s3.amazonaws.com[\r][\n]"
>> "Authorization: AWS XXXXXXXX:eA+KR8i3SpRQdTS/pxeBeci7iOw=[\r][\n]
"
>> "User-Agent: aws-internal/3[\r][\n]"
>> "Date: Mon, 30 Nov 2015 10:36:05 +00:00[\r][\n]"
>> "Content-Type: application/x-www-form-urlencoded; charset=utf-8[\r][\n]"
>> "Connection: Keep-Alive[\r][\n]"
>> "[\r][\n]"
>> GET /?prefix=html HTTP/1.1
>> Host: mybucket.s3.amazonaws.com
>> Authorization: AWS XXXXXXXX:eA+KR8i3SpRQdTS/pxeBeci7iOw=
>> User-Agent: aws-internal/3
>> Date: Mon, 30 Nov 2015 10:36:05 +00:00
>> Content-Type: application/x-www-form-urlencoded; charset=utf-8
>> Connection: Keep-Alive
<< "HTTP/1.1 403 Forbidden[\r][\n]"
<< "x-amz-bucket-region: us-east-1[\r][\n]"
<< "x-amz-request-id: DA6567BEA36C46F9[\r][\n]"
<< "x-amz-id-2: kCC6NxI43AJi3G+YB0Dxgoc6ZrCGh/V3Wc4nhSnxk+mxYpdH50am3BBgzXfkLHrj
[\r][\n]"
<< "Content-Type: application/xml[\r][\n]"
<< "Transfer-Encoding: chunked[\r][\n]"
<< "Date: Mon, 30 Nov 2015 10:36:06 GMT[\r][\n]"
<< "Server: AmazonS3[\r][\n]"
<< "[\r][\n]"
Receiving response: HTTP/1.1 403 Forbidden
<< HTTP/1.1 403 Forbidden
<< x-amz-bucket-region: us-east-1
<< x-amz-request-id: DA6567BEA36C46F9
<< x-amz-id-2: kCC6NxI43AJi3G+YB0Dxgoc6ZrCGh/V3Wc4nhSnxk+mxYpdH50am3BBgzXfkLHrj
<< Content-Type: application/xml
<< Transfer-Encoding: chunked
<< Date: Mon, 30 Nov 2015 10:36:06 GMT
<< Server: AmazonS3
<< "117[\r][\n]"
<< "<?xml version="1.0" encoding="UTF-8"?>[\n]"
<< "<Error><Code>AccessDenied</Code><Message>AWS authentication requires a valid
Date or x-amz-date header</Message><RequestId>DA6567BEA36C46F9</RequestId><Host
Id>kCC6NxI43AJi3G+YB0Dxgoc6ZrCGh/V3Wc4nhSnxk+mxYpdH50am3BBgzXfkLHrj</HostId></Er
ror>"
<< "[\r][\n]"
<< "0[\r][\n]"
<< "[\r][\n]"
Connection [id: 1][route: {s}->https://mybucket.s3.amazonaws.com] can be
kept alive indefinitely
Connection released: [id: 1][route: {s}->https://mybucket.s3.amazonaws.co
m][total kept alive: 1; route allocated: 1 of 50; total allocated: 1 of 50]
AWS authentication requires a valid Date or x-amz-date header (Service: Amazon S
3; Status Code: 403; Error Code: AccessDenied; Request ID: DA6567BEA36C46F9)
Error Type: Client
Error Code: AccessDenied
HTTP Code: 403
Request ID: DA6567BEA36C46F9
[Ljava.lang.StackTraceElement;#12a7737
it seems you are using different version of java.
Please try to degrade java version. hope it will work. i had similar kind of issue before after degrading it to lower version fixed my problem.

NTLM authentication in axis2 client return error 401

I am using axis2 to create client code and access the wcf webservice with NTLM authentication. My client code is
Service1Stub stub = new Service1Stub();
Options options = stub._getServiceClient().getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("administrator");
auth.setPassword("passwrd");
auth.setHost("172.16.12.25");
auth.setDomain("MY-PC");
List<String> authSchemes = new ArrayList<String>();
authSchemes.add(HttpTransportProperties.Authenticator.NTLM);
auth.setAuthSchemes(authSchemes);
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
stub._getServiceClient().setOptions(options);
when I run my client code it returns the following error
org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:310)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:194)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.tempuri.Service1Stub.welcomeData(Service1Stub.java:473)
at ws.client.Client.myservice(Client.java:159)
at ws.client.Client.main(Client.java:50)
my header log is
>> "POST /Service1/Service1.svc HTTP/1.1[\r][\n]"
>> "Content-Type: text/xml; charset=UTF-8[\r][\n]"
>> "SOAPAction: "http://tempuri.org/IService1/WelcomeData"[\r][\n]"
>> "User-Agent: Axis2[\r][\n]"
>> "Content-Length: 278[\r][\n]"
>> "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGMAAAAAAAAAewAAAAkACQBAAAAADQANAEkAAAANAA0AVgAAAAAAAAB7AAAABlIAAFZJTk9USC1QQ0FETUlOSVNUUkFUT1IxNzIuMTYuMTIuMjQ11kmkEIwyUVitHBvTPwhExpcylZ9vkdwd[\r][\n]"
>> "Host: 172.16.12.25[\r][\n]"
>> "[\r][\n]"
>> "<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns1:WelcomeData xmlns:ns1="http://tempuri.org/"><ns1:helloservice>Hello Servie</ns1:helloservice></ns1:WelcomeData></soapenv:Body></soapenv:Envelope>"
<< "HTTP/1.1 401 Unauthorized[\r][\n]"
<< "HTTP/1.1 401 Unauthorized[\r][\n]"
<< "Content-Type: text/html[\r][\n]"
<< "Server: Microsoft-IIS/7.5[\r][\n]"
<< "WWW-Authenticate: NTLM[\r][\n]"
<< "X-Powered-By: ASP.NET[\r][\n]"
<< "Date: Thu, 10 May 2012 19:30:20 GMT[\r][\n]"
<< "Content-Length: 1293[\r][\n]"
<< "[\r][\n]"
<< "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[\r][\n]"
<< "<html xmlns="http://www.w3.org/1999/xhtml">[\r][\n]"
<< "<head>[\r][\n]"
<< "<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>[\r][\n]"
<< "<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>[\r][\n]"
<< "<style type="text/css">[\r][\n]"
<< "<!--[\r][\n]"
<< "body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}[\r][\n]"
<< "fieldset{padding:0 15px 10px 15px;} [\r][\n]"
<< "h1{font-size:2.4em;margin:0;color:#FFF;}[\r][\n]"
<< "h2{font-size:1.7em;margin:0;color:#CC0000;} [\r][\n]"
<< "h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} [\r][\n]"
<< "#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;[\r][\n]"
<< "background-color:#555555;}[\r][\n]"
<< "#content{margin:0 0 0 2%;position:relative;}[\r][\n]"
<< ".content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}[\r][\n]"
<< "-->[\r][\n]"
<< "</style>[\r][\n]"
<< "</head>[\r][\n]"
<< "<body>[\r][\n]"
<< "<div id="header"><h1>Server Error</h1></div>[\r][\n]"
<< "<div id="content">[\r][\n]"
<< " <div cla"
<< "ss="content-container"><fieldset>[\r][\n]"
<< " <h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>[\r][\n]"
<< " <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>[\r][\n]"
<< " </fieldset></div>[\r][\n]"
<< "</div>[\r][\n]"
<< "</body>[\r][\n]"
<< "</html>[\r][\n]
I don't know where I made mistake.
As far as I know, the standard release of Axis2 1.6 still uses HTTPClient 3.1 and thus NTLMv1, which most Windows servers have disabled by default. Changing this requires either patching Axis2 or changing the registry settings on the server.
Here's a link to the development thread with a patch as recent as 25-05-2012:
https://issues.apache.org/jira/browse/AXIS2-4318
Not sure if you have figured out a way to access WCF via NTLM authentication.. but this is what I did to fix this issue..
HttpClient doesnt support NTLM v2 hence I use JCIFS library to return NTLM v1,2,3 message type as described in this website
http://devsac.blogspot.com/2010/10/supoprt-for-ntlmv2-with-apache.html
I just used the JCIFS_NTLMScheme.java file from the above website to register the auth scheme and it worked !!!!
Sample client:
List authSchema = new ArrayList();
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, org.tempuri.JCIFS_NTLMScheme.class);
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("");
auth.setPassword("");
auth.setDomain("");
auth.setHost("");
auth.setPort();
List authPrefs = new ArrayList(1);
authPrefs.add(AuthPolicy.NTLM);
auth.setAuthSchemes(authPrefs);
stub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
As #WLPhoenix pointed out, Axis2 uses the old Apache Commons HTTP, which only supports an old, reverse-engineered NTLM implementation. In the new Apache HTTPComponents 4.2.3, support was added for the new, openly-documented NTLM standard, which works with newer versions of Windows Server and IIS (source).
Here is a way to backport the new Apache HTTPComponents 4 NTLMScheme for use in Axis2 using a custom Apache Commons HTTP AuthScheme.
public class BackportedNTLMScheme extends org.apache.http.impl.auth.NTLMScheme implements org.apache.commons.httpclient.auth.AuthScheme {
#Override
public String authenticate(final Credentials credentials, final HttpMethod method) throws AuthenticationException {
org.apache.commons.httpclient.NTCredentials oldCredentials;
try {
oldCredentials = (org.apache.commons.httpclient.NTCredentials) credentials;
} catch (final ClassCastException e) {
throw new InvalidCredentialsException(
"Credentials cannot be used for NTLM authentication: "
+ credentials.getClass().getName());
}
final org.apache.http.auth.Credentials adaptedCredentials = new NTCredentials(oldCredentials.getUserName(), oldCredentials.getPassword(), oldCredentials.getHost(), oldCredentials.getDomain());
try {
final Header header = super.authenticate(adaptedCredentials, null);
return header.getValue();
} catch (final org.apache.http.auth.AuthenticationException e) {
throw new AuthenticationException("AuthenticationException", e);
}
}
#Override
public void processChallenge(final String challenge) throws MalformedChallengeException {
final String s = AuthChallengeParser.extractScheme(challenge);
if (!s.equalsIgnoreCase(getSchemeName())) {
throw new MalformedChallengeException("Invalid NTLM challenge: " + challenge);
}
int challengeIdx = challenge.indexOf(' ');
final CharArrayBuffer challengeBuffer;
if(challengeIdx != -1){
challengeBuffer = new CharArrayBuffer(challenge.length());
challengeBuffer.append(challenge);
} else {
challengeBuffer = new CharArrayBuffer(0);
challengeIdx = 0;
}
try {
parseChallenge(challengeBuffer, challengeIdx, challengeBuffer.length());
} catch (final org.apache.http.auth.MalformedChallengeException e) {
throw new MalformedChallengeException("MalformedChallengeException", e);
}
}
#Override
#Deprecated
public String getID() {
throw new RuntimeException("deprecated BackportedNTLMScheme.getID()");
}
#Override
#Deprecated
public String authenticate(final Credentials credentials, final String method, final String uri) throws AuthenticationException {
throw new RuntimeException("deprecated BackportedNTLMScheme.authenticate(Credentials, String, String)");
}
}
Usage
// given a stubbed AXIS SOAP client called MyAxisClient:
MyAxisClientStub myAxisClient = new MyAxisClientStub();
ServiceClient serviceClient = myAxisClient._getServiceClient();
// use new NTLM
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, BackportedNTLMScheme.class);
Authenticator authenticator = new Authenticator();
authenticator.setAuthSchemes(Arrays.asList(AuthPolicy.NTLM));
authenticator.setDomain("my-auth-domain");
authenticator.setHost("my-auth-host");
authenticator.setUsername("my-username");
authenticator.setPassword("my-password");
serviceClient.getOptions().setProperty(HTTPConstants.AUTHENTICATE, authenticator);
//call MyAxisClient methods
I tested this on IIS 7.5 on Windows Server 2008 R2.
I could not get this to work until a coworker found this which fixed 401 Unauthorized.
import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
import org.apache.commons.httpclient.auth.CredentialsProvider;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.NTCredentials;
final NTCredentials credentials = new NTCredentials(username, password, host, domain);
final CredentialsProvider myCredentialsProvider = new CredentialsProvider() {
public Credentials getCredentials(final AuthScheme scheme, final String host, int port, boolean proxy) throws CredentialsNotAvailableException {
return credentials;
}
};
DefaultHttpParams.getDefaultParams().setParameter("http.authentication.credential-provider", myCredentialsProvider);

problem in making custom root certificate store for SSL using QT?

I am developing my custom browser in Qt using QWebView and
I am trying to make my own root cert store of trusted certificates which are taken from mozilla project.
I have used QSslSocket::setDefaultCaCertificates() to override the default certificates.
But I am not able to load https://www.gmail.com , where as in mozilla it works.
I have set all required root certs for gmail to my store.
can anyone guide me ?
The reason you can't connect is because the SSL certificate (with serial 2F:DF:BC:F6:AE:91:52:6D:0F:9A:A3:DF:40:34:3E:9A) presented to you when you connect to www.gmail.com is issued for a different domain - www.google.com. This has nothing to do with root CA certificate store because no root CA certificate is needed to compare cert's Subject CN field with the host you are trying to connect to. You can ignore this and other SSL errors by calling
void QNetworkReply::ignoreSslErrors () [virtual slot]
To avoid this error you can connect directly to https://mail.google.com which is the domain you are being redirected to when you try to connect to https://www.gmail.com
Below is a working example which will show you the exact SSL errors and QNAM level errors. Either line B1 or line B2 must be active at the same time. You can comment line A if you want to see what happens with the default (system) root CA certificate store. There are two certs used by this code; CA's cert with serial 30:00:00:02 should be placed in a file called ThawteSGCCA.crt and CA's cert with serial 70:BA:E4:1D:10:D9:29:34:B6:38:CA:7B:03:CC:BA:BF should be placed in a file called BuiltinObjectToken-VerisignClass3PublicPrimaryCertificationAuthority.crt.
#include <QtGui/QApplication>
#include <QtCore/QDebug>
#include <QtCore/QList>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QSslConfiguration>
#include <QtNetwork/QSslSocket>
#include <QtNetwork/QSslError>
#include <QtWebKit/QWebFrame>
#include <QtWebKit/QWebPage>
class Handler : public QObject{
Q_OBJECT
public slots:
void slotLoadFinished(bool ok) {
if (ok) {
qDebug() << "Page size: " << static_cast<QWebPage*>(sender())->mainFrame()->toHtml().size();
}
}
void slotFinished(QNetworkReply * reply) {
if (reply->error() == QNetworkReply::NoError) {
qDebug() << "connected to " << reply->url();
qDebug() << "HTTP status: " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
} else {
qDebug() << "error while connecting to " << reply->url();
qDebug() << "error code: " << reply->error();
qDebug() << "error string: " << reply->errorString();
}
}
void slotSslErrors(QNetworkReply * reply, QList<QSslError> const & errors) {
qDebug() << "SSL errors: " << errors;
qDebug() << "peer's certificate: "
<< reply->sslConfiguration().peerCertificate();
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Handler handler;
// CA certs for:
// 1. cert with Subject.CN == mail.google.com cert with serial 1f:19:f6:de:35:dd:63:a1:42:91:8a:d5:2c:c0:ab:12
// 2. cert with Subject.CN == www.google.com cert with serial 2F:DF:BC:F6:AE:91:52:6D:0F:9A:A3:DF:40:34:3E:9A
QList<QSslCertificate> CAcerts =
// serial 30:00:00:02
QSslCertificate::fromPath("ThawteSGCCA.crt") +
// serial 70:BA:E4:1D:10:D9:29:34:B6:38:CA:7B:03:CC:BA:BF
QSslCertificate::fromPath("BuiltinObjectToken-VerisignClass3PublicPrimaryCertificationAuthority.crt");
qDebug() << "root CA certificates:\n"
<< CAcerts
<< "\n";
QSslSocket::setDefaultCaCertificates(CAcerts); // line A
QWebPage page;
// OK because cert with serial 1f:19:f6:de:35:dd:63:a1:42:91:8a:d5:2c:c0:ab:12 is for host mail.google.com
// page.mainFrame()->load(QUrl("https://mail.google.com")); // line B1
// SSL ERROR "The host name did not match any of the valid hosts for this certificate"
// because cert with serial 1f:19:f6:de:35:dd:63:a1:42:91:8a:d5:2c:c0:ab:12 is NOT for www.gmail.com
page.mainFrame()->load(QUrl("https://www.gmail.com")); // line B2
QObject::connect(page.networkAccessManager(), SIGNAL(finished(QNetworkReply*)), &handler, SLOT(slotFinished(QNetworkReply*)));
QObject::connect(page.networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), &handler, SLOT(slotSslErrors(QNetworkReply*,QList<QSslError>)));
QObject::connect(&page, SIGNAL(loadFinished(bool)), &handler, SLOT(slotLoadFinished(bool)));
return app.exec();
}
#include "main.moc"