prepopulate cin before reading it - c++

I am writing a program in C++ (in Borland C++ builder 6.0) that reads and displays customer data through cin and cout and stores and reads it to and from a database (sqlite).
It uses a console for interaction with the user.
What I want to achieve is that the user can update customer data that has been written previously into the database (e.g. data like name, address, etc)
When the user is going to update customer data, I want to let him go through the same steps/data as when creating a customer, but now, the data that the user wants to enter or modify has been prepopulated (as read from the database) and already displayed on the console, i.e. written into the input buffer cin, like it was typed in by the user. The user then only needs to hit enter to go to the next step/data and leave the data as it was. If the user needs to change or updata the data, he needs to change the data that was read from the database and displayed, but can modify it as he likes after which it will be written/updated into the database.
I hope it's clear what I mean.

This can't be done (trivially - almost anything CAN be done if you just put enough effort into it, the trick is to know when to put the effort on doing it a better way!) with cin/cout. You are much better off using some sort of text-mode UI library, such as ncurses or similar.
I have written a lot of code that did something similar, but I wrote my own set of functions to manage cursor position, input of data with validation, selecting things from lists, etc, etc. You will probably have to do SOME of that.
I would also suggest that you at least consider using a more modern compiler.

Related

Create file that the application can edit but the user cannot

I'm making a scored game, and want to save the high scores. I want to save the scores in a file that the program can access (of course), but the scores shouldn't be editable by the user (a read-only file, probably). The problem with a read-only file is that, obviously, it's read only, so I can't write the high scores to it. Is there any way to create a file that can be edited by the application but not by the user, or do I have to encrypt the file in some way?
Note: I prefer the C (stdio.h) method of file writing.
Even encryption won't stop editing of the file by something other than your application.
Can I suggest that one option is to simply store the data in binary format? You then save the complication of implementing an encryption, but still prevent any accidental editing of the file.
You could also make your application set the file to be read-only by all, and then make it writeable only while using it. Again, this won't prevent someone else changing those permissions, but it will prevent accidental editing.
There is an established means of accomplishing this on Unix-like systems, but I don't know how you'd do it on other platforms. The idea is to give the high scores files the group ID of a special group just for this purpose, usually simply called games. The games themselves are then setgid games, so that ordinary users can run games, and the games can edit the high scores files, but users cannot directly write to the high scores files.
More details over on Unix & Linux: https://unix.stackexchange.com/a/59059/14308

How to make a user changeable constant?

I want to make a simple console application that will execute some usefull functions that I regularly use for my school (to check if a number is prime, to write factors of a number, solve a quadratic equation etc.).
But as I was making it I decided to add some details about the app to make the user interface prettier: to write the name of the app, version ...
I came to an idea to have an admin password which I can type in and then I can modify those extra details or change the password.
But if I have a password that I store like a const variable or a regular variable const string password = "blablabla;" every time I run the app it will have the same password "blablabla" so is there a way to somehow change the password and other extra data so the program saves the new values permanently?
I thought to save all those extra information in some file and then read them from it every time, but then if the file is changed then the data will be to and I don't want that. I want to change the data only with an admin password. I also thought I can encrypt those information but still thay can be easely changed.
I also thought that the program can open the source code and then modify those initialized values, but then I need to compile that file and I also don't want that.
I only want an .exe app that will run and can change those information permanently with an admin password.
Does anyone now if this can be done and how?
I'm writing this app in C++.
Thank you in advance
is there a way to somehow change the password and other extra data so the program saves the new values permanently?
In theory, you may be able to modify the constants in the data segment of the executable. How to do that is dependent on the executable format. But I would consider that a kludgy workaround and it would be difficult to prevent someone from modifying the executable without the password. What you really want is variables. And you have a good idea for how to initialize the variables:
I thought to save all those extra information in some file
A good idea. Simple solution, probably appropriate for the scope of your app.
if the file is changed then the data will be to and I don't want that. I want to change the data only with an admin password.
Then protect the file somehow. You could, for example not give anyone write permission to the file. Or if you're paranoid (this is just a small console app just for you, right?) encrypt it...
I also thought I can encrypt those information but still thay can be easely changed.
It won't be easy without the key. Sure they can modify the cryptotext, resulting in garbage data, but if you are concerned about that, realize that if they have write access to your files, they can just delete the program itself.
If you want to go this far though, consider storing your data in a full-fledged database which will have authentication and encryption already implemented.
You need to add Windows resources to your application and then update them run-time.
https://msdn.microsoft.com/en-us/library/ms648004%28v=vs.85%29.aspx

Save, Load and Replay game. c++

