Why is my Destination IP Address seen as my Source IP Address when attempting to connect from a Handheld Device? - compact-framework

I am trying to call a REST method on a server from a handheld device with this code:
public static void WriteIt2( string fileName, string data )
{
// "filename" is what the file to save will be named; "data" is the contents of that file
if (File.Exists(fileName))
{
MessageBox.Show(String.Format("{0} exists - deleting", fileName));
File.Delete(fileName);
}
string justFileName = Path.GetFileNameWithoutExtension(fileName);
String uri = String.Format("http://192.168.125.50:21608/api/inventory/sendXML/duckbilled/platypus/{0}", justFileName);
SendXMLFile2(uri, data);
}
public static void SendXMLFile2(string uri, string data)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "Post";
req.ContentType = "text/plain; charset=utf-8";
byte[] encodedBytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(encodedBytes, 0, encodedBytes.Length);
requestStream.Close();
WebResponse result = req.GetResponse();
MessageBox.Show(result.ToString());
}
The breakpoint in my server code is not getting reached; I'm trying to find out why. I'm using RawCap and Wireshark to try to see exactly what's going on. After running RawCap and opening the .pcap file it creates in WireShark, and by then searching for any appearances of the port I'm trying to access (via Edit > Find Packet > Packet Bytes with "21608" as the search string") I found this in the Data for the only packet that contains that string:
SBCMYReportProviderStatusMessage#bgM
%<NetworkShield`http://192.168.125.50:21608/api/inventory/sendXML/duckbilled/platypus/INV_0000003.0916201413022
6z )
...so the code running on the handheld device is being picked up by WireShark, but Wireshark shows 192.168.125.50 as "Source" and 192.168.125.87 as "Destination" (Protocol == TCP, where I would kind of expect it to be HTTP).
192.168.125.50 is my PC's IP Address (should be the Destination, not the Source, right?)
192.168.125.87, the Destination, according to "nbtstat -a 192.168.125.87" is "BUCK, UNIQUE" I don't know or what "BUCK" is...(obviously, a computer on the local network)
The IP Address of the handheld is 192.168.55.101
Why does Wireshark not show 192.168.55.101 as the Source and 192.168.125.50 as the Destination? Is it possible to determine the reason for the failure (the REST method not getting hit) from this Wireshark data?
UPDATE
By right-clicking the Packet record in WireShark and selecting "Follow TCP Stream" I get the following:
SBCM.................w.......R.e.p.o.r.t.P.r.o.v.i.d.e.r.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<....F.i.l.e.S.y.s.t.e.m.S.h.i.e.l.d.....l...C.:.\.W.i.n.d.o.w.s.\.a.s.s.e.m.b.l.y.\.N.a.t.i.v.e.I.m.a.g.e.s._.v.2...0...5.0.7.2.7._.3.2.. . . . [ much more of the same type of thing elided ]
.................SBCM.................Y.......R.e.p.o.r.t.P.r.o.v.i.d.e.r.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<
...N.e.t.w.o.r.k.S.h.i.e.l.d.....`...h.t.t.p.:././.1.9.2...1.6.8...1.2.5...5.0.:.2.1.6.0.8./.a.p.i./.i.n.v.e.n.t.o.r.y./.s.e.n.d.X.M.L./.d.u.c.k.b.i.l.l.e.d./.p.l.a.t.y.p.u.s./.I.N.V._.0.0.0.0.0.0.3...0.9.1.6.2.0.1.4.1.3.0.2.2.6.....z ......)...SBCM.........................R.e.p.o.r.t.P.r.o.v.i.d.e.r.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<....W.e.b.R.e.p........................JSBCM.........................R.e.p.o.r.t.M.a.i.n.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<............................$.....O6.........R8e....E.......C.......C....B_.................SBCM.........................R.e.p.o.r.t.P.r.o.v.i.d.e.r.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<....W.e.b.R.e.p........................JSBCM.........................R.e.p.o.r.t.M.a.i.n.S.t.a.t.u.s.M.e.s.s.a.g.e.#...bg.M.....%.<............................$.....O6.........R8e....E.......C.......C....B_.................
I cannot make heads or tails of this; I don't know what I should expect to see after my uri...I don't see any "ack" of either success or failure...

