Add edge files.

This commit is contained in:
2024-11-22 19:34:59 +01:00
parent ef080a96b2
commit 7d42a35f7a
5 changed files with 98 additions and 28 deletions

View File

@@ -1,6 +1,6 @@
""" """
Install script for the Python jailer. Install script for the Python jailer.
Version: 1.0.0-main1 Version: 0.2.0-alpha2
""" """
import os import os
import shutil import shutil
@@ -63,7 +63,7 @@ if setup_posix.lower() == "y":
f.write(usrname) f.write(usrname)
f.close() f.close()
with open("./sys/procinfo", "a+") as f: with open("./sys/procinfo", "a+") as f:
f.write("proc: vfs(/proc/)\nmgr: vfs(/proc/kcore)") f.write("proc: vfs(/proc/)\nkernel: vfs(/proc/kcore)")
f.close() f.close()
with open("./proc/kcore", "a+") as f: with open("./proc/kcore", "a+") as f:
f.write("/sys/jail_mgr.py") f.write("/sys/jail_mgr.py")
@@ -75,6 +75,7 @@ else:
os.mkdir("./usr") os.mkdir("./usr")
os.mkdir("./proc") os.mkdir("./proc")
os.mkdir(f"./home/{usrname}") os.mkdir(f"./home/{usrname}")
os.mkdir("./sys/krnl/")
print("Copying files...") print("Copying files...")
shutil.move("./main.py", "./sys/jail_mgr.py") shutil.move("./main.py", "./sys/jail_mgr.py")
shutil.move("./sh.py", "./bin/shell.py") shutil.move("./sh.py", "./bin/shell.py")

View File

@@ -1 +1 @@
0.2.0-main1 0.1.1-main1

77
main.py
View File

@@ -1,6 +1,6 @@
""" """
This is the PyJail, a jailing tool for running Python apps in a sandboxed environment. This is the PyJail, a jailing tool for running Python apps in a sandboxed environment.
Version: 0.2.0-main1 Version: edge0003-base0.2.1
""" """
import os import os
import time import time
@@ -9,7 +9,7 @@ import runpy
class PyJail: class PyJail:
""" """
The The jail manager, handles all system calls and such.
""" """
def __init__(self, debug=False): def __init__(self, debug=False):
self.rootpath = "" self.rootpath = ""
@@ -30,8 +30,6 @@ class PyJail:
Runs a specified program. Runs a specified program.
""" """
path_to_bin = self.fs(path_to_bin) path_to_bin = self.fs(path_to_bin)
# print(path_to_bin)
# print(str(self.rootpath) + str(path_to_bin))
if path_to_bin == 3 or path_to_bin == 2: if path_to_bin == 3 or path_to_bin == 2:
self.msg("jailmgr.run_program()", "An error has occurred launching the program.", True, self.msg("jailmgr.run_program()", "An error has occurred launching the program.", True,
"WARNING") "WARNING")
@@ -41,7 +39,7 @@ class PyJail:
self._program_counter += 1 self._program_counter += 1
runpy.run_path(path_to_bin) runpy.run_path(path_to_bin)
def msg(self, caller: str, message:str, emit: bool = False, log_level: str = "INFO"): def msg(self, caller: str, message: str, emit: bool = False, log_level: str = "INFO"):
""" """
The custom message parser, can parse messages and alert apps of said messages. The custom message parser, can parse messages and alert apps of said messages.
Replaces print statements. Replaces print statements.
@@ -56,10 +54,12 @@ class PyJail:
accepted_log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] accepted_log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
if log_level.upper() not in accepted_log_levels: if log_level.upper() not in accepted_log_levels:
self.msg(f"jailmgr.msg()",f"Not accepted loglevel!! {log_level}", False, "ERROR") self.msg(f"jailmgr.msg()",f"Not accepted loglevel!! {log_level}", False, "ERROR")
return 1
msg = f"[{time.time}] [{caller}] [{log_level}] {message}"
with open(self.fs("/proc/klog"), "a+") as f: with open(self.fs("/proc/klog"), "a+") as f:
f.write(f"[{time.time}] [{caller}] [{log_level}] {message}") f.write(msg)
if emit is True: if emit is True:
print(message) print(msg)
return 0 return 0
def fs(self, check_path=None, resolve_symlinks=True): def fs(self, check_path=None, resolve_symlinks=True):
@@ -101,7 +101,6 @@ class PyJail:
# This is a symlink! # This is a symlink!
# Symlinks always contain the full literal path that they need to access, so we can # Symlinks always contain the full literal path that they need to access, so we can
# take that and do the same trick to split it and add the next things to it. # take that and do the same trick to split it and add the next things to it.
# raise NotImplementedError()
is_symlink_split = is_symlink.split(" ", 1) is_symlink_split = is_symlink.split(" ", 1)
symlink_dest = is_symlink_split[1] symlink_dest = is_symlink_split[1]
symlink_dest = f"{symlink_dest}/{path}" symlink_dest = f"{symlink_dest}/{path}"
@@ -132,9 +131,63 @@ class PyJail:
self.msg("jailmgr.fs()", message=rootpath, log_level="INFO") self.msg("jailmgr.fs()", message=rootpath, log_level="INFO")
return rootpath return rootpath
@staticmethod def kver(self):
def kver():
""" """
Returns the jail manager version Returns the kernel version
""" """
return "0.2.0-main1" return "edge0003-base0.2.1"
def netsock(self, ip, port, mode, msg):
"""
An easy interface to network sockets, built right into the jailmanager
Args:
ip: The IP of the server to access.
port: The port to access the server on
mode: Either UDP, TCP or PKG (HTTP)
msg: The message to send the server
Returns:
Whatever the server returns.
"""
if mode == "PKG":
import requests
else:
import socket
if mode == "TCP":
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
self.msg("jailmgr.netsock()", "Socket import failed!", False, "CRITICAL")
self.msg("jailmgr.netsock()", "An unexpected error occurred!", True, "ERROR")
return None
# Connect to the server
client_socket.connect((ip, port))
self.msg("jailmgr.netsock()", f"Connected to server at {server_ip}:{server_port}", False, "INFO")
# Send the message to the server
client_socket.send(message.encode())
# Receive the response from the server
response = client_socket.recv(1024).decode()
client_socket.close() # Close the connection
self.msg("jailmgr.netsock", f"Received from server: {response}", False "INFO")
return response
elif mode == "PKG":
# raise NotImplementedError("TODO: PKG will be implemented later!")
file_io = requests.get(ip)
if file_io.startswith("PYPAK PMD"):
with open(self.fs(f"/usr/netsock/cache/{pkg}.pmd"), "a+") as f:
f.write(file_io)
f.close()
else:
raise NotImplementedError("TODO: UDP will be implemented later!")
# raise NotImplementedError("TODO: Netsock will be implemented once 0.3.0 comes around!")

