├── run.py ├── requirements.txt ├── init ├── elivepatch.confd └── elivepatch.init ├── .travis.yml ├── src └── elivepatch_server │ ├── resources │ ├── __init__.py │ ├── AgentInfo.py │ ├── dispatcher.py │ └── livepatch.py │ └── __init__.py ├── tests ├── conftest.py └── test_app.py ├── setup.py ├── docs └── API.md ├── .gitignore ├── README.md └── LICENSE /run.py: -------------------------------------------------------------------------------- 1 | from src.elivepatch_server import run 2 | 3 | run() 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask_restful 3 | flask_testing 4 | pytest 5 | -------------------------------------------------------------------------------- /init/elivepatch.confd: -------------------------------------------------------------------------------- 1 | # /etc/conf.d/elivepatch 2 | DAEMON_USER=root 3 | DAEMON_GROUP=root -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.7" 4 | matrix: 5 | include: 6 | - python: 3.7 7 | dist: xenial 8 | sudo: true 9 | # command to install dependencies 10 | install: 11 | - pip install -r requirements.txt 12 | - python setup.py install 13 | # command to run tests 14 | script: 15 | - pytest 16 | -------------------------------------------------------------------------------- /src/elivepatch_server/resources/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # (c) 2017, Alice Ferrazzi 5 | # Distributed under the terms of the GNU General Public License v2 or later 6 | 7 | __version__ = "0.1" 8 | __author__ = "Alice Ferrazzi" 9 | __license__ = "GNU GPLv2+" 10 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os.path 3 | 4 | sys.path.append( 5 | os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) 6 | ) 7 | 8 | from elivepatch_server import app 9 | import pytest 10 | from flask_restful import Api as api 11 | from flask_testing import TestCase 12 | 13 | 14 | @pytest.fixture 15 | def app(): 16 | return app 17 | -------------------------------------------------------------------------------- /tests/test_app.py: -------------------------------------------------------------------------------- 1 | from elivepatch_server import app as flask_app 2 | import pytest 3 | from flask_restful import Api as api 4 | from conftest import app 5 | import unittest 6 | 7 | 8 | class TestIntegrations(unittest.TestCase): 9 | def setUp(self): 10 | self.app = flask_app.test_client() 11 | 12 | def test_not_found(self): 13 | response = self.app.get("/") 14 | assert response.status_code == 404 15 | 16 | def test_found(self): 17 | response = self.app.get("/elivepatch/api/") 18 | assert response.status_code == 200 19 | -------------------------------------------------------------------------------- /init/elivepatch.init: -------------------------------------------------------------------------------- 1 | #!/sbin/openrc-run 2 | 3 | depend() { 4 | need net 5 | } 6 | 7 | DAEMON=/usr/bin/elivepatch_server 8 | DAEMON_NAME=elivepatch_server 9 | PIDFILE=/var/run/${DAEMON_NAME}.pid 10 | 11 | start_pre() { 12 | checkpath -d -o ${DAEMON_USER}:${DAEMON_GROUP} /var/log/${DAEMON_NAME} 13 | } 14 | 15 | start () { 16 | ebegin "Starting system ${DAEMON_NAME} daemon" 17 | start-stop-daemon --start --background --pidfile ${PIDFILE} \ 18 | --user ${DAEMON_USER}:${DAEMON_GROUP} \ 19 | --make-pidfile \ 20 | --stdout /var/log/${DAEMON_NAME}/${DAEMON_NAME}.log \ 21 | --stderr /var/log/${DAEMON_NAME}/${DAEMON_NAME}.err \ 22 | --exec ${DAEMON} runserver 23 | eend $? "Failed to start ${DAEMON_NAME}" 24 | } 25 | 26 | stop () { 27 | ebegin "Stopping system ${DAEMON_NAME} daemon" 28 | start-stop-daemon --stop --pidfile ${PIDFILE} --user ${DAEMON_USER}:${DAEMON_GROUP} --retry 10 29 | eend $? "Failed to stop ${DAEMON_NAME}" 30 | } 31 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="elivepatch_server", 5 | version="0.1", 6 | description="Distributed elivepatch server API", 7 | url="https://wiki.gentoo.org/wiki/Elivepatch, " 8 | + "https://github.com/aliceinwire/elivepatch-server", 9 | classifiers=[ 10 | "Development Status :: 4 - Beta", 11 | "Environment :: Web Environment", 12 | "Framework :: Flask", 13 | "Intended Audience :: Developers", 14 | "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", 15 | "Operating System :: OS Independent", 16 | "Programming Language :: Python", 17 | "Programming Language :: Python :: 2.6", 18 | "Programming Language :: Python :: 2.7", 19 | "Programming Language :: Python :: 3", 20 | "Programming Language :: Python :: 3.3", 21 | "Programming Language :: Python :: 3.4", 22 | "Programming Language :: Python :: 3.5", 23 | "Topic :: System :: Operating System Kernels", 24 | ], 25 | author="Alice Ferrazzi", 26 | author_email="alice.ferrazzi@gmail.com", 27 | license="GNU GPLv2+", 28 | packages=find_packages("src"), 29 | package_dir={"": "src"}, 30 | install_requires=["flask>=1", "flask_restful"], 31 | entry_points={ 32 | "console_scripts": ["elivepatch-server=elivepatch_server:run"] 33 | }, 34 | ) 35 | -------------------------------------------------------------------------------- /src/elivepatch_server/resources/AgentInfo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # (c) 2017, Alice Ferrazzi 5 | # Distributed under the terms of the GNU General Public License v2 or later 6 | 7 | from flask_restful import Resource, reqparse, fields, marshal 8 | 9 | agent_fields = {"module": fields.String, "version": fields.String} 10 | 11 | 12 | def agentinfo(module=None): 13 | """ 14 | :rtype: object 15 | """ 16 | agents = [] 17 | agent = {"id": 1, "module": "elivepatch", "version": "0.01"} 18 | agents.append(agent) 19 | return agents 20 | 21 | 22 | agents = agentinfo() 23 | 24 | 25 | class AgentAPI(Resource): 26 | def __init__(self): 27 | self.reqparse = reqparse.RequestParser() 28 | self.reqparse.add_argument( 29 | "module", 30 | type=str, 31 | required=True, 32 | help="No task title provided", 33 | location="json", 34 | ) 35 | self.reqparse.add_argument( 36 | "version", 37 | type=str, 38 | required=True, 39 | help="No task title provided", 40 | location="json", 41 | ) 42 | super(AgentAPI, self).__init__() 43 | 44 | def get(self): 45 | return {"agent": [marshal(host, agent_fields) for host in agents]} 46 | 47 | def post(self): 48 | args = self.reqparse.parse_args() 49 | host = { 50 | "id": agents[-1]["id"] + 1, 51 | "module": args["module"], 52 | "version": args["version"], 53 | } 54 | agents.append(host) 55 | return {"agent": marshal(host, agent_fields)}, 201 56 | -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | ### send_livepatch _POST_ 2 | Get the livepatch object by sending the UUID 3 | #### url: /elivepatch/api/v1.0/send_livepatch 4 | - KernelVersion type=string required=False 5 | - UUID type=string required=False 6 | 7 | ### GetFiles _POST_ 8 | Send the information for building the livepatch object 9 | #### url: /elivepatch/api/v1.0/get_files 10 | - KernelVersion type=string required=False 11 | Kernel verson needed for know which kernel we are working 12 | - UUID type=string required=False 13 | Assigning a Universally Unique Identifier 14 | - patch type=werkzeug.datastructures.FileStorage required=True 15 | Previous applied patch to kernel 16 | - main_patch type=werkzeug.datastructures.FileStorage required=True 17 | Patch that will be converted in the live patch object 18 | - config type=werkzeug.datastructures.FileStorage required=True 19 | Configuraton file of the kernel 20 | 21 | #### example 22 | Success 23 | ``` 24 | { 25 | "KernelVersion": "5.1.9", 26 | "UUID': '57773c4c-65e2-4ed1-9daa-345737a9b05f" 27 | } 28 | ``` 29 | 30 | Fail 31 | ``` 32 | { 33 | "message": "These are not the patches you are looking for" 34 | } 35 | ``` 36 | 37 | ### Root _GET_ 38 | Root of the endpoint 39 | #### url: /elivepatch/api/ 40 | #### example 41 | curl -H "Accept: application/ld+json" -X GET http://localhost:5000/elivepatch/api/ | jd 42 | success 43 | ``` 44 | { 45 | "agent": [ 46 | { 47 | "module": "elivepatch", 48 | "version": "0.01" 49 | } 50 | ] 51 | } 52 | ``` 53 | 54 | ### Agent _GET_ 55 | Retrive agent informations 56 | #### url: /elivepatch/api/v1.0/agent 57 | #### example 58 | curl -H "Accept: application/ld+json" -X GET http://localhost:5000/elivepatch/api/v1.0/agent | jd 59 | success 60 | ``` 61 | { 62 | "agent": [ 63 | { 64 | "module": "elivepatch", 65 | "version": "0.01" 66 | } 67 | ] 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # IPython 78 | profile_default/ 79 | ipython_config.py 80 | 81 | # pyenv 82 | .python-version 83 | 84 | # celery beat schedule file 85 | celerybeat-schedule 86 | 87 | # SageMath parsed files 88 | *.sage.py 89 | 90 | # Environments 91 | .env 92 | .venv 93 | env/ 94 | venv/ 95 | ENV/ 96 | env.bak/ 97 | venv.bak/ 98 | 99 | # Spyder project settings 100 | .spyderproject 101 | .spyproject 102 | 103 | # Rope project settings 104 | .ropeproject 105 | 106 | # mkdocs documentation 107 | /site 108 | 109 | # mypy 110 | .mypy_cache/ 111 | .dmypy.json 112 | dmypy.json 113 | 114 | # Pyre type checker 115 | .pyre/ 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # elivepatch-server 2 | [![Build Status](https://travis-ci.org/gentoo/elivepatch-server.svg?branch=master)](https://travis-ci.org/gentoo/elivepatch-server) 3 | [![Maintainability](https://api.codeclimate.com/v1/badges/d79ff85d840722dbc9d6/maintainability)](https://codeclimate.com/github/gentoo/elivepatch-server/maintainability) 4 | [![Docker Pulls](https://img.shields.io/docker/pulls/alice2f/elivepatch-server.svg?style=plastic)](https://hub.docker.com/r/alice2f/elivepatch-server) 5 | [![Docker Cloud Build Status](https://img.shields.io/docker/cloud/build/alice2f/elivepatch-server.svg)](https://hub.docker.com/r/alice2f/elivepatch-server) 6 | 7 | Flexible Distributed Linux Kernel Live Patching 8 | 9 | ## System Dependencies 10 | `elivepatch-server` needs the correct toolchain to build a Linux Kernel and the following software: 11 | - [kpatch](https://github.com/dynup/kpatch) 12 | - [git](https://git-scm.com/) 13 | 14 | ## Setup 15 | `elivepatch-server` is a [flask](https://www.palletsprojects.com/p/flask/)-based application. 16 | 17 | You can use [virtualenv](https://virtualenv.pypa.io/en/stable/) to have a separate python3 environment. 18 | ``` sh 19 | $ cd elivepatch-server 20 | $ virtualenv .venv 21 | $ source .venv/bin/activate 22 | $ pip install -r requirements 23 | ``` 24 | 25 | ``` sh 26 | $ python elivepatch-server 27 | ``` 28 | 29 | Will run the server using [werkzeug](https://palletsprojects.com/p/werkzeug/) 30 | 31 | ## API 32 | 33 | - Endpoint root: /elivepatch/api/ 34 | - agent: /elivepatch/api/v1.0/agent 35 | - send_livepatch: /elivepatch/api/v1.0/send_livepatch 36 | - GetFiles: /elivepatch/api/v1.0/get_files 37 | 38 | More information on the REST API is [here](docs/API.md) 39 | 40 | ## Development 41 | 42 | You can use the [docker image](https://github.com/elivepatch/elivepatch-docker) to test your changes without the risk of damaging your system. 43 | 44 | Follow the provided [instructions](https://github.com/elivepatch/elivepatch-docker#basic-development) to set it up. 45 | -------------------------------------------------------------------------------- /src/elivepatch_server/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # (c) 2017, Alice Ferrazzi 5 | # Distributed under the terms of the GNU General Public License v2 or later 6 | 7 | __version__ = "0.1" 8 | __author__ = "Alice Ferrazzi" 9 | __license__ = "GNU GPLv2+" 10 | 11 | from flask import Flask 12 | from flask_restful import Api 13 | import multiprocessing 14 | import argparse 15 | 16 | from .resources import AgentInfo, dispatcher 17 | 18 | app = Flask(__name__, static_url_path="") 19 | 20 | app.config['ELP_JOBS'] = multiprocessing.cpu_count() 21 | 22 | api = Api(app) 23 | 24 | api.add_resource(AgentInfo.AgentAPI, "/elivepatch/api/", endpoint="root") 25 | 26 | # get agento information 27 | api.add_resource(AgentInfo.AgentAPI, "/elivepatch/api/v1.0/agent", endpoint="agent") 28 | 29 | # where to retrieve the live patch when ready 30 | api.add_resource( 31 | dispatcher.SendLivePatch, 32 | "/elivepatch/api/v1.0/send_livepatch", 33 | endpoint="send_livepatch", 34 | ) 35 | 36 | # where to receive the config file 37 | api.add_resource( 38 | dispatcher.GetFiles, 39 | "/elivepatch/api/v1.0/get_files", 40 | endpoint="config", 41 | ) 42 | 43 | def parse_args(): 44 | parser = argparse.ArgumentParser() 45 | 46 | parser.add_argument( 47 | "-j", 48 | "--jobs", 49 | type=int, 50 | default=multiprocessing.cpu_count(), 51 | help="Specify the number of make jobs", 52 | ) 53 | 54 | parser.add_argument( 55 | "-H", "--host", type=str, default="0.0.0.0", help="Specify the host" 56 | ) 57 | 58 | parser.add_argument( 59 | "-P", "--port", type=int, default="5000", help="Specify the port" 60 | ) 61 | 62 | parser.add_argument( 63 | "-T", "--threaded", action="store_true", help="Enable threading (ignored)" 64 | ) 65 | 66 | parser.add_argument( 67 | "-d", "--debug", action="store_true", help="Enable debugging" 68 | ) 69 | 70 | parser.add_argument( 71 | "-C", 72 | "--ssl-cert", 73 | type=str, 74 | help="Use a ssl certificate, `adhoc` to autogenerate a self-signed one", 75 | ) 76 | 77 | parser.add_argument( 78 | "-K", 79 | "--ssl-key", 80 | type=str, 81 | help="Use a ssl private key, omit it if you want to use an autogenerated cert/key", 82 | ) 83 | 84 | return parser.parse_args() 85 | 86 | 87 | def run(): 88 | cmdline_args = parse_args() 89 | 90 | kwargs = dict( 91 | host=cmdline_args.host, 92 | port=cmdline_args.port, 93 | ) 94 | 95 | if cmdline_args.ssl_cert == "adhoc": 96 | kwargs["ssl_context"] = "adhoc" 97 | 98 | app.config['DEBUG'] = cmdline_args.debug; 99 | app.config['ELP_JOBS'] = cmdline_args.jobs; 100 | 101 | app.run(**kwargs) 102 | 103 | 104 | if __name__ == "__main__": 105 | run() 106 | -------------------------------------------------------------------------------- /src/elivepatch_server/resources/dispatcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # (c) 2017, Alice Ferrazzi 5 | # Distributed under the terms of the GNU General Public License v2 or later 6 | 7 | 8 | import os 9 | import re 10 | import werkzeug 11 | import logging 12 | 13 | from flask import jsonify, make_response, current_app 14 | from flask_restful import Resource, reqparse, fields, marshal 15 | from .livepatch import PaTch 16 | 17 | pack_fields = {"KernelVersion": fields.String, "UUID": fields.String} 18 | 19 | packs = {"id": 1, "KernelVersion": None, "UUID": None} 20 | 21 | 22 | def check_uuid(uuid): 23 | """ 24 | Check uuid is in the correct format 25 | :param uuid: 26 | :return: 27 | """ 28 | if not uuid: 29 | logging.error("uuid is missing") 30 | else: 31 | # check uuid format 32 | prog = re.compile("^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$") 33 | result = prog.match(uuid) 34 | if result: 35 | logging.debug("UUID: " + str(uuid)) 36 | return uuid 37 | logging.error("uuid format is not correct") 38 | 39 | 40 | def get_uuid_dir(uuid): 41 | return os.path.join("/tmp/", "elivepatch-" + uuid) 42 | 43 | 44 | class SendLivePatch(Resource): 45 | def __init__(self): 46 | self.reqparse = reqparse.RequestParser() 47 | self.reqparse.add_argument( 48 | "KernelVersion", 49 | type=str, 50 | required=False, 51 | help="No task title provided", 52 | location="json", 53 | ) 54 | self.reqparse.add_argument( 55 | "UUID", 56 | type=str, 57 | required=False, 58 | help="No task title provided", 59 | location="json", 60 | ) 61 | super(SendLivePatch, self).__init__() 62 | pass 63 | 64 | def get(self): 65 | args = self.reqparse.parse_args() 66 | logging.debug("get livepatch: " + str(args)) 67 | # check if is a valid UUID request 68 | args["UUID"] = check_uuid(args["UUID"]) 69 | uuid_dir = get_uuid_dir(args["UUID"]) 70 | 71 | livepatch_full_path = os.path.join(uuid_dir, "elivepatch-main.ko") 72 | try: 73 | with open(livepatch_full_path, "rb") as fp: 74 | response = make_response(fp.read()) 75 | response.headers["content-type"] = ", application/octet-stream" 76 | return response 77 | except: 78 | return make_response( 79 | jsonify( 80 | { 81 | "message": "These are not the \ 82 | patches you are looking for" 83 | } 84 | ), 85 | 403, 86 | ) 87 | 88 | def post(self): 89 | return make_response( 90 | jsonify( 91 | { 92 | "message": "These are not the \ 93 | patches you are looking for" 94 | } 95 | ), 96 | 403, 97 | ) 98 | 99 | 100 | class GetFiles(Resource): 101 | def __init__(self, **kwargs): 102 | self.reqparse = reqparse.RequestParser() 103 | self.reqparse.add_argument( 104 | "KernelVersion", 105 | type=str, 106 | required=False, 107 | help="No task title provided", 108 | location="headers", 109 | ) 110 | self.reqparse.add_argument( 111 | "UUID", 112 | type=str, 113 | required=False, 114 | help="No task title provided", 115 | location="headers", 116 | ) 117 | super(GetFiles, self).__init__() 118 | pass 119 | 120 | def get(self): 121 | return make_response( 122 | jsonify( 123 | { 124 | "message": "These are not the \ 125 | patches you are looking for" 126 | } 127 | ), 128 | 403, 129 | ) 130 | 131 | def post(self): 132 | app = current_app 133 | args = self.reqparse.parse_args() 134 | args["UUID"] = check_uuid(args["UUID"]) 135 | parse = reqparse.RequestParser() 136 | parse.add_argument( 137 | "patch", 138 | action="append", 139 | type=werkzeug.datastructures.FileStorage, 140 | location="files", 141 | ) 142 | parse.add_argument( 143 | "main_patch", 144 | action="append", 145 | type=werkzeug.datastructures.FileStorage, 146 | location="files", 147 | ) 148 | parse.add_argument( 149 | "config", 150 | type=werkzeug.datastructures.FileStorage, 151 | location="files", 152 | ) 153 | file_args = parse.parse_args() 154 | 155 | uuid_dir = get_uuid_dir(args["UUID"]) 156 | if os.path.exists(uuid_dir): 157 | logging.debug('the folder: "' + uuid_dir + '" is already present') 158 | return ( 159 | {"the request with " + args["UUID"] + " is already present"}, 160 | 201, 161 | ) 162 | else: 163 | logging.debug('creating: "' + uuid_dir + '"') 164 | os.makedirs(uuid_dir) 165 | 166 | logging.info("file get config: " + str(file_args)) 167 | configFile = file_args["config"] 168 | # saving config file 169 | configFile_name = os.path.join(uuid_dir, file_args["config"].filename) 170 | configFile.save(configFile_name) 171 | 172 | lpatch = PaTch(uuid_dir, configFile_name) 173 | 174 | # saving incremental patches 175 | incremental_patches_directory = os.path.join( 176 | uuid_dir, 177 | "etc", 178 | "portage", 179 | "patches", 180 | "sys-kernel", 181 | "gentoo-sources", 182 | ) 183 | if os.path.exists(incremental_patches_directory): 184 | logging.debug('the folder: "' + uuid_dir + '" is already present') 185 | return ( 186 | {"the request with " + args["UUID"] + " is already present"}, 187 | 201, 188 | ) 189 | else: 190 | logging.debug("creating: " + incremental_patches_directory) 191 | os.makedirs(incremental_patches_directory) 192 | try: 193 | for patch in file_args["patch"]: 194 | logging.debug(str(patch)) 195 | patchfile = patch 196 | patchfile_name = patch.filename 197 | patch_fulldir_name = os.path.join( 198 | incremental_patches_directory, patchfile_name 199 | ) 200 | patchfile.save(patch_fulldir_name) 201 | except: 202 | logging.error("no incremental patches") 203 | 204 | # saving main patch 205 | logging.info(str(file_args["main_patch"])) 206 | main_patchfile = file_args["main_patch"][0] 207 | main_patchfile_name = main_patchfile.filename 208 | main_patch_fulldir_name = os.path.join(uuid_dir, main_patchfile_name) 209 | main_patchfile.save(main_patch_fulldir_name) 210 | 211 | # check vmlinux presence if not rebuild the kernel 212 | kernel_sources_status = lpatch.get_kernel_sources( 213 | args["KernelVersion"], debug=app.config["DEBUG"] 214 | ) 215 | if not kernel_sources_status: 216 | return make_response( 217 | jsonify({"message": "gentoo-sources not available"}), 403 218 | ) 219 | lpatch.build_livepatch( 220 | "vmlinux", jobs=app.config["ELP_JOBS"], debug=app.config["DEBUG"] 221 | ) 222 | 223 | pack = { 224 | "id": packs["id"] + 1, 225 | "KernelVersion": None, 226 | "UUID": args["UUID"], 227 | } 228 | return {"get_config": marshal(pack, pack_fields)}, 201 229 | -------------------------------------------------------------------------------- /src/elivepatch_server/resources/livepatch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, Alice Ferrazzi 5 | # Distributed under the terms of the GNU General Public License v2 or later 6 | 7 | import subprocess 8 | import os 9 | import fileinput 10 | import tempfile 11 | import shutil 12 | import logging 13 | 14 | 15 | class PaTch(object): 16 | def __init__(self, base_dir, base_config_path): 17 | self.base_dir = base_dir 18 | self.base_config_path = base_config_path 19 | 20 | self.__kernel_source_dir__ = os.path.join( 21 | self.base_dir, "usr/src/linux/" 22 | ) 23 | 24 | def build_livepatch(self, vmlinux, jobs, debug=True): 25 | """ 26 | Function for building the livepatch 27 | 28 | :param vmlinux: path to the vmlinux file 29 | :param debug: copy build.log in the base directory 30 | :return: void 31 | """ 32 | vmlinux_source = os.path.join(self.__kernel_source_dir__, vmlinux) 33 | kpatch_cachedir = os.path.join(self.base_dir, "kpatch") 34 | 35 | os.makedirs(kpatch_cachedir) 36 | if not os.path.isfile(vmlinux_source): 37 | self.build_kernel(jobs) 38 | 39 | bashCommand = [ 40 | "kpatch-build", 41 | "-s", 42 | self.__kernel_source_dir__, 43 | "-v", 44 | vmlinux_source, 45 | "-j", 46 | str(jobs), 47 | "-c", 48 | "config", 49 | "-n", 50 | "elivepatch-main", 51 | "--skip-gcc-check", 52 | "main.patch", 53 | ] 54 | if debug: 55 | bashCommand.extend(["--skip-cleanup"]) 56 | bashCommand.extend(["-dddd"]) 57 | _command(bashCommand, self.base_dir, {"CACHEDIR": kpatch_cachedir}) 58 | if debug: 59 | shutil.copy( 60 | os.path.join(kpatch_cachedir, "build.log"), self.base_dir 61 | ) 62 | 63 | def get_kernel_sources(self, kernel_version, debug=True): 64 | """ 65 | Function for download the kernel sources 66 | 67 | :return: void 68 | """ 69 | try: 70 | _command( 71 | [ 72 | "git", 73 | "clone", 74 | "https://github.com/aliceinwire/gentoo-sources_overlay.git", 75 | ] 76 | ) 77 | except: 78 | logging.error("git clone failed.") 79 | 80 | ebuild_path = os.path.join( 81 | "gentoo-sources_overlay", 82 | "sys-kernel", 83 | "gentoo-sources", 84 | "gentoo-sources-" + kernel_version + ".ebuild", 85 | ) 86 | logging.info(ebuild_path) 87 | if os.path.isfile(ebuild_path): 88 | # Use a private tmpdir for portage 89 | with tempfile.TemporaryDirectory( 90 | dir=self.base_dir 91 | ) as portage_tmpdir: 92 | logging.info( 93 | "base_dir: " 94 | + str(self.base_dir) 95 | + " PORTAGE_TMPDIR: " 96 | + str(portage_tmpdir) 97 | ) 98 | # portage_tmpdir is not always working with root privileges 99 | if debug: 100 | if os.geteuid() != 0: 101 | env = { 102 | "ROOT": self.base_dir, 103 | "PORTAGE_CONFIGROOT": self.base_dir, 104 | "PORTAGE_TMPDIR": portage_tmpdir, 105 | "PORTAGE_DEBUG": "1", 106 | } 107 | else: 108 | env = { 109 | "ROOT": self.base_dir, 110 | "PORTAGE_CONFIGROOT": self.base_dir, 111 | "PORTAGE_TMPDIR": self.base_dir, 112 | "PORTAGE_DEBUG": "1", 113 | } 114 | else: 115 | if os.geteuid() != 0: 116 | env = { 117 | "ROOT": self.base_dir, 118 | "PORTAGE_CONFIGROOT": self.base_dir, 119 | "PORTAGE_TMPDIR": portage_tmpdir, 120 | } 121 | else: 122 | env = { 123 | "ROOT": self.base_dir, 124 | "PORTAGE_CONFIGROOT": self.base_dir, 125 | "PORTAGE_TMPDIR": self.base_dir, 126 | } 127 | _command( 128 | ["ebuild", ebuild_path, "digest", "clean", "merge"], 129 | env=env, 130 | ) 131 | kernel_sources_status = True 132 | else: 133 | logging.error("ebuild not present") 134 | kernel_sources_status = None 135 | return kernel_sources_status 136 | 137 | def build_kernel(self, jobs): 138 | kernel_config_path = os.path.join( 139 | self.__kernel_source_dir__, ".config" 140 | ) 141 | 142 | if "CONFIG_DEBUG_INFO=y" in open(self.base_config_path).read(): 143 | logging.debug("DEBUG_INFO correctly present") 144 | elif "CONFIG_DEBUG_INFO=n" in open(self.base_config_path).read(): 145 | logging.debug("changing DEBUG_INFO to yes") 146 | for line in fileinput.input(self.base_config_path, inplace=1): 147 | out = line.replace( 148 | "CONFIG_DEBUG_INFO=n", "CONFIG_DEBUG_INFO=y" 149 | ) 150 | logging.debug(out) 151 | else: 152 | logging.debug("Adding DEBUG_INFO for getting kernel debug symbols") 153 | for line in fileinput.input(self.base_config_path, inplace=1): 154 | out = line.replace( 155 | "# CONFIG_DEBUG_INFO is not set", "CONFIG_DEBUG_INFO=y" 156 | ) 157 | logging.debug(out) 158 | shutil.copyfile(self.base_config_path, kernel_config_path) 159 | # olddefconfig default everything that is new from the configuration file 160 | _command(["make", "olddefconfig"], self.__kernel_source_dir__) 161 | # copy the olddefconfig generated config file back, 162 | # so that we don't trigger a config restart when kpatch-build runs 163 | shutil.copyfile(kernel_config_path, self.base_config_path) 164 | _command(["make", "-j", str(jobs)], self.__kernel_source_dir__) 165 | _command(["make", "modules"], self.__kernel_source_dir__) 166 | 167 | 168 | def _command(bashCommand, kernel_source_dir=None, env=None): 169 | """ 170 | Popen override function 171 | 172 | :param bashCommand: List of command arguments to execute 173 | :param kernel_source_dir: String with the directory where the command is executed 174 | :param env: Dictionary for setting system environment variable 175 | :return: void 176 | """ 177 | # Inherit the parent environment and update the private copy 178 | if env: 179 | process_env = os.environ.copy() 180 | process_env.update(env) 181 | env = process_env 182 | 183 | if kernel_source_dir: 184 | logging.info(bashCommand) 185 | process = subprocess.Popen( 186 | bashCommand, stdout=subprocess.PIPE, cwd=kernel_source_dir, env=env 187 | ) 188 | output, error = process.communicate() 189 | for output_line in output.split(b"\n"): 190 | logging.info(output_line.strip().decode("utf-8")) 191 | else: 192 | logging.info(bashCommand) 193 | process = subprocess.Popen( 194 | bashCommand, stdout=subprocess.PIPE, env=env 195 | ) 196 | output, error = process.communicate() 197 | for output_line in output.split(b"\n"): 198 | logging.info(output_line.strip().decode("utf-8")) 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------