Basically as part of a team I have had to create a pacman like game for my university course, just zombies instead of ghosts.
We have built all of the game so far and it seems to work really well. Our current problem is that we have to Save a game (with a username and score), Load the game into the position it was once saved, with the correct username and score, and finally be able to offer a replay option where the user can see all the moves that they have previously made (as well as the moves the zombies have made). The zombies will always make the same moves that the user makes as they are designed to chase the user.
My question is what would be the best way to do the save, load and reload options? We cannot use vectors, stacks or queues. We can only really use strings, arrays and other basic variables.
We were thinking to do the reload first by adding everything onto the end of a string and then popping the last value off the string. We could then delay each one by a second and the user will be able to see his/her moves.
As for Saving we were unsure, there are also holes (0 symbols) and pills (* symbols) to take into account. So the position of character, zombies, pills and holes will need to be saved. The character can start from any random position and pretty much everything else is placed after.
The way we do the loading will depend on the way you suggest we do the saving.
Does anyone have any suggestions of the way we should do save, load and replay?
thanks
The simplest way I could think of is saving the user inputs.
This way you could easily replay the game by sending the inputs to the game engine (this may require a lot of restructuring depending on the design of the game engine). To accelerate the loading you could also save the game state at the time of the save (through serialization).
That's the idea, how to do it... you need an ever-expanding array to record the user-input, so let's use a linked-list.
struct Node {
T data;
Node* next_node;
};
//Google for the rest of the code, it is a reeeaaallly
// basic/fundamental data structure.
The data would be the user-inputs and the time they happened.
To save the data, you simply have to iterate through the linked-list and append it to a std::ostream& (to be generic, a std::ofstream& to be specific).
You may add some other useful information (such as the game state and the highscore) before or after the user inputs (or even in another file, which would really make sense for the highscores).
You'll need to read up on some serialization. I wrote some articles on it here, but this is going to be overkill for you guys: http://www.randygaul.net/2013/01/05/c-reflection-part-5-automated-serialization/
You can use some very simple serialization to write out the moves of each zombie into a file. Then when you want to reload this information you deserialize the information in the file. Each move will likely be stored in some form of a linked list so you'll have to come up with a way of recreating such lists upon deserialization.
Your question is really broad so my answer has to be quite broad as well. Really it's up to you to research a solution and implement it.

Code Generator for SDK

I have certain SDK and I want to write a code generator based on the user input. I have designed UI to get the inputs from the user. Is there any known design pattern for such task. Question that confusing me are
Where and how should i store the user inputs.
Should I store them in internal datastructure or some form of xml or json format so that it could be used again.
I am doing this as part of Visual Studio package and have written menu item for the same.
In my opinion this cannot be answered generally. Where to store user input data depends on how much it is (Does it fit into the memory?) and whether you want to use it longer than the program runs (e.g. for logging or loading user input when running again).
Which design pattern(s) to use is rather dependent on what exactly you do with the user input than on the fact that it is user input. For example if you treat your generated code as an object and you will generate more than one of these objects, you could think of implementing a "Builder" design pattern to generate tis code object. If the generated code will have a generic structure which is just slightly altered by the user input, you can look at "Template Methods".

When is it best to sanitize user input?