40
sh.py
View File

@@ -1,44 +1,60 @@
""" """
The shell for PyNVOS The shell for PyNVOS
Version: 0.1.0-main1 Version: 0.2.0.0400
""" """
import importlib import importlib
import os import os
import cmd import cmd
import shutil
# from ..sys.krnl import Kernel # from ..sys.krnl import Kernel
print(__name__) print(__name__)
class shell(cmd.Cmd): class shell(cmd.Cmd):
intro = "Shell started, PyNVOS 0.1.1-main1" jail_mgr = importlib.import_module(".jail_mgr", "vfs.sys")
prompt = "shell-0.1.0$ " jailmgr = jail_mgr.PyJail()
kver = jailmgr.kver()
intro = f"Shell started, PyNVOS {kver}"
prompt = "shell-0.2$ "
file = None file = None
krnl = importlib.import_module(".jail_mgr", "vfs.sys")
kernel = krnl.Kernel()
print(str(kernel) + " " + str(type(kernel)))
def do_cd(self, args): def do_cd(self, args):
"""Changes directory""" """Changes directory"""
args = shell.kernel.fs(args) args = shell.jailmgr.fs(args)
os.chdir(args) os.chdir(args)
def do_exec(self, args): def do_exec(self, args):
"""Allows you to execute a file""" """Allows you to execute a file"""
# Apps in /bin should be allowed to launch without first adding /bin/ or ./, just the name of the executable # Apps in /bin should be allowed to launch without first adding /bin/ or ./, just the name of the executable
# So for ledit it should be just 'ledit' and not /bin/ledit.py or ./ledit.py # So for ledit it should be just 'ledit' and not /bin/ledit.py or ./ledit.py
bins_in_bin = os.listdir(shell.kernel.fs("/bin")) bins_in_bin = os.listdir(self.jailmgr.fs("/bin"))
apps_strip = [] apps_strip = []
for apps in bins_in_bin: for apps in bins_in_bin:
if apps.endswith(".py"): if apps.endswith(".py"):
apps_strip.append(apps.strip(".py")) apps_strip.append(apps.strip(".py"))
if args in apps_strip: if args in apps_strip:
shell.kernel.run_program(f"/bin/{args}.py") shell.jailmgr.run_program(f"/bin/{args}.py")
else: else:
shell.kernel.run_program(args) shell.jailmgr.run_program(args)
def do_ls(self, none): def do_ls(self, none):
"""Lists the content of a directory""" """Lists the content of a directory"""
os.listdir(os.getcwd()) os.listdir(os.getcwd())
def do_pkg(self, pkg):
"""Downloads packages over the internet."""
self.jailmgr.netsock(f"https://pkg.novacow.ch/repo/{kver}/meta/{pkg}.pmd", None, "PKG", f"{pkg}")
shutil.copy(self.jailmgr.fs(f"/usr/netsock/cache/{pkg}.pmd"), self.jailmgr.fs(f"/usr/pkg/metacache/"))
with open(self.jailmgr.fs(f"/usr/pkgs/metacache/{pkg}.pmd"), "r") as f:
package_meta = f.read()
f.close()
print(package_meta)
y_n_confirmation = input("Do you want to install this package? [y/N] ")
if y_n_confirmation.lower() != "y":
print("Aborted.")
return
self.jailmgr.netsock(f"https://pkg.novacow.ch/repo/{kver}/main/static/binary/{pkg}.py", None, "PKG", f"{pkg}")
shutil.copy(self.jailmgr.fs(f"/usr/netsock/cache/{pkg}.py"), self.jailmgr.fs(f"/usr/bin/"))
def postloop(self): def postloop(self):
pass pass
@@ -46,6 +62,6 @@ class shell(cmd.Cmd):
if __name__ == '<run_path>': if __name__ == '<run_path>':
shell().cmdloop() shell().cmdloop()
if __name__ == '__main__': if __name__ == '__main__':
print("The shell can't be ran as a standalone program and must be ran in conjunction with the kernel.") print("The shell can't be ran as a standalone program and must be ran in conjunction with the jail manager.")
input("Press Enter to continue...") input("Press Enter to continue...")
exit(-1) exit(-1)

View File

@@ -1 +1 @@
0.2 build 0036 0.1.0