I need to set some cookies using C++, but I can't seem to get them to set, and am quite unfamiliar with CGICC so I don't know where I'm going wrong. Here's my login code (I know it's very insecure, this is homework, nothing that will ever be public facing)
void login(cgicc::Cgicc formdata, std::vector<User> &users)
{
bool success = false;
std::string userName = getValue("username", formdata);
std::string password = getValue("password", formdata);
for(auto iter = users.begin(); iter != users.end(); ++iter)
{
if(iter->getUsername() == userName && iter->getPassword() == password)
{
success = true;
std::string id = std::to_string(iter->getID());
std::cout << "<script> alert(\"Login was successful!\"); </script>" << std::endl;
std::cout << cgicc::HTTPHTMLHeader().setCookie(cgicc::HTTPCookie("username", userName));
std::cout << cgicc::HTTPHTMLHeader().setCookie(cgicc::HTTPCookie("userID", id));
}
}
if(!success)
std::cout << "<script> alert(\"Failed to login. Check your credentials and try again\");</script>"<<std::endl;
}
All the other code has been verified to be working correctly, just the cookie setting code is an issue.
use this as an example:
std::cout << "Content-Type: text/html\n";
std::cout << "Set-Cookie:count=2;\n";
std::cout << "Set-Cookie:user=tizio;\n";
std::cout << "Set-Cookie:password=profdfosfiotjrejiod;\n\n"
these lines must be the first of the html page
Related
I'm trying to delete Windows Defender's scans history and backup history using C++, but I have no clue how I can do it.
I'm using this code:
std::string wdefenderhistory = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History"; //defender history
std::string wdefenderbackupstore = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\BackupStore"; //defender backups
if (std::filesystem::exists(wdefenderhistory)) {
std::filesystem::remove_all(wdefenderhistory);
}
if (std::filesystem::exists(wdefenderbackupstore)) {
std::filesystem::remove_all(wdefenderbackupstore);
}
I tried already with std::fs::remove() and std::remove(), but nothing works.
Any way to force deleting a folder with admin rights without using system() / ShellExecute() syntax?
Started the program as admin, etc etc - nothing works, so I'm asking there.
std::fs::remove_all() is also giving me a memory error:
I'm sure for 99% that error code will be 0x5
I noticed that some folders in directory (only CacheManager and everything under it needs) does not needs the "admin" perms,
so i solved the problem with:
code is deleting every folder w/o admin privilege and keeps C:\..\History path :)
std::string wdefenderhistory = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History"; //defender history
std::string wdefenderbackupstore = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\BackupStore"; //defender backups
if (std::filesystem::exists(wdefenderhistory)) {
const std::filesystem::path defenderhist{ "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History" };
for (auto const& dir_entry : std::filesystem::recursive_directory_iterator{ defenderhist })
{
try {
const std::filesystem::path cachemanager{ "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History\\CacheManager" };
for (auto const& dir_entryy : std::filesystem::recursive_directory_iterator{ cachemanager })
{
if (dir_entry != dir_entryy && dir_entry != cachemanager) {
std::filesystem::remove_all(dir_entry);
}
}
}
catch (std::filesystem::filesystem_error const& ex) {
std::cout
<< "what(): " << ex.what() << '\n'
<< "path1(): " << ex.path1() << '\n'
<< "path2(): " << ex.path2() << '\n'
<< "code().value(): " << ex.code().value() << '\n'
<< "code().message(): " << ex.code().message() << '\n'
<< "code().category(): " << ex.code().category().name() << '\n';
}
}
}
Please mark this thread as solved because i dont know how to do it, thank you
I'm using Microsoft's cpprestsdk to send a JSON from client to server.
The problem is that the data I'm writing in the JSON isn't keeping it's original writing order, and it's being rearranged in alphabetical order.
This is the function that returns the JSON value object:
web::json::value returnJSON()
{
json::value output;
output[L"Outer_list"][L"valX"] = json::value::string(L"value1");
output[L"Outer_list"][L"valY"] = json::value::string(L"value2");
output[L"Outer_list"][L"valA"] = json::value::string(L"value3");
output[L"Outer_list"][L"valZ"] = json::value::string(L"value4");
output[L"Outer_list"][L"valXList"][0] = json::value::string(L"XValue1");
output[L"Outer_list"][L"valXList"][1] = json::value::string(L"XValue2");
output[L"Outer_list"][L"valXList"][2] = json::value::string(L"XValue3");
output[L"Outer_list"][L"valYList"][0] = json::value::string(L"YValue1");
output[L"Outer_list"][L"valYList"][1] = json::value::string(L"YValue2");
output[L"Outer_list"][L"valYList"][2] = json::value::string(L"YValue3");
std::wcout << "output = " << output.serialize() << std::endl << std::endl;
return output;
}
And this is the function that sends the data:
void sendPOST()
{
web::json::value myJson = returnJSON();
http_client client(L"http://127.0.0.1:34568/");
try {
client.request(methods::POST, L"MY_path-query_fragment", myJson).then([](http_response response) {
if (response.status_code() == status_codes::OK) {
auto body = response.extract_string().get();
std::wcout << "The response is = \n" << body << std::endl;
}
else
{
std::cout << "No response" << std::endl;
}
});
}
catch (const std::exception& e)
{
std::cout << "ERROR: " << e.what() << std::endl;
}
}
The data should look like this:
{"Outer_list":{"valX":"value1","valY":"value2","valA":"value3","valZ":"value4","valXList":["XValue1","XValue2","XValue3"],"valYList":["YValue1","YValue2","YValue3"]}}
But on the client/server I see that the data that's being sent/received is:
{"Outer_list":{"valA":"value3","valX":"value1","valXList":["XValue1","XValue2","XValue3"],"valY":"value2","valYList":["YValue1","YValue2","YValue3"],"valZ":"value4"}}
As you can immediately see, the valA is the first one and the valZ is the last, becuase they have been reodered.
How can I turn off this alphabetical reoder, and keep the original writing order?
It turns out you can turn off the sorting! Add this line right after you create 'output':
output[L"Outer_list"] = web::json::value::object(true);
There is a default parameter (bool keep_order = false) that you can override when you create your web::json::value::object. Once this is set, all values added will be kept in the original order.
I was also looking for a way to make the output easier to read by humans and stumbled upon this in the docs.
This My first node.js and n_api. I have been using PHP/APACHI. But I need the c++ library for my web And I decided to using n_api.
The problem is that the value sent by ajax is always 0 in c++.
I don't know what is problem.
ex) I using a vscode.
const testAddon = require('./build/Release/firstaddon.node');
var http = require('http');
var url = require('url');
var fs = require('fs');
const express = require('express');
const app = express();
bodyParser = require('body-parser');
var port = '1080';
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.post('/server', function(req, res){
var responseData = {};
responseData.pID = req.body.pID;
console.log(responseData.pID); <<============= here, value is correct.
const prevInstance = new testAddon.ClassExample(4.3);
var value = prevInstance.getFile(responseData.pID);
console.log(value);
res.json(responseData);
});
If ajax sends 2, console.log(responseData.pID) //2 appears. It is normal.
Below is the classtest.cpp
Napi::Value ClassTest::GetFile(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
using namespace std;
if (info.Length() != 1 || !info[0].IsNumber())
{
Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
}
Napi::Number file_id = info[0].As<Napi::Number>();
int num = this->actualClass_->openFile(file_id); <<== here, file id
return Napi::Number::New(info.Env(), num);
}
And ActualClass.cpp Files showing problems.
int ActualClass::openFile(int id)
{
ifstream fin;
cout << id << endl; <<============================ here, always '0'
filename += to_string(id) += ".txt";
fin.open(filename.c_str(), ios_base::in | ios_base::binary);
if (fin.is_open())
{
while (fin.read((char *)&sdo, sizeof(sdo)))
{
cout << setw(20) << sdo.name << ":"
<< setprecision(0) << setw(12) << sdo.width
<< setprecision(2) << setw(6) << sdo.height
<< setprecision(4) << setw(6) << sdo.size << endl;
slist.push_back(sdo);
}
fin.close();
}
else if (!fin.is_open())
{
cerr << "can't open file " << filename << ".\n";
exit(EXIT_FAILURE);
}
return sdo.size;
}
Only files 1 to 4 are prepared.
But, the argument value entering the function is always 0.
Result is "can't open file 0.txt".
How can I solve it?
Napi::Number file_id = info[0].As<Napi::Number>();
I know here it is converted to an int value that can be handled by C++. Is there anything else I don't know?
Thanks for reading.
You need to cast it to the number with the help of the Napi::Number::Int32Value call. (You can also use Napi::Number::Int64Value for bigger numbers)
Try this.
int file_id = info[0].ToNumber().Int32Value();
Also unrelated to the question, but worth mentioning that when you are doing ThrowAsJavaScriptException() the actual C++ code keeps executing, you better return undefined to avoid nasty bugs.
if (info.Length() != 1 || !info[0].IsNumber())
{
Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
return Env.Undefined();
}
A more clean way will be to enable the CPP exceptions and just throw the error in that place.
if (info.Length() != 1 || !info[0].IsNumber())
{
throw Napi::TypeError::New(env, "Number expected");
}
I am having problems with Windows file path separators using the libssh c++ wrapper libsshpp.
Suppose I have following code:
#define SSH_NO_CPP_EXCEPTIONS
#include "libssh/libsshpp.hpp"
#include <iostream>
#pragma comment(lib, "ssh")
int main()
{
ssh::Session session;
int sessionMsg = -1;
std::string host = "myhost.com";
std::string user = "username";
std::string idfile = "%s\\.ssh\\id_ed25519";
std::string hostkeys = "ssh-ed25519";
std::string keyExchange = "curve25519-sha256";
session.setOption(SSH_OPTIONS_HOST, host.c_str());
session.setOption(SSH_OPTIONS_USER, user.c_str());
session.setOption(SSH_OPTIONS_STRICTHOSTKEYCHECK, (long)0);
session.setOption(SSH_OPTIONS_HOSTKEYS, hostkeys.c_str());
session.setOption(SSH_OPTIONS_KEY_EXCHANGE, keyExchange.c_str());
session.setOption(SSH_OPTIONS_ADD_IDENTITY, idfile.c_str());
std::cout << "Trying to connect to " << host << " with user " << user << "...\n";
session.connect();
if (session.isServerKnown() != SSH_SERVER_KNOWN_OK) {
std::cout << "Server unknown.\n";
if (session.writeKnownhost() != SSH_OK) {
std::cout << "Unable to write to known_hosts file.\n";
}
else {
session.connect();
}
}
sessionMsg = session.userauthPublickeyAuto();
std::string err = session.getError();
if (sessionMsg != SSH_AUTH_SUCCESS) {
if (!err.empty()) {
std::cout << err;
}
std::cout << "Auth failed.";
}
else {
std::cout << err.empty() ? session.getIssueBanner() : err;
}
}
In the beginning I had set the idfile value to just id_ed25519 but then libssh complained: Failed to read private key: C:\Users\MyUser/.ssh/id_ed25519 (notice the switching slashes). After changing it to %s\\.ssh\\id_ed25519 it seemed to have had a positive impact on the connection routine, however now I keep falling into the (session.writeKnownhost() != SSH_OK) code part.
Now, I am wondering if this might be due to the same "switching slashes" problem which came up for the private key file path because apparently libssh wants to access C:\Users\MyUser\.ssh\known_hosts but quite possibly the path is set as something like C:\Users\MyUser/.ssh/known_hosts.
My question is: is there a possibility to change the path seperators to windows-style somehow in the session or is there something else I am overseeing or doing wrong here?
I was able to solve the problem adding the SSH_OPTIONS_SSH_DIR option and changing the private key and known_hosts paths (now relative to the ssh directory path):
// note here: %s will be replaced by libssh with the home directory path
std::string sshDir = "%s//.ssh";
std::string idFile = "id_ed25519";
std::string knownHosts = "known_hosts";
// ...
session.setOption(SSH_OPTIONS_USER, user.c_str());
session.setOption(SSH_OPTIONS_SSH_DIR, sshDir.c_str()); // <-- added
// ...
during CPPRest SDK (2.8) testing, I initialized an HTTP Request simulating user login to the local server, I am expecting a JSON string to be returned indicating if login succeed. here is the code I wrote.
void printJSON(json::value v)
{
if (!v.is_null()){
// Loop over each element in the object
for (auto iter = v.as_object().cbegin(); iter != v.as_object().cend(); ++iter){
const string &key = iter->first;
const json::value &value = iter->second;
if (value.is_object() || value.is_array()){
if(key.size() != 0){
std::wcout << "Parent: " << key.c_str() << std::endl;
}
printJSON(value);
if(key.size() != 0){
std::wcout << "End of Parent: " << key.c_str() << std::endl;
}
}else{
std::wcout << "Key: " << key.c_str() << ", Value: " << value.to_string().c_str() << std::endl;
}
}
}
}
void login(){
http_client client("http://localhost:8080/user");
http_request request(methods::POST);
request.headers().add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.headers().add("Content-Length", "100");
request.headers().add("Host", "testhost.com");
request.headers().add("X-Requested-With", "XMLHttpRequest");
request.set_body("u_id=test_admin&pwd=123456789");
pplx::task<void> task = client.request(request)
.then([](http_response response)-> pplx::task<json::value>{
if(response.status_code() == status_codes::OK){
return response.extract_json();
} else {
return pplx::task_from_result(json::value());
};})
.then([](pplx::task<json::value> previousTask){
try{
const json::value & v = previousTask.get();
printJSON(v);
} catch(const http_exception &e){
std::cout<<e.what()<<std::endl;
}
});
try{
task.wait();
} catch(std::exception &e){
std::cout<<e.what()<<std::endl;
}
}
When I run this code, nothing happened, it seems request never reaches to the Server which has been tested using JSP, So I am pretty sure something went wrong in my code. please help, thanks
Vague.
If you're saying that the request is not reaching the server, there might be a problem with the listener at the time you executed this code.
Your request format is correct and running, you may try to wrap the body (u_id, pwd) into a json, and see if it works.
The bottomline is debugging or sharing your server code would probably help clarify things a bit more.