Related

Send certificate in http request header - c++

I have a certificate that I need to send in the header of an http request. This is how I acquired the cert:
PCCERT_CONTEXT cert = nullptr;
wstring store = // store name
wstring subjectName = // subject name
HCERTSTORE hStoreHandle = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
0,
NULL,
CERT_SYSTEM_STORE_CURRENT_USER,
store.c_str());
cert = CertFindCertificateInStore(
hStoreHandle,
X509_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR,
subjectName.c_str(),
NULL);
I need to send it as a custom header, as the load balancer that sits in front of my service strips off the certificate header ["X-ARR-CLIENTCERT"] before forwarding the request. I believe I need to send the cert->pbCertEncoded, but on the server, I can't decode it and convert it back to an X509Certificate2.
This is what I tried on the client:
request.headers().add("client-cert", cert->pbCertEncoded);
On the server:
var headerCert = Request.Headers["client-cert"];
byte[] certdata = Convert.FromBase64String(headerCert);
X509Certificate2 cert = new X509Certificate2(certdata);
The request header on the server is non-null. But it cannot parse it back to an X509Certificate2.
I tried another thing on the client. After getting the cert, I converted it to a string
DWORD size = 0;
CryptBinaryToString(cert->pbCertEncoded, cert->cbCertEncoded, CRYPT_STRING_BASE64, NULL, &size);
LPWSTR outstring = new TCHAR[size];
CryptBinaryToString(cert->pbCertEncoded, cert->cbCertEncoded, CRYPT_STRING_BASE64, outstring, &size);
If I try to send outstring in the header, it complains:
WinHttpAddRequestHeaders: 87: The parameter is incorrect.
But when I take the contents of outstring and try to parse it on the server, it decodes back to the right certificate. This tells me that I'm not doing something right when passing cert->pbCertEncoded in the header. Maybe I need to re-encode it or transform it somehow so the server can correctly parse it? I'd appreciate any help. Thanks!
My client is in c++ and server in .NET. I'm using cpprestsdk to send the certificate in the http request.
The pbCertEncoded is the ASN.1 encoded representation of the certificate. Look for instance here.
So you must encode the bytes to base64 for instance like this:
#include <Wincrypt.h>
#pragma comment (lib, "Crypt32.lib")
int ToBase64Crypto(const BYTE* pSrc, int nLenSrc, char* pDst, int nLenDst )
{
DWORD nLenOut = nLenDst;
BOOL fRet = CryptBinaryToString(
(const BYTE*)pSrc,
nLenSrc,
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
pDst, &nLenOut
);
if (!fRet) {
nLenOut=0; // failed
}
return (nLenOut);
}

what is correct use of consumer groups in spring cloud stream dataflow and rabbitmq?

