From d2394cd1bd5ece2dbac98c33701bd89345f7afba Mon Sep 17 00:00:00 2001
From: edgd1er <edgd1er@hotmail.com>
Date: Fri, 22 Oct 2021 23:39:31 +0200
Subject: [PATCH] start as root, change uid/gid, drop priv, run server/client

---
 docker/docker-py3-kms/Dockerfile |  4 +--
 docker/entrypoint.py             | 58 +++++++-------------------------
 docker/start.py                  | 12 +++----
 3 files changed, 19 insertions(+), 55 deletions(-)

diff --git a/docker/docker-py3-kms/Dockerfile b/docker/docker-py3-kms/Dockerfile
index 5bfb7d5..629d5b0 100644
--- a/docker/docker-py3-kms/Dockerfile
+++ b/docker/docker-py3-kms/Dockerfile
@@ -32,8 +32,6 @@ RUN apk add --no-cache --update \
     build-base python3-dev \
     ca-certificates \
     duplicity \
-    su-exec \
-    sudo \
     tzdata \
     shadow \
     && git clone --branch master --depth 1 https://github.com/coleifer/sqlite-web.git /tmp/sqlite_web \
@@ -56,7 +54,7 @@ RUN chmod 755 /usr/bin/entrypoint.py
 
 WORKDIR /home/py-kms
 #USER py-kms
-EXPOSE ${PORT}/tcp
+EXPOSE 1688/tcp
 EXPOSE 8080
 
 ENTRYPOINT [ "/usr/bin/python3", "/usr/bin/entrypoint.py" ]
diff --git a/docker/entrypoint.py b/docker/entrypoint.py
index d886c92..3250225 100755
--- a/docker/entrypoint.py
+++ b/docker/entrypoint.py
@@ -7,18 +7,10 @@ import os
 import pwd
 import subprocess
 
-argumentVariableMapping = {
-    '-l': 'LCID',
-    '-c': 'CLIENT_COUNT',
-    '-a': 'ACTIVATION_INTERVAL',
-    '-r': 'RENEWAL_INTERVAL',
-    '-w': 'HWID',
-    '-V': 'LOGLEVEL',
-    '-F': 'LOGFILE',
-    '-S': 'LOGSIZE',
-    '-e': 'EPID'
-}
-sqliteWebPath = '/home/sqlite_web/sqlite_web.py'
+PYTHON3 = '/usr/bin/python3'
+dbPath = os.path.join(os.sep, 'home', 'py-kms', 'db', 'pykms_database.db')
+log_level = os.getenv('LOGLEVEL', 'INFO')
+
 
 def change_uid_grp():
   user_db_entries = pwd.getpwnam("py-kms")
@@ -27,54 +19,28 @@ def change_uid_grp():
   gid = user_grp_db_entries.gr_gid
   new_gid = int(os.getenv('GID', str(gid)))
   new_uid = int(os.getenv('UID', str(uid)))
-  os.chown("/home/py-kms", new_uid, new_uid)
-  os.chown("/db/pykms_database.db", new_uid, new_uid)
+  os.chown("/home/py-kms", new_uid, new_gid)
+  os.chown("/usr/bin/start.py", new_uid, new_gid)
+  if os.path.isfile(dbPath): os.chown(dbPath, new_uid, new_gid)
+  os.system("ls -al /usr/bin/start.py")
   if gid != new_gid:
     print("Setting gid to " + str(new_gid), flush=True)
     os.setgid(gid)
   if uid != new_uid:
     print("Setting uid to " + str(new_uid), flush=True)
     os.setuid(uid)
-# Build the command to execute
-listenIP = os.environ.get('IP', '0.0.0.0')
-listenPort = os.environ.get('PORT', '1688')
-command = ['/usr/bin/python3', 'pykms_Server.py', listenIP, listenPort]
-for (arg, env) in argumentVariableMapping.items():
-    if env in os.environ and os.environ.get(env) != '':
-        command.append(arg)
-        command.append(os.environ.get(env))
-        
-enableSQLITE = os.path.isfile(sqliteWebPath) and os.environ.get('SQLITE', 'false').lower() == 'true'
-if enableSQLITE:
-    dbPath = os.path.join('db', 'pykms_database.db')
-    print('Storing database file to ' + dbPath)
-    os.makedirs('db', exist_ok=True)
-    command.append('-s')
-    command.append(dbPath)
 
 
 def change_tz():
   tz = os.getenv('TZ', 'etc/UTC')
   # TZ is not symlinked and defined TZ exists
