Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new_change_task #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
new_change_task
susmita2022khatun committed Dec 24, 2023
commit 3b0b5d8914b48da2cde30a74504779c1a44acfa7
Binary file added mini_project/logg_container/container
Binary file not shown.
137 changes: 137 additions & 0 deletions mini_project/logg_container/container.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#include "parser.h"
#include <sched.h>
#include <cstdlib>
#include <sys/mount.h>
#include <fstream>
#include <ctime>
#include "header.h"

using namespace std;

ofstream logFile; // Declare a global file stream for logging

// Function to log messages to a file
void logMessage(const char *message) {
time_t rawtime;
struct tm *timeinfo;

time(&rawtime);
timeinfo = localtime(&rawtime);

char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);

logFile << "[" << buffer << "] " << message << endl;
}

int isOK(int status, const char *msg) {
if (status == -1) {
perror(msg);
logMessage(msg); // Log the error
exit(EXIT_FAILURE);
}
return status;
}
int run(const char* name){
char* args[] = {(char*)name,(char*)0};
return execvp(name,args );
}

void WRITE(const char *path, const char *value) {
int fd = open(path, O_WRONLY | O_APPEND);
if (fd == -1) {
logMessage("Error in opening");
exit(1);
}
ssize_t bytes = write(fd, value, strlen(value));
if (bytes == -1) {
logMessage("Error in writing");
exit(1);
}
close(fd);
}

char *stack_mem() {
const int stacksize = 65 * 1024;
auto *stack = new (nothrow) char[stacksize];
if (stack == nullptr) {
logMessage("Can't allocate memory");
exit(EXIT_FAILURE);
}
return stack + stacksize;
}

void cloneProcess(int (*function)(void *), int flags) {
auto pid = clone(function, stack_mem(), flags, 0);
isOK(pid, "Clone Process Error");
wait(nullptr);
}

void setupENV() {
clearenv();
setenv("TERM", "xterm-256color", 0);
setenv("PATH", "/bin/:/sbin/:/usr/sbin", 0);
}

void setupRoot(const char *folder) {
isOK(chroot(folder), " cant set root:");
isOK(chdir("/"), "chdir: ");
}

void setupjail() {
map<string, string> c = parse("container_config.ini");
const char *root = c["custom_root"].c_str();
const char *cpuManage = c["cpu_manage"].c_str();
const char *memory = c["memory"].c_str();
const char *maxProcess = c["maxProcess"].c_str();
const char *hostname = c["host_name"].c_str();
WRITE(CGROUP_MEM, memory);
WRITE(CGROUP_CPU, cpuManage);

logMessage("Setting up jail environment"); // Log setup information

isOK(sethostname(hostname, strlen(hostname)), "hostname error");
setupENV();
setupRoot("./root");
}

int jail(void *args) {
setupjail();

mount("proc", "/proc", "proc", 0, 0);
pid_t shellPid = fork();
isOK(shellPid, "can't create fork");
if (shellPid == 0) {
logMessage("Executing /bin/bash"); // Log command execution
run("/bin/bash");
exit(0);
}

// wait till all child processes
while (wait(nullptr) > 0);

// zombie check out
// unmount the procfs when all processes are finished
umount("proc");
logMessage("Container execution completed"); // Log container completion
return EXIT_SUCCESS;
}

void makeCgroup() {
WRITE(CGROUP_SUBTREE, "+cpu +memory +pids");
mkdir(REQ_CGROUP, S_IRUSR | S_IWUSR);
const char *pid = to_string(getpid()).c_str();
WRITE(concat(REQ_CGROUP, "/cgroup.procs"), pid);
}

