How to handle server-client requests - c++

Currently I'm working on a Server-Client system which will be the backbone of my application.
I have to find the best way to send requests and handle them on the server-side.
The server-side should be able to handle requests like this one:
getPortfolio -i 2 -d all
In an old project I decided to send such a request as string and the server application had to look up the first part of the string ("getPortfolio"). Afterwards the server application had to find the correct method in a map which linked the methods with the the first part of the string ("getPortfolio"). The second part ("-i 2 -d all") got passed as parameter and the method itself had to handle this string/parameter.
I doubt that this is the best solution in order to handle many different requests.
Rgds
Layne

To me it seems you're having two different questions.
For the socket part, I suggest you use Beej's guide to socket programming if you want to have full control about what you do. If you don't want to/don't have the time to treat this part yourself, you can just use a C++ socket library as well. There are plenty of them; I only used this one so far, but others might be as just good (or even better).
Regarding your parsing algorithm, you may first write down everything about the message format, so you'll have a strict guideline to follow. Then process step by step:
First, extract the "first word" and just keep the following parameters in some list. Check if the first word is valid and if it is known. If the "first word" does not match with any of the predefined existing functions, just ignore the message (and eventually report the error to the client application).
Once you have the matching function, simply call it passing the others parameters.
This way, each function will do a specific task and your code will be splitted in an elegant way.
Unfortunately, it is difficult for me to be any more explicit since we somehow lack of details here.

Related

Transport Rule Logical And for Exchange 2010

Good Afternoon,
I have exhausted my googling and best-guess ideas, so I hope someone here has an idea of whether this is possible or not.
I am using Exchange Server 2010 (vanilla) in a test environment and trying to create a Hub Transport Rule using the Exchange Management Console. The requirements of the rules filtering are similar to the following scenario:
1.) If a recipient's address matches (ends with) "#testdomain.com" AND (begins with) "john"
2.) If the sender's address matches (ends with) "#testdomain.com"
3.) Copy the message to the "SupervisorOfJohns#testdomain.com" mailbox
I have no problems doing items 2 and 3, but I cannot figure out how to get item 1 in the same condition. I have come across some threads that simply concluded that MS goofed on this, but I am hesitant to fault them for something which seems like it should be really straightforward. I must be missing something. Expressions I have tried so far...:
1.) (^john)(#testdomain.com$)
2.) ^(john)(#testdomain.com)$
3.) (^john)#testdomain.com
4.) ^john #testdomain.com$
5.) ^(john)#testdomain.com
If you use the interface and +Add them as two separate entries, it treats them as an OR clause (if a recipient address begins with "john", OR it ends with "#testdomain.com"). As you can see from my simplistic attempts, I have barely any clue what can/should work in this case. Any suggestions or ideas would be appreciated.
Respectfully,
B. Whitman
Here's what I ended up using:
john\w*#testdomain.com
The reasoning behind the question is that I'm trying to make a service to catch certain e-mails and do some processing with them. I also wanted to restrict the senders/recipients to certain domains (though some checking will also be done with the processing service). Thanks to hjpotter92 for his solutions!

What is the best way to encrypt hardcoded strings in C++?

Warning: C++ noob
I've read multiple posts on StackOverflow about string encryption. By the way, they don't answer my doubts.
I must insert one or two hardcoded strings in my code but I would like to make it difficult to read in plain text when debugging/reverse engineering. That's not all: my strings are URLs, so a simple packet analyzer (Wireshark) can read it.
I've said difficult because I know that, when the code runs, the string is somewhere (in RAM?) decrypted as plain text and somebody can read it. So, assuming that is not possible to completely secure my string, what is the best way of encrypting/decrypting it in C++?
I was thinking of something like this:
//I've omitted all the #include and main stuff of course...
string encryptedUrl = "Ajdu67gGHhbh34590Hb6vfu6gu" //Encrypted url with some known algorithm
URLDownloadToFile(NULL, encryptedUrl.decrypt(), C:\temp.txt, 0, NULL);
What about packet analyzing? I'm sure there's no way to hide the URL but maybe I'm missing something? Thank you and sorry for my worst english!
Edit 1: What my application does?
It's a simple login script. My application downloads a text file from an URL. This file contains an encrypted string that is read using fstream library. The string is then decrypted and used to login on another site. It is very weak, because there's no database, no salt, no hashing. My achievement is to ensure that neither the url nor the login string are "easy" to read from a static analisys of the binary, and possibly as hard as possible with a dynamic analysis (debugging, revers engineering, etc).
If you want to stymie packet inspectors, the bare minimum requirement is to use https with a hard-coded server certificate baked into your app.
There is no panacea for encrypting in-app content. A determined hacker with the right skills will get at the plain url, no matter what you do. The best you can hope for is to make it difficult enough that most people will just give up. The way to achieve this is to implement multiple diverse obfuscation and tripwire techniques. Including, but not limited to:
Store parts of the encrypted url and the password (preferably a one-time key) in different locations and bring them together in code.
Hide the encrypted parts in large strings of randomness that looks indistinguishable from the parts.
Bring the parts together piecemeal. E.g., Concatenate the first and second third of the encrypted url into a single buffer from one initialisation function, concatenate this buffer with the last third in a different unrelated init function, and use the final concatenation in yet another function, all called from different random places in your code.
Detect when the app is running under a debugger and have different functions trash the encrypted contents at different times.
Detection should be done at various call sites using different techniques, not by calling a single "DetectDebug" function or testing a global bool, both of which create a single point of attack.
Don't use obvious names, like, "DecryptUrl" for the relevant functions.
Harvest parts of the key from seemingly unrelated, but consistent sources. E.g., read the clock and only use a few of the high bits (high enough that that they won't change for the foreseeable future, but low enough that they're not all zero), or use a random sampling of non-volatile results from initialisation code.
This is just the tip of the iceberg and will only throw novices off the scent. None of it is going to stop, or even significantly slow down, a skillful attacker, who will simply intercept calls to the SSL library using a stealth debugger. You therefore have to ask yourself:
How much is it worth to me to protect this url, and from what kind of attacker?
Can I somehow change the system design so that I don't need to secure the url?
Try XorSTR [1, 2]. It's what I used to use when trying to hamper static analysis. Most results will come from game cheat forums, there is an html generator too.
However as others have mentioned, getting the strings is still easy for anyone who puts a breakpoint on URLDownloadToFile. However, you will have made their life a bit harder if they are trying to do static analysis.
I am not sure what your URL's do, and what your goal is in all this, but XorStr + anti-debug + packing the binary will stop most amateurs from reverse engineering your application.