A follow up to this:
one SCDF source, 2 processors but only 1 processes each item
The 2 processors (del-1 and del-2) in the picture are receiving the same data within milliseconds of each other. I'm trying to rig this so del-2 never receives the same thing as del-1 and vice versa. So obviously I've got something configured incorrectly but I'm not sure where.
My processor has the following application.properties
spring.application.name=${vcap.application.name:sample-processor}
info.app.name=#project.artifactId#
info.app.description=#project.description#
info.app.version=#project.version#
management.endpoints.web.exposure.include=health,info,bindings
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
spring.cloud.stream.bindings.input.group=input
Is "spring.cloud.stream.bindings.input.group" specified correctly?
Here's the processor code:
#Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Object transform(String inputStr) throws InterruptedException{
ApplicationLog log = new ApplicationLog(this, "timerMessageSource");
String message = " I AM [" + inputStr + "] AND I HAVE BEEN PROCESSED!!!!!!!";
log.info("SampleProcessor.transform() incoming inputStr="+inputStr);
return message;
}
Is the #Transformer annotation the proper way to link this bit of code with "spring.cloud.stream.bindings.input.group" from application.properties? Are there any other annotations necessary?
Here's my source:
private String format = "EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ";
#Bean
#InboundChannelAdapter(value = Source.OUTPUT, poller = #Poller(fixedDelay = "1000", maxMessagesPerPoll = "1"))
public MessageSource<String> timerMessageSource() {
ApplicationLog log = new ApplicationLog(this, "timerMessageSource");
String message = new SimpleDateFormat(format).format(new Date());
log.info("SampleSource.timeMessageSource() message=["+message+"]");
return () -> new GenericMessage<>(new SimpleDateFormat(format).format(new Date()));
}
I'm confused about the "value = Source.OUTPUT". Does this mean my processor needs to be named differently?
Is the inclusion of #Poller causing me a problem somehow?
This is how I define the 2 processor streams (del-1 and del-2) in SCDF shell:
stream create del-1 --definition ":split > processor-that-does-everything-sleeps5 --spring.cloud.stream.bindings.applicationMetrics.destination=metrics > :merge"
stream create del-2 --definition ":split > processor-that-does-everything-sleeps5 --spring.cloud.stream.bindings.applicationMetrics.destination=metrics > :merge"
Do I need to do anything differently there?
All of this is running in Docker/K8s.
RabbitMQ is given by bitnami/rabbitmq:3.7.2-r1 and is configured with the following props:
RABBITMQ_USERNAME: user
RABBITMQ_PASSWORD <redacted>:
RABBITMQ_ERL_COOKIE <redacted>:
RABBITMQ_NODE_PORT_NUMBER: 5672
RABBITMQ_NODE_TYPE: stats
RABBITMQ_NODE_NAME: rabbit#localhost
RABBITMQ_CLUSTER_NODE_NAME:
RABBITMQ_DEFAULT_VHOST: /
RABBITMQ_MANAGER_PORT_NUMBER: 15672
RABBITMQ_DISK_FREE_LIMIT: "6GiB"
Are any other environment variables necessary?

C# "The request was aborted: Could not create SSL/TLS secure channel." - happening occasionally