int main() {
logFile.open("container_log.txt", ios::out | ios::app); // Open log file

logMessage(("Parent Pid: " + to_string(getpid())).c_str());

makeCgroup();
cloneProcess(jail, CLONE_NEWPID | CLONE_NEWUTS | SIGCHLD);

logFile.close(); // Close log file
return EXIT_SUCCESS;
}
6 changes: 6 additions & 0 deletions mini_project/logg_container/container_config.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[container]
custom_root = ./root
maxProcess = 7
cpu_manage = 20000 100000
memory = 2G
host_name = container
4 changes: 4 additions & 0 deletions mini_project/logg_container/container_log.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[2023-12-24 01:52:22] Parent Pid: 14597
[2023-12-24 01:52:22] Setting up jail environment
[2023-12-23 20:22:22] Executing /bin/bash
[2023-12-23 20:22:33] Container execution completed
20 changes: 20 additions & 0 deletions mini_project/logg_container/header.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/wait.h>
#include <sched.h>
#include <cstdlib>
#include <sys/mount.h>
#include <sys/types.h>

#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define concat(a,b) (a"" b)
#define CGROUP_MEM "/sys/fs/cgroup/cntr/memory.max"
#define CGROUP_CPU "/sys/fs/cgroup/cntr/cpu.max"
#define CGROUP_SUBTREE "/sys/fs/cgroup/cgroup.subtree_control"
#define REQ_CGROUP "/sys/fs/cgroup/cntr"
3 changes: 3 additions & 0 deletions mini_project/logg_container/intro.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
implementation of logging mechanisms within the container.
the image of output is provided in the folder itself , also the txt form i.e. container_log.txt
is obtained.
3 changes: 3 additions & 0 deletions mini_project/logg_container/makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
container: container.cpp
rm -f container
g++ container.cpp -o container
Binary file added mini_project/logg_container/output.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions mini_project/logg_container/parser.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>

using namespace std;

map<string,string> parse(const string& filename){
map<string,string> config;
ifstream file(filename);
if(!file.is_open()){
cerr<<"Error in opening of config file"<<endl;
return {};
}
string line,section;
while(getline(file,line)){
if(line.find('[')!=string::npos && line.find(']')!=string::npos){
section = line.substr(line.find('[')+1,line.find(']')-line.find('['));
continue;
}
stringstream ss(line);
string key,value;
getline(ss,key,'=');
getline(ss,value);
config[key]=value;
}

file.close();
return config;


}
Binary file added mini_project/network_container/container_network
Binary file not shown.
80 changes: 80 additions & 0 deletions mini_project/network_container/container_network.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

void setupNetworkNamespace() {
// Create a new network namespace
int netns = unshare(CLONE_NEWNET);
if (netns == -1) {
perror("unshare(CLONE_NEWNET)");
exit(EXIT_FAILURE);
}

// Create a veth pair (virtual Ethernet devices)
const char* veth1 = "veth1";
const char* veth2 = "veth2";

if (system(("ip link add " + string(veth1) + " type veth peer name " + string(veth2)).c_str()) == -1) {
perror("ip link add");
exit(EXIT_FAILURE);
}

// Move veth2 to the network namespace
if (system(("ip link set " + string(veth2) + " netns $pid").c_str()) == -1) {
perror("ip link set");
exit(EXIT_FAILURE);
}

// Configure IP addresses for veth1 in the original namespace
if (system(("ip addr add 192.168.1.1/24 dev " + string(veth1)).c_str()) == -1) {
perror("ip addr add");
exit(EXIT_FAILURE);
}

// Bring up veth1
if (system(("ip link set " + string(veth1) + " up").c_str()) == -1) {
perror("ip link set up");
exit(EXIT_FAILURE);
}

// Set up NAT for internet access in the network namespace
if (system("iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE") == -1) {
perror("iptables");
exit(EXIT_FAILURE);
}

cout << "Container network namespace set up successfully." << endl;
}

int main() {
pid_t pid = fork();

if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}

if (pid == 0) {
// Child process (container)
setupNetworkNamespace();
execlp("/bin/bash", "/bin/bash", NULL);

// If execlp fails
perror("execlp");
exit(EXIT_FAILURE);
} else {
// Parent process
waitpid(pid, NULL, 0);
cout << "Parent process exiting." << endl;
}

return EXIT_SUCCESS;
}
4 changes: 4 additions & 0 deletions mini_project/network_container/intro.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Container Networking:

Explore container networking options, such as setting up a bridge network or connecting the container to an existing network. This allows containers to communicate with each other or with the host.
the image of the output is provided in folder.
Binary file added mini_project/network_container/output1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mini_project/network_container/output2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.