I want to show off my C++ projects through a website

The problem is that, well, it's C++. The way I've created them makes it such that they've always been run via a terminal/console window and wait for user input or else simply take a sample input and run with that. The output has also always been to the terminal screen or sometimes to a file. I'm not quite sure how I could take all of that and integrate it with a website while leaving the source code as it is, if that's at all possible. I guess what I'm trying to aim for is to have whatever website I use behave like a terminal window that will accept user input and then send it off to run the C++ program in question and return with the output (whatever it may be), all with minimal modification to the source code. Either that or else set up a more automated kind of page where a user can just click 'Go' and the program will run using a sample input.
When it comes to web I consider myself intermediate with HTML, CSS, PHP & MySQL, and a beginner with Javascript, so if this can be accomplished using those languages, that would be fantastic. If not, don't be afraid to show me something new though.
The easiest interaction model to bring to the web is an application that takes its input up front and produces its output on stdout. In this situation, as the unknown poster mentioned, you could use CGI. But due to the nature of CGI, this will only work (in the simplest sense) if all the information is collected from the user in one page, sent to the application and the results returned in one page. This is because each invocation of a page using CGI spawns a new indepdent process to serve the request. (There are other more efficient solutions now, such as FastCGI which keeps a pool of processes around.) If your application is interactive, in that it collects some information, presents some results, prints some options, collects some more user input, then produces more results, it will need to be adapted.
Here is about the simplest possible CGI program in C++:
#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Content-type: text/plain\n" << std::endl;
std::cout << "Hello, CGI World!" << std::endl;
}
All it does is return the content type followed by a blank line, then the actual content with the usual boring greeting.
To accept user input, you would write a form in HTML, and the POST target would be your application. It will be passed a string containing the parameters of the request, in the usual HTTP style:
foo.cgi?QTY=123&N=41&DESC=Simple+Junk
You would then need to parse the query string (which is passed to the program via the QUERY_STRING environment variable) to gather the input fields from the form to pass to your application. Beware, as parsing parameter strings is the source of a great number of security exploits. It would definitely be worthwhile finding a CGI library for C++ (a Google search reveals many) that does the parsing for you. The query data can be obtained with:
const char* data = getenv("QUERY_STRING");
So at a minimum, you would need to change your application to accept its input from a query string of name=value pairs. You don't even need to generate HTML if you don't want to; simply return the content type as text/plain to begin with. Then you can improve it later with HTML (and change the content type accordingly).
There are other more sophisticated solutions, including entire web frameworks such as Wt. But that would involve considerable changes to your apps, which you said you wished to avoid.
Almost off-topic, but you might want to take a look at Wt.
have you considered using cgi ... its 19th century technology which lets webserver execute programs written in C/C++ to run and generate output
I do not know much about it ... but I used it for some school projects
Show it all off with Screencasts. I use Camtasia Studio, but there are a ton of them out there: http://en.wikipedia.org/wiki/Screencast
Camtasia will even generate all of the HTML and Flash you need to upload to your web server. Buy a nice USB microphone, and write a script of what you're going to say and show.
What is the purpose of showing off your projects? Do you wish to impress your friends or employers?
It doesn't seem feasible to emulate or port your C++ console apps through a web interface.
I suppose you could write a bridge between a server side script and your C++ binary which passes the user input through to your app, then returns the result through the web interface. Bear in mind this would be a huge task for you to undertake.
Ruby have a compiler on their website which demonstrates this can be done.
However no one on the web would expect to run your C++ apps in a web browser. Also I think that anyone who is interested in running a C++ app would be totally comfortable with downloading a C++ binary that you made and running it (apart from the security risk) but when you think about it we download apps and run them all the time, whilst trusting the source.
I have a portfolio website which I created for the purpose of letting employers see my work. Take a look, it will give you an idea of another way you can do things.
Basically I provide the binaries for download, videos, screenshots and links. Things that the user can use to see my work quickly if they don't have time (or an appropriate computer) to run my projects on.
Good luck
I have no experience with this (other than hearing a guy on BART talk about implementing his server-side code all in C), but you might consider taking a look at SWIG (http://www.swig.org/). It allows you to wrap C++ so that you can access C++ code when using languages such as PHP.

How do I extract the network protocol from the source code of the server?

I'm trying to write a chat client for a popular network. The original client is proprietary, and is about 15 GB larger than I would like. (To be fair, others call it a game.)
There is absolutely no documentation available for the protocol on the internet, and most search results only come back with the client's scripting interface. I can understand that, since used in the wrong way, it could lead to ruining other people's experience.
I've downloaded the source code of a couple of alternative servers, including the one I want to connect to, but those
contain no documentation other than install instructions
are poorly commented (I did a superficial browsing)
are HUGE (the src folder of the target server contains 12 MB worth of .cpp and .h files), and grep didn't find anything related
I've also tried searching their forums and contacting the maintainers of the server, but so far, no luck.
Packet sniffing isn't likely to help, as the protocol relies heavily on encryption.
At this point, all my hope is my ability to chew through an ungodly amount of code. How do I start?
Edit: A related question.
If your original code is encrypted with some well known library like OpenSSL or Ctypto++ it might be useful to write your wrapper for the main entry points of these libraries, then delagating the call to the actual library. If you make such substitution and build the project successfully, you will be able to trace everything which goes out in the plain text way.
If your project is not using third party encryption libs, hopefully it is still possible to substitute the encryption routines with some wrappers which trace their input and then delegate encryption to the actual code.
Your bet is that usually enctyption is implemented in separate, relatively small number of source files so that should be easier for you to track input/output in these files.
Good luck!
I'd say
find the command that is used to send data through the socket (the call depends on the network library)
find references of this command and unroll from there. If you can modify-recompile the server code, it might help.
On the way, you will be able to log decrypted (or, more likely, not yet encrypted) network activity.
IMO, the best answer is to read the source code of the alternative server. Try using a good C++ IDE to help you. It will make a lot of difference.
It is likely that the protocol related material you need to understand will be limited to a subset of the files. These will contain references to network sockets and things. Start from there and work outwards as far as you need to.
A viable approach is to tackle this as a crypto challenge. That makes it easy, because you control so much.
For instance, you can use a current client to send a known message to the server, and then check server memory for that string. Once you've found out in which object the string ends, it also becomes possible to trace its ancestry through the code. Set a breakpoint on any non-const method of the object, and find the stacktraces. This gives you a live view of how messages arrive at the server, and a list of core functions essential to message processing. You can next find related functions (caller/callee of the functions on your list).

Web Service to return complex object with optional parts

I'm trying to think of the correct design for a web service. Essentially, this service is going to perform a client search in a number of disparate systems, and return the results.
Now, a client can have various pieces of information attached - e.g. various pieces of contact information, their address(es), personal information. Some of this information may be complex to retrieve from some systems, so if the consumer isn't going to use it, I'd like them to have some way of indicating that to the web service.
One obvious approach would be to have different methods for different combinations of wanted detail - but as the combinations grow, so too do the number of methods. Another approach I've looked at is to add two string array parameters to the method call, where one array is a list of required items (e.g. I require contact information), and the other is optional items (e.g. if you're going to pull in their names anyway, you might as well return that to me).
A third approach would be to add additional methods to retrieve the detail. But that's going to explode the number of round trips if I need all the details for potentially hundreds of clients who make up the result.
To be honest, I'm not sure I like any of the above approaches. So how would you design such a generic client search service?
(Considered CW since there might not be a single "right" answer, but I'll wait and see what sort of answers arrive)
Create a "criteria" object and use that as a parameter. Such an object should have a bunch of properties to indicate the information you want. For example "IncludeAddresses" or "IncludeFullContactInformation".
The consumer is then responsible to set the right properties to true, and all combinations are possible. This will also make the code in the service easier to do. You can simply write if(criteria.IncludeAddresses){response.Addresses = GetAddresses;}
Any non-structured or semi-structured data is best handled by XML. You might pass XML data via a string or wrap it up in a class adding some functionality to it. Use XPathNavigator to go through XML. You can also use XMLDocument class although it is not too friendly to use. Anyway, you will need some kind of class to handle XML content of course.
That's why XML was invented - to handle data which structure is not clearly defined.
Regards,
Maciej