This is a request to GoCardless test API from a Dynamics CRM plugin. I receive "The request was aborted: Could not create SSL/TLS secure channel." error. It only happens on the first request after some time without sending one. If I send it again, it will be OK. I would appreciate a lot your help.
Here is my code:
//I have tried all the following lines in comment without success
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//ServicePointManager.Expect100Continue = true;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// Create a new WebClient instance.
string baseURL = "https://api-sandbox.gocardless.com/";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", "Bearer " + t);
client.Headers.Add("GoCardless-Version", "2015-07-06");
client.Headers.Add("Accept", "application/json");
Customers model = new Customers();
customer.country_code = "GB";
model.customers = customer;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customers));
ser.WriteObject(stream1, model);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] byteArray = Encoding.ASCII.GetBytes(sr.ReadToEnd());
ReturnedCustomers result = new ReturnedCustomers();
//Upload the input string using the HTTP 1.0 POST method.
try
{
byte[] responseArray = client.UploadData(baseURL + "customers", "POST", byteArray);
string responseText = Encoding.ASCII.GetString(responseArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ReturnedCustomers));
using (Stream s = GenerateStreamFromString(responseText))
{
result = (ReturnedCustomers)serializer.ReadObject(s);
}
}
catch (WebException exception)
{
}
From the Microsoft documentation (https://msdn.microsoft.com/en-us/library/gg334752.aspx) are the following limitations:
Only the HTTP and HTTPS protocols are allowed.
Access to localhost (loopback) is not permitted.
IP addresses cannot be used. You must use a named web address that requires DNS name resolution.
Anonymous authentication is supported and recommended.
5.There is no provision for prompting the logged on user for credentials or saving those credentials.
The error may be due to seguneti things:
The certificate is invalid
The certification authority is not public
Could you check what is the value of ServicePointManager.Expect100Continue and ServicePointManager.SecurityProtocol attributes in your environment?

Processing-java sketch( server ) not responding in the way I want it to

I have created a processing-java sketch. This sketch is the server. All I want this program to do is that the client and server can connect and write messages(sentences) between each other. Case 1 was successful, but case 2 was not. I have explained the process for each case and what went wrong/successful.
Case 1) On the same computer(Mac), I started the server program and on Terminal("Command Prompt" on Mac), I typed telnet local host 5204 and the client(Mac) connected with the server(Mac). I was able to type sentences (or Strings) between the server and client and it was successful. So whatever sentence I type in the server, it was visible to the client and vice versa. Note: The server and client were both in the same computer.
Case 2) On the Mac, I started the server program. On another computer(Windows 7)
I connected to the server via Command Prompt. The connection was successful. In this case, the Strings could be sent from the server to the client and the Strings were visible to the client. But when I tried to send Strings to the server from the client, the server could only receive the information character by character, not as an entire sentence/String. I tried changing the port number, the client device, the frameRate, but I still had no success.
This is my problem. Please comment if my question could be clearer or if I need to give more details. Thank you for answering.
Below is my Server code:
import processing.net.*;
Server myServer;
//Strings from server and client
String typing = "";
String c = "";
void setup() {
size(400, 400);
//creating server on port 5204
myServer = new Server(this, 5204);
}
void draw() {
background(255);
//displaying server's text and client's text
fill(0);
text(typing, 100, 100);
text("Client: " + c, 100, 150);
Client client = myServer.available();
if(client != null) {
//reading input from client
c = client.readString();
c.trim();
}
}
void keyPressed() {
//Server can type sentences to client
if(key == '\n') {
myServer.write(typing + '\n');
typing = "";
}else{
typing = typing + key;
}
}
Did you try ncat for Windows?
With it you can try: echo Text to send & echo. | ncat localhost 5204
Source

FileUpload using HttpWebRequest returns (411) Length Required Error

I have written an ActiveX control which supports drag-drop of email attachments and disk files and uploads files to a web server.
I used the samples available at this link for Uploading files
Upload files with HTTPWebrequest (multipart/form-data)
I am sending data in chunks by setting the following properties
wr = (HttpWebRequest)WebRequest.Create(UploadUrl);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.ContentLength = contentLength;
wr.AllowWriteStreamBuffering = false;
wr.Timeout = 600000;
wr.KeepAlive = false;
wr.ReadWriteTimeout = 600000;
wr.ProtocolVersion = HttpVersion.Version10;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.SendChunked = true;
wr.UserAgent = "Mozilla/3.0 (compatible; My Browser/1.0)";
rs = wr.GetRequestStream();
With the above settings I am getting an error (411) Length Required.
After reading the following article I realized, I dont need to set Content-Length property when I set SendChunked = true;
http://en.wikipedia.org/wiki/Chunked_transfer_encoding
But the Microsoft example code here doesn't do so
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.sendchunked.aspx
After further digging I came to know that Chunked encoding is supported in HTTP version 1.1 only. So I changed the property as follows
wr.ProtocolVersion = HttpVersion.Version11;
Now I don't see that 411 error any more.
Now, can someone with better knowledge verify my understanding here and please let me know if I am doing right.
Thanks
Ravi.
They are both just mechanisms to let the receiver know when it has reached the end of the transfer. If you want to use Content-Length, it is pretty simple. Just take your encoded byte array of POST data, and use the Length property.
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] postDataByteArray = encoding.GetBytes (postData);
wr.ContentLength = postDataByteArray.Length;