-  if tz not in os.readlink(LTIME) and os.path.isfile('/usr/share/zoneinfo/' + tz):
+  if tz not in os.readlink('/etc/localtime') and os.path.isfile('/usr/share/zoneinfo/' + tz):
     print("Setting timezone to " + tz, flush=True)
-    os.remove(LTIME)
-    os.symlink(os.path.join('/usr/share/zoneinfo/', tz), LTIME)
-# In case SQLITE is defined: Start the web interface
-if enableSQLITE:
-    time.sleep(5) # The server may take a while to start
-    if not os.path.isfile(dbPath):
-        # Start a dummy activation to ensure the database file is created
-        subprocess.run(['/usr/bin/python3', 'pykms_Client.py', listenIP, listenPort, '-m', 'Windows10', '-n', 'DummyClient', '-c', 'ae3a27d1-b73a-4734-9878-70c949815218'])
-    sqliteProcess = subprocess.Popen(['/usr/bin/python3', sqliteWebPath, '-H', listenIP, '--read-only', '-x', dbPath, '-p', os.environ.get('SQLITE_PORT', 8080)])
+    os.remove('/etc/localtime')
+    os.symlink(os.path.join('/usr/share/zoneinfo/', tz), '/etc/localtime')
 
 
-LTIME = '/etc/localtime'
-PYTHON3 = '/usr/bin/python3'
-log_level = os.getenv('LOGLEVEL', 'INFO')
-
 # Main
 if (__name__ == "__main__"):
   change_tz()
-  change_uid_grp()
-  subprocess.call("/usr/bin/start.py",shell=True)
+  subprocess.call(PYTHON3 + " /usr/bin/start.py", preexec_fn=change_uid_grp(), shell=True)
diff --git a/docker/start.py b/docker/start.py
index 7bb3309..8de8d57 100644
--- a/docker/start.py
+++ b/docker/start.py
@@ -1,7 +1,6 @@
 #!/usr/bin/python3
 
 # This replaces the old start.sh and ensures all arguments are bound correctly from the environment variables...
-
 import os
 import subprocess
 import time
@@ -19,13 +18,14 @@ argumentVariableMapping = {
   '-S': 'LOGSIZE',
   '-e': 'EPID'
 }
-enableSQLITE = os.getenv('SQLITE', 'false').lower() == 'true'
-dbPath = os.path.join('/db/pykms_database.db')
+
+sqliteWebPath = '/home/sqlite_web/sqlite_web.py'
+enableSQLITE = os.path.isfile(sqliteWebPath) and os.environ.get('SQLITE', 'false').lower() == 'true'
+dbPath = os.path.join(os.sep, 'home', 'py-kms', 'db', 'pykms_database.db')
 log_level = os.getenv('LOGLEVEL', 'INFO')
 
 
 def start_kms_client():
-  time.sleep(5)  # The server may take a while to start
   if not os.path.isfile(dbPath):
     # Start a dummy activation to ensure the database file is created
     client_cmd = [PYTHON3, 'pykms_Client.py', os.environ.get('IP', "0.0.0.0"), os.environ.get('PORT', 1688),
@@ -51,8 +51,6 @@ def start_kms():
       command.append(arg)
       command.append(os.environ.get(env))
 
-  os.makedirs(os.path.dirname(dbPath), exist_ok=True)
-
   if enableSQLITE:
     print('Storing database file to ' + dbPath, flush=True)
     command.append('-s')
@@ -65,6 +63,8 @@ def start_kms():
 
   # In case SQLITE is defined: Start the web interface
   if enableSQLITE:
+    time.sleep(5)  # The server may take a while to start
+    os.system('ls -al ' + dbPath)
     start_kms_client()
     sqlite_cmd = [PYTHON3, '/home/sqlite_web/sqlite_web.py', '-H', os.environ.get('IP'), '--read-only', '-x', dbPath,
                   '-p', os.environ.get('SQLITE_PORT')]