User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons?
Unfortunately, almost no one of the participants ever clearly understands what are they talking about. Literally. Only Kibbee managed to make it straight.
This topic is all about sanitization. But the truth is, such a thing like wide-termed "general purpose sanitization" everyone is so eager to talk about is just doesn't exist.
There are a zillion different mediums, each require it's own, distinct data formatting. Moreover - even single certain medium require different formatting for it's parts. Say, HTML formatting is useless for javascript embedded in HTML page. Or, string formatting is useless for the numbers in SQL query.
As a matter of fact, such a "sanitization as early as possible", as suggested in most upvoted answers, is just impossible. As one just cannot tell in which certain medium or medium part the data will be used. Say, we are preparing to defend from "sql-injection", escaping everything that moves. But whoops! - some required fields weren't filled and we have to fill out data back into form instead of database... with all the slashes added.
On the other hand, we diligently escaped all the "user input"... but in the sql query we have no quotes around it, as it is a number or identifier. And no "sanitization" ever helped us.
On the third hand - okay, we did our best in sanitizing the terrible, untrustworthy and disdained "user input"... but in some inner process we used this very data without any formatting (as we did our best already!) - and whoops! have got second order injection in all its glory.
So, from the real life usage point of view, the only proper way would be
formatting, not whatever "sanitization"
right before use
according to the certain medium rules
and even following sub-rules required for this medium's different parts.
It depends on what kind of sanitizing you are doing.
For protecting against SQL injection, don't do anything to the data itself. Just use prepared statements, and that way, you don't have to worry about messing with the data that the user entered, and having it negatively affect your logic. You have to sanitize a little bit, to ensure that numbers are numbers, and dates are dates, since everything is a string as it comes from the request, but don't try to do any checking to do things like block keywords or anything.
For protecting against XSS attacks, it would probably be easier to fix the data before it's stored. However, as others mentioned, sometimes it's nice to have a pristine copy of exactly what the user entered, because once you change it, it's lost forever. It's almost too bad there's not a fool proof way to ensure you application only puts out sanitized HTML the way you can ensure you don't get caught by SQL injection by using prepared queries.
I sanitize my user data much like Radu...
First client-side using both regex's and taking control over allowable characters
input into given form fields using javascript or jQuery tied to events, such as
onChange or OnBlur, which removes any disallowed input before it can even be
submitted. Realize however, that this really only has the effect of letting those
users in the know, that the data is going to be checked server-side as well. It's
more a warning than any actual protection.
Second, and I rarely see this done these days anymore, that the first check being
done server-side is to check the location of where the form is being submitted from.
By only allowing form submission from a page that you have designated as a valid
location, you can kill the script BEFORE you have even read in any data. Granted,
that in itself is insufficient, as a good hacker with their own server can 'spoof'
both the domain and the IP address to make it appear to your script that it is coming
from a valid form location.
Next, and I shouldn't even have to say this, but always, and I mean ALWAYS, run
your scripts in taint mode. This forces you to not get lazy, and to be diligent about
step number 4.
Sanitize the user data as soon as possible using well-formed regexes appropriate to
the data that is expected from any given field on the form. Don't take shortcuts like
the infamous 'magic horn of the unicorn' to blow through your taint checks...
or you may as well just turn off taint checking in the first place for all the good
it will do for your security. That's like giving a psychopath a sharp knife, bearing
your throat, and saying 'You really won't hurt me with that will you".
And here is where I differ than most others in this fourth step, as I only sanitize
the user data that I am going to actually USE in a way that may present a security
risk, such as any system calls, assignments to other variables, or any writing to
store data. If I am only using the data input by a user to make a comparison to data
I have stored on the system myself (therefore knowing that data of my own is safe),
then I don't bother to sanitize the user data, as I am never going to us it a way
that presents itself as a security problem. For instance, take a username input as
an example. I use the username input by the user only to check it against a match in
my database, and if true, after that I use the data from the database to perform
all other functions I might call for it in the script, knowing it is safe, and never
use the users data again after that.
Last, is to filter out all the attempted auto-submits by robots these days, with a
'human authentication' system, such as Captcha. This is important enough these days
that I took the time to write my own 'human authentication' schema that uses photos
and an input for the 'human' to enter what they see in the picture. I did this because
I've found that Captcha type systems really annoy users (you can tell by their
squinted-up eyes from trying to decipher the distorted letters... usually over and
over again). This is especially important for scripts that use either SendMail or SMTP
for email, as these are favorites for your hungry spam-bots.
To wrap it up in a nutshell, I'll explain it as I do to my wife... your server is like a popular nightclub, and the more bouncers you have, the less trouble you are likely to have
in the nightclub. I have two bouncers outside the door (client-side validation and human authentication), one bouncer right inside the door (checking for valid form submission location... 'Is that really you on this ID'), and several more bouncers in
close proximity to the door (running taint mode and using good regexes to check the
user data).
I know this is an older post, but I felt it important enough for anyone that may read it after my visit here to realize their is no 'magic bullet' when it comes to security, and it takes all these working in conjuction with one another to make your user-provided data secure. Just using one or two of these methods alone is practically worthless, as their power only exists when they all team together.
Or in summary, as my Mum would often say... 'Better safe than sorry".
UPDATE:
One more thing I am doing these days, is Base64 encoding all my data, and then encrypting the Base64 data that will reside on my SQL Databases. It takes about a third more total bytes to store it this way, but the security benefits outweigh the extra size of the data in my opinion.
I like to sanitize it as early as possible, which means the sanitizing happens when the user tries to enter in invalid data. If there's a TextBox for their age, and they type in anything other that a number, I don't let the keypress for the letter go through.
Then, whatever is reading the data (often a server) I do a sanity check when I read in the data, just to make sure that nothing slips in due to a more determined user (such as hand-editing files, or even modifying packets!)
Edit: Overall, sanitize early and sanitize any time you've lost sight of the data for even a second (e.g. File Save -> File Open)
The most important thing is to always be consistent in when you escape. Accidental double sanitizing is lame and not sanitizing is dangerous.
For SQL, just make sure your database access library supports bind variables which automatically escapes values. Anyone who manually concatenates user input onto SQL strings should know better.
For HTML, I prefer to escape at the last possible moment. If you destroy user input, you can never get it back, and if they make a mistake they can edit and fix later. If you destroy their original input, it's gone forever.
Early is good, definitely before you try to parse it. Anything you're going to output later, or especially pass to other components (i.e., shell, SQL, etc) must be sanitized.
But don't go overboard - for instance, passwords are hashed before you store them (right?). Hash functions can accept arbitrary binary data. And you'll never print out a password (right?). So don't parse passwords - and don't sanitize them.
Also, make sure that you're doing the sanitizing from a trusted process - JavaScript/anything client-side is worse than useless security/integrity-wise. (It might provide a better user experience to fail early, though - just do it both places.)
My opinion is to sanitize user input as soon as posible client side and server side, i'm doing it like this
(client side), allow the user to
enter just specific keys in the field.
(client side), when user goes to the next field using onblur, test the input he entered
against a regexp, and notice the user if something is not good.
(server side), test the input again,
if field should be INTEGER check for that (in PHP you can use is_numeric() ),
if field has a well known format
check it against a regexp, all
others ( like text comments ), just
escape them. If anything is suspicious stop script execution and return a notice to the user that the data he enetered in invalid.
If something realy looks like a posible attack, the script send a mail and a SMS to me, so I can check and maibe prevent it as soon as posible, I just need to check the log where i'm loggin all user inputs, and the steps the script made before accepting the input or rejecting it.
Perl has a taint option which considers all user input "tainted" until it's been checked with a regular expression. Tainted data can be used and passed around, but it taints any data that it comes in contact with until untainted. For instance, if user input is appended to another string, the new string is also tainted. Basically, any expression that contains tainted values will output a tainted result.
Tainted data can be thrown around at will (tainting data as it goes), but as soon as it is used by a command that has effect on the outside world, the perl script fails. So if I use tainted data to create a file, construct a shell command, change working directory, etc, Perl will fail with a security error.
I'm not aware of another language that has something like "taint", but using it has been very eye opening. It's amazing how quickly tainted data gets spread around if you don't untaint it right away. Things that natural and normal for a programmer, like setting a variable based on user data or opening a file, seem dangerous and risky with tainting turned on. So the best strategy for getting things done is to untaint as soon as you get some data from the outside.
And I suspect that's the best way in other languages as well: validate user data right away so that bugs and security holes can't propagate too far. Also, it ought to be easier to audit code for security holes if the potential holes are in one place. And you can never predict which data will be used for what purpose later.
Clean the data before you store it. Generally you shouldn't be preforming ANY SQL actions without first cleaning up input. You don't want to subject yourself to a SQL injection attack.
I sort of follow these basic rules.
Only do modifying SQL actions, such as, INSERT, UPDATE, DELETE through POST. Never GET.
Escape everything.
If you are expecting user input to be something make sure you check that it is that something. For example, you are requesting an number, then make sure it is a number. Use validations.
Use filters. Clean up unwanted characters.
Users are evil!
Well perhaps not always, but my approach is to always sanatize immediately to ensure nothing risky goes anywhere near my backend.
The added benefit is that you can provide feed back to the user if you sanitize at point of input.
Assume all users are malicious.
Sanitize all input as soon as possible.
Full stop.
I sanitize my data right before I do any processing on it. I may need to take the First and Last name fields and concatenate them into a third field that gets inserted to the database. I'm going to sanitize the input before I even do the concatenation so I don't get any kind of processing or insertion errors. The sooner the better. Even using Javascript on the front end (in a web setup) is ideal because that will occur without any data going to the server to begin with.
The scary part is that you might even want to start sanitizing data coming out of your database as well. The recent surge of ASPRox SQL Injection attacks that have been going around are doubly lethal because it will infect all database tables in a given database. If your database is hosted somewhere where there are multiple accounts being hosted in the same database, your data becomes corrupted because of somebody else's mistake, but now you've joined the ranks of hosting malware to your visitors due to no initial fault of your own.
Sure this makes for a whole lot of work up front, but if the data is critical, then it is a worthy investment.
User input should always be treated as malicious before making it down into lower layers of your application. Always handle sanitizing input as soon as possible and should not for any reason be stored in your database before checking for malicious intent.
I find that cleaning it immediately has two advantages. One, you can validate against it and provide feedback to the user. Two, you do not have to worry about consuming the data in other places.