Compare commits

...

4 Commits

Author SHA1 Message Date
67a2395db3
fix: code quality 2021-03-01 10:33:42 +01:00
ce70c7144c
sec: disallow global IPs from proxying 2021-03-01 10:33:19 +01:00
534b33fa52
fix: parse more than the first line of metadata 2021-03-01 10:32:07 +01:00
2913a8aa24
add: redirect and vendor-data
- add redirect and vendor-data (empty only, to speed up boot)
- some CQ too
- default file names standardized
2021-03-01 10:00:50 +01:00

115
main.py
View File

@ -1,39 +1,78 @@
import os
import sys
import cherrypy
from cherrypy.lib.static import serve_file
import yaml
import socket
#!/usr/bin/env python3
"""
Serve cloud init files
"""
import configparser
import os
import socket
import sys
from ipaddress import AddressValueError, IPv4Address, IPv6Address
import yaml
import cherrypy
from cherrypy.lib.static import serve_file
PATH = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
config.read(os.path.join(PATH, "config.ini"))
CONFIG = configparser.ConfigParser()
CONFIG.read(os.path.join(PATH, "config.ini"))
user_data_filename = config["app"].get("user_data", "sample_file.txt")
meta_data_filename = config["app"].get("meta_data", "meta_data_extra.txt")
USER_DATA_FILENAME = CONFIG["app"].get("user_data", "user-data")
META_DATA_FILENAME = CONFIG["app"].get("meta_data", "meta-data")
REDIRECT_FILENAME = CONFIG["app"].get("redirect", "redirect")
class MainApp:
class CloudInitApp:
"""
Serve cloud init files
"""
def __init__(self):
self.remoteip = None
self.hostinfo = ('localhost', )
def _can_ip_be_proxy(self):
self.remoteip = cherrypy.request.remote.ip
try:
ipobj = IPv4Address(self.remoteip)
except AddressValueError:
try:
ipobj = IPv6Address(self.remoteip)
except AddressValueError:
return False
return not ipobj.is_global
def _init_ip(self):
"""
Get remote IP
"""
if self._can_ip_be_proxy():
try:
self.remoteip = cherrypy.request.headers.get(
'X-Real-Ip',
cherrypy.request.remote.ip
)
except:
self.remoteip = cherrypy.request.remote.ip
except KeyError:
pass
try:
self.hostinfo = socket.gethostbyaddr(self.remoteip)
except socket.herror:
self.hostinfo = ('localhost', )
pass
def _redirect_if_needed(self):
filepath = os.path.join(PATH, "data", self.hostinfo[0],
REDIRECT_FILENAME)
if os.path.exists(filepath):
try:
with open(filepath) as redirect:
content = redirect.read().splitlines()
raise cherrypy.HTTPRedirect(content[0], 301)
except IOError:
return False
return False
@cherrypy.expose
def user_data(self):
@ -41,11 +80,12 @@ class MainApp:
Serves a static file
"""
self._init_ip()
self._redirect_if_needed()
filepath = os.path.join(PATH, "data", self.hostinfo[0],
user_data_filename)
USER_DATA_FILENAME)
if not os.path.exists(filepath):
filepath = os.path.join(PATH, "data", user_data_filename)
return serve_file(filepath, "application/x-download", "attachment")
filepath = os.path.join(PATH, "data", USER_DATA_FILENAME)
return serve_file(filepath, "text/yaml", "attachment")
@cherrypy.expose
def meta_data(self):
@ -53,18 +93,33 @@ class MainApp:
Return meta-data in YAML
"""
self._init_ip()
self._redirect_if_needed()
hostname = self.hostinfo[0]
data = {"instance-id": hostname.split(".")[0], "local-hostname": hostname}
data = {
"instance-id": hostname.split(".")[0],
"local-hostname": hostname
}
filepath = os.path.join(PATH, "data", hostname, meta_data_filename)
filepath = os.path.join(PATH, "data", hostname, META_DATA_FILENAME)
if os.path.exists(filepath):
with open(filepath, "r") as f:
line = f.readlines()[0]
ls = list(map(lambda k: k.strip(), line.split(":")))
data[ls[0]] = ls[1]
with open(filepath, "r") as metadata:
for line in metadata.readlines():
linesplit = list(map(lambda k: k.strip(), line.split(":")))
data[linesplit[0]] = linesplit[1]
cherrypy.response.headers['Content-Type'] = \
'text/yaml'
cherrypy.response.headers['Content-Disposition'] = \
'attachment; filename="user-data"'
return yaml.dump(data)
@cherrypy.expose
def vendor_data(self):
"""
Return empty vendor-data
"""
return ""
@cherrypy.expose
def finished(self, data):
"""
@ -77,15 +132,17 @@ class MainApp:
if not os.path.exists(folder):
os.makedirs(folder)
with open(os.path.join(folder, meta_data_filename), "w") as f:
f.write(data)
with open(os.path.join(folder, META_DATA_FILENAME), "w") as fin:
fin.write(data)
ROOT = MainApp()
ROOT = CloudInitApp()
if __name__ == "__main__":
cherrypy.server.socket_host = config["server"].get("server_host", "127.0.0.1")
cherrypy.server.socket_port = config["server"].getint("server_port", 8081)
cherrypy.server.socket_host = \
CONFIG["server"].get("server_host", "127.0.0.1")
cherrypy.server.socket_port = \
CONFIG["server"].getint("server_port", 8081)
ENGINE = cherrypy.engine
cherrypy.tree.mount(ROOT)