├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── installer ├── opsconfig │ ├── __init__.py │ ├── installer.py │ ├── menu.py │ ├── nginxConfigManipulator.py │ ├── nginxInstaller.py │ ├── nginxparser.py │ └── utils.py ├── pyproject.toml ├── requirements.txt └── tests │ ├── config.yml │ └── nginxconfig │ ├── both.com │ ├── cssblur │ ├── multiple.com │ └── test.com └── instructions.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | installer/__pycache__ 3 | installer/build 4 | installer/dist 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to open-pdf-sign-configurator 2 | 3 | We welcome contributions to open-pdf-sign-configurator! Here are some guidelines to help you get started. 4 | 5 | ## Code of Conduct 6 | 7 | We follow the [Contributor Covenant](https://www.contributor-covenant.org/) code of conduct. Please make sure to read and follow it when interacting with the project. 8 | 9 | ## Submitting Changes 10 | 11 | - Fork the repository and create a new branch for your changes. 12 | - Make your changes in the new branch. 13 | - Add tests for any new functionality. 14 | - Ensure that all tests pass. 15 | - Submit a pull request from your branch to the `main` branch of the main repository. 16 | 17 | ## Reporting Issues 18 | 19 | If you find any issues with the project, please open a new issue in the [issue tracker](https://github.com/open-pdf-sign/open-pdf-sign/issues) and include the following information: 20 | 21 | - A clear and concise description of the issue. 22 | - Steps to reproduce the issue. 23 | - Any relevant error messages or logs. 24 | 25 | 26 | ## License 27 | 28 | open-pdf-sign-configurator is licensed under the [APL 2](https://github.com/open-pdf-sign/open-pdf-sign-configurator/blob/master/LICENSE) license. By contributing to the project, you agree to license your contributions under the same license. 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # open-pdf-sign-configurator 2 | 3 | open-pdf-sign-configurator is a tool that simplifies the process of setting up and configuring open-pdf-sign on an nginx server. It automates many of the steps involved in the installation and configuration process, making it quick and easy for users to get open-pdf-sign up and running on their web servers. This can help save time and reduce the potential for errors, allowing users to quickly and easily sign PDFs on their web server. 4 | 5 | After you install and activate it, all PDFs served by your Nginx server will automatically be signed by your 6 | SSL certificate. 7 | 8 | For more details please go to https://openpdfsign.org/ 9 | ## Requirements 10 | * Java 8 or higher 11 | * python 3.9 or higher 12 | * Webserver (currently only Nginx supported) 13 | * SSL certificate (tested with letsencrypt) 14 | 15 | ## Install 16 | TLDR: 17 | 18 | ```bash 19 | apt-get install default-jre python3 python3-pip 20 | pip install openpdfsign-configurator 21 | opsconfig 22 | ``` 23 | 24 | for detailed instructions please go to: [Instructions](https://github.com/open-pdf-sign/open-pdf-sign-configurator/blob/main/instructions.md) 25 | 26 | 27 | If you want to remove, remove relevant blocks in your Nginx config and run 28 | 29 | ```bash 30 | rm /etc/systemd/system/openpdfsign.service 31 | rm -rf /etc/openpdfsign 32 | ``` 33 | 34 | 35 | ## Development 36 | * go to the "installer" folder 37 | * create a virtual environment 38 | * do pip install -r requirements.txt 39 | 40 | In order to develop, you can simply run the main.py file, just make sure to change the "stage" from "prod" to "dev" 41 | 42 | ### Testing 43 | This will create a docker container with: 44 | - Nginx server running 45 | - A certificate for test.com 46 | - all dependencies installed 47 | 48 | go to the file main.py in directory installer and change "prod" to "test" 49 | 50 | ```bash 51 | cd installer 52 | python -m build 53 | cp dist/*.whl ../test/installerdev 54 | cd ../test/installerdev 55 | vim Dockerfile #(change the version of the whl file if necessery) 56 | docker build -t nginx . 57 | docker run --name installertest -d -p 80:80 -p 443:443 nginx 58 | docker exec -it installertest bash 59 | opsconfig 60 | java -jar /etc/openpdfsign/openpdfsign.jar --config /etc/openpdfsign/config.yml 61 | ``` 62 | visit: https://127.0.0.1/test1.pdf 63 | 64 | ### Release 65 | - python -m build 66 | - twine upload -r testpypi dist/* 67 | - twine upload -r pypi dist/* 68 | 69 | #### Testing a release 70 | This will test the pypi test pip package. 71 | In order to test you can run the following commands. 72 | 73 | ```bash 74 | cd test/installerrelease 75 | docker build -t nginx . 76 | docker run --name installertest -d -p 80:80 -p 443:443 nginx 77 | docker exec -it installertest bash 78 | opsconfig 79 | java -jar /etc/openpdfsign/openpdfsign.jar --config /etc/openpdfsign/config.yml 80 | ``` 81 | visit: https://127.0.0.1/test1.pdf 82 | 83 | ## License 84 | 85 | This project is licensed under the Apache 2.0-License. 86 | -------------------------------------------------------------------------------- /installer/opsconfig/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-pdf-sign/open-pdf-sign-configurator/6d008da19d8b623eb46a602ffefdcccd40a75d60/installer/opsconfig/__init__.py -------------------------------------------------------------------------------- /installer/opsconfig/installer.py: -------------------------------------------------------------------------------- 1 | from opsconfig import nginxInstaller 2 | from opsconfig import utils 3 | 4 | # can be: "test", "prod" or "dev" 5 | stage = "test" 6 | installpath = "/etc/openpdfsign/" 7 | ymlConfigFilePath = installpath + "config.yml" 8 | if stage == "dev": 9 | ymlConfigFilePath = "config.yml" 10 | installpath = "./" 11 | 12 | 13 | def main(): 14 | services = nginxInstaller.run(stage) 15 | # save all to yml file 16 | utils.createInstallDirs(installpath) 17 | utils.saveConfigToYml(services, ymlConfigFilePath) 18 | utils.startServerAsService(ymlConfigFilePath, installpath, stage) 19 | 20 | 21 | if stage == "test": 22 | main() 23 | 24 | # install via apt-get https://earthly.dev/blog/creating-and-hosting-your-own-deb-packages-and-apt-repo/ 25 | -------------------------------------------------------------------------------- /installer/opsconfig/menu.py: -------------------------------------------------------------------------------- 1 | def installMenu(installers): 2 | # Create the menu 3 | print("Which names would you like to activate PDF signing for?") 4 | print("------------------------------------------------------------") 5 | i = 1 6 | infos = [] 7 | offsets = [] 8 | for installer in installers: 9 | info = installer.getNginxInfo() 10 | for entry in info: 11 | print(str(i) + ":", " ".join(entry["host"])) 12 | i += 1 13 | offsets.append(i-1) 14 | infos.append(info) 15 | print("------------------------------------------------------------") 16 | print( 17 | "Select the appropriate numbers separated by commas or leave input blank to select all options shown (Enter 'c' to cancel):") 18 | userInput = input() 19 | if userInput == "c": return 20 | optionsInt = list(range(i-1)) 21 | if userInput != "": 22 | options = userInput.split(",") 23 | try: 24 | optionsInt = [int(o) - 1 for o in options] 25 | except: 26 | print("didn't recognize input") 27 | 28 | if len(set(optionsInt)) is not len(optionsInt): 29 | print("multiple selections") 30 | return [], [] 31 | for o in optionsInt: 32 | if o < 0 or o >= i: 33 | print(o + 1, "out of range") 34 | return [], infos 35 | selection = [[] for _ in range(len(infos))] 36 | for i in optionsInt: 37 | j = 0 38 | for offset in offsets: 39 | if i < offset: 40 | if j > 0: 41 | selection[j].append(i - offsets[j - 1]) 42 | else: 43 | selection[j].append(i) 44 | break 45 | j += 1 46 | 47 | return selection, infos 48 | -------------------------------------------------------------------------------- /installer/opsconfig/nginxConfigManipulator.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from opsconfig import nginxparser 4 | 5 | 6 | class NginxConfigManipulator: 7 | exe = "nginx" 8 | configFile = "" 9 | parsed = None 10 | 11 | def __init__(self, configFile): 12 | self.configFile = configFile 13 | 14 | def checkExe(self, exe): 15 | path, _ = os.path.split(exe) 16 | if path and os.path.isfile(path) and os.access(path, os.X_OK): 17 | pass 18 | else: 19 | return False 20 | for path in os.environ["PATH"].split(os.pathsep): 21 | newExe = os.path.join(path, exe) 22 | if newExe and os.path.isfile(newExe) and os.access(newExe, os.X_OK): 23 | return True 24 | 25 | def getNginxInfo(self): 26 | # check if nginx exists 27 | self.checkExe("nginx") 28 | # check if config is ok 29 | # nginx -t 30 | with open(self.configFile) as filee: 31 | self.parsed = nginxparser.load(filee) 32 | 33 | keys = [] 34 | # check each server block 35 | counter = 0 36 | for server in self.parsed: 37 | # check all elements in server block 38 | for element in server: 39 | if len(element) > 0 and element[0] != "server": 40 | key = {} 41 | for el in element: 42 | key["index"] = counter 43 | if el[0] == "server_name": 44 | key["host"] = [el[e] for e in range(1,len(el))] 45 | if el[0] == "ssl_certificate": 46 | key["certificate"] = el[1] 47 | if el[0] == "ssl_certificate_key": 48 | key["key"] = el[1] 49 | 50 | if len(key.keys()) == 4: 51 | keys.append(key) 52 | break 53 | if element == "#": 54 | if "managed by open-pdf-sign" in server[1]: 55 | print(keys[-1]["server_name"], "already configured") 56 | counter += 1 57 | return keys 58 | 59 | def insertBlocks(self, selection): 60 | port = '8090' 61 | position = 0 62 | directive = [['\n ', 'location', ' ', '~', ' ', '\\.(pdf)$', ' '], [ 63 | ['\n ', 'proxy_set_header', ' ', 'X-Forwarded-For', ' ', '$proxy_add_x_forwarded_for', ' '], 64 | ['\n ', 'proxy_set_header', ' ', 'X-Forwarded-Proto', ' ', '$scheme'], 65 | ['\n ', 'proxy_set_header', ' ', 'X-Real-IP', ' ', '$remote_addr'], 66 | ['\n ', 'proxy_set_header', ' ', 'Host', ' ', '$http_host'], 67 | ['\n ', 'proxy_set_header', ' ', 'X-Open-Pdf-Sign-Nginx-Version', ' ', '1.0.0'], 68 | ['\n ', 'proxy_set_header', ' ', 'X-Open-Pdf-Sign-File', ' ', '$document_root$uri'], 69 | ['\n ', 'proxy_pass', ' ', 'http://127.0.0.1:' + port + '/v1/sign$1'], 70 | ['\n ', 'proxy_redirect', ' ', 'off'], 71 | ]] 72 | comment = [' ', '#', ' managed by open-pdf-sign-configurator'] 73 | for serverBlock in selection: 74 | self.parsed[serverBlock][1].insert(position, directive) 75 | self.parsed[serverBlock][1].insert(position + 1, comment) 76 | -------------------------------------------------------------------------------- /installer/opsconfig/nginxInstaller.py: -------------------------------------------------------------------------------- 1 | import io 2 | 3 | from opsconfig import menu 4 | from opsconfig import nginxparser 5 | from opsconfig import utils 6 | from opsconfig.nginxConfigManipulator import NginxConfigManipulator 7 | 8 | 9 | def run(stage="dev"): 10 | if stage == "dev": 11 | nginxConfigsDir = "tests/nginxconfig/" 12 | elif stage == "test": 13 | nginxConfigsDir = "/etc/nginx/sites-available/" 14 | else: 15 | nginxConfigsDir = "/etc/nginx/sites-available/" 16 | 17 | nginxConfigs = utils.getNginxConfigs(nginxConfigsDir) 18 | installers = [] 19 | for nginxConfig in nginxConfigs: 20 | configFile = nginxConfig 21 | installer = NginxConfigManipulator(nginxConfigsDir + configFile) 22 | installers.append(installer) 23 | selection, infos = menu.installMenu(installers) 24 | 25 | services = [] 26 | for i in range(len(infos)): 27 | installer = installers[i] 28 | service = [infos[i][s] for s in selection[i]] 29 | services.extend(service) 30 | installer.insertBlocks([s["index"] for s in service]) 31 | if stage == "dev": 32 | nginxDump = nginxparser.dumps(installer.parsed) 33 | print(nginxDump) 34 | else: 35 | with io.open(installer.configFile, "w", encoding="utf-8") as config: 36 | nginxparser.dump(installer.parsed, config) 37 | return services 38 | -------------------------------------------------------------------------------- /installer/opsconfig/nginxparser.py: -------------------------------------------------------------------------------- 1 | """Very low-level nginx config parser based on pyparsing.""" 2 | # Forked from https://github.com/fatiherikli/nginxparser (MIT Licensed) 3 | # taken from https://github.com/certbot/certbot/blob/master/certbot-nginx/certbot_nginx/_internal/nginxparser.py (APL 2.0) 4 | import copy 5 | import logging 6 | import operator 7 | import typing 8 | from typing import Any 9 | from typing import IO 10 | from typing import Iterable 11 | from typing import Iterator 12 | from typing import List 13 | from typing import overload 14 | from typing import Tuple 15 | from typing import TYPE_CHECKING 16 | from typing import Union 17 | 18 | from pyparsing import Combine 19 | from pyparsing import Forward 20 | from pyparsing import Group 21 | from pyparsing import Literal 22 | from pyparsing import Optional 23 | from pyparsing import ParseResults 24 | from pyparsing import QuotedString 25 | from pyparsing import Regex 26 | from pyparsing import restOfLine 27 | from pyparsing import stringEnd 28 | from pyparsing import White 29 | from pyparsing import ZeroOrMore 30 | 31 | if TYPE_CHECKING: 32 | from typing_extensions import SupportsIndex # typing.SupportsIndex not supported on Python 3.7 33 | 34 | logger = logging.getLogger(__name__) 35 | 36 | 37 | class RawNginxParser: 38 | # pylint: disable=pointless-statement 39 | """A class that parses nginx configuration with pyparsing.""" 40 | 41 | # constants 42 | space = Optional(White()).leaveWhitespace() 43 | required_space = White().leaveWhitespace() 44 | 45 | left_bracket = Literal("{").suppress() 46 | right_bracket = space + Literal("}").suppress() 47 | semicolon = Literal(";").suppress() 48 | dquoted = QuotedString('"', multiline=True, unquoteResults=False, escChar='\\') 49 | squoted = QuotedString("'", multiline=True, unquoteResults=False, escChar='\\') 50 | quoted = dquoted | squoted 51 | head_tokenchars = Regex(r"(\$\{)|[^{};\s'\"]") # if (last_space) 52 | tail_tokenchars = Regex(r"(\$\{)|[^{;\s]") # else 53 | tokenchars = Combine(head_tokenchars + ZeroOrMore(tail_tokenchars)) 54 | paren_quote_extend = Combine(quoted + Literal(')') + ZeroOrMore(tail_tokenchars)) 55 | # note: ')' allows extension, but then we fall into else, not last_space. 56 | 57 | token = paren_quote_extend | tokenchars | quoted 58 | 59 | whitespace_token_group = space + token + ZeroOrMore(required_space + token) + space 60 | assignment = whitespace_token_group + semicolon 61 | 62 | comment = space + Literal('#') + restOfLine 63 | 64 | block = Forward() 65 | 66 | # order matters! see issue 518, and also http { # server { \n} 67 | contents = Group(comment) | Group(block) | Group(assignment) 68 | 69 | block_begin = Group(whitespace_token_group) 70 | block_innards = Group(ZeroOrMore(contents) + space).leaveWhitespace() 71 | block << block_begin + left_bracket + block_innards + right_bracket 72 | 73 | script = ZeroOrMore(contents) + space + stringEnd 74 | script.parseWithTabs().leaveWhitespace() 75 | 76 | def __init__(self, source: str) -> None: 77 | self.source = source 78 | 79 | def parse(self) -> ParseResults: 80 | """Returns the parsed tree.""" 81 | return self.script.parseString(self.source) 82 | 83 | def as_list(self) -> List[Any]: 84 | """Returns the parsed tree as a list.""" 85 | return self.parse().asList() 86 | 87 | 88 | class RawNginxDumper: 89 | """A class that dumps nginx configuration from the provided tree.""" 90 | def __init__(self, blocks: List[Any]) -> None: 91 | self.blocks = blocks 92 | 93 | def __iter__(self, blocks: typing.Optional[List[Any]] = None) -> Iterator[str]: 94 | """Iterates the dumped nginx content.""" 95 | blocks = blocks or self.blocks 96 | for b0 in blocks: 97 | if isinstance(b0, str): 98 | yield b0 99 | continue 100 | item = copy.deepcopy(b0) 101 | if spacey(item[0]): 102 | yield item.pop(0) # indentation 103 | if not item: 104 | continue 105 | 106 | if isinstance(item[0], list): # block 107 | yield "".join(item.pop(0)) + '{' 108 | for parameter in item.pop(0): 109 | for line in self.__iter__([parameter]): # negate "for b0 in blocks" 110 | yield line 111 | yield '}' 112 | else: # not a block - list of strings 113 | semicolon = ";" 114 | if isinstance(item[0], str) and item[0].strip() == '#': # comment 115 | semicolon = "" 116 | yield "".join(item) + semicolon 117 | 118 | def __str__(self) -> str: 119 | """Return the parsed block as a string.""" 120 | return ''.join(self) 121 | 122 | 123 | spacey = lambda x: (isinstance(x, str) and x.isspace()) or x == '' 124 | 125 | 126 | class UnspacedList(List[Any]): 127 | """Wrap a list [of lists], making any whitespace entries magically invisible""" 128 | 129 | def __init__(self, list_source: Iterable[Any]) -> None: 130 | # ensure our argument is not a generator, and duplicate any sublists 131 | self.spaced = copy.deepcopy(list(list_source)) 132 | self.dirty = False 133 | 134 | # Turn self into a version of the source list that has spaces removed 135 | # and all sub-lists also UnspacedList()ed 136 | super().__init__(list_source) 137 | for i, entry in reversed(list(enumerate(self))): 138 | if isinstance(entry, list): 139 | sublist = UnspacedList(entry) 140 | super().__setitem__(i, sublist) 141 | self.spaced[i] = sublist.spaced 142 | elif spacey(entry): 143 | # don't delete comments 144 | if "#" not in self[:i]: 145 | super().__delitem__(i) 146 | 147 | @overload 148 | def _coerce(self, inbound: None) -> Tuple[None, None]: ... 149 | 150 | @overload 151 | def _coerce(self, inbound: str) -> Tuple[str, str]: ... 152 | 153 | @overload 154 | def _coerce(self, inbound: List[Any]) -> Tuple["UnspacedList", List[Any]]: ... 155 | 156 | def _coerce(self, inbound: Any) -> Tuple[Any, Any]: 157 | """ 158 | Coerce some inbound object to be appropriately usable in this object 159 | :param inbound: string or None or list or UnspacedList 160 | :returns: (coerced UnspacedList or string or None, spaced equivalent) 161 | :rtype: tuple 162 | """ 163 | if not isinstance(inbound, list): # str or None 164 | return inbound, inbound 165 | else: 166 | if not hasattr(inbound, "spaced"): 167 | inbound = UnspacedList(inbound) 168 | return inbound, inbound.spaced 169 | 170 | def insert(self, i: "SupportsIndex", x: Any) -> None: 171 | """Insert object before index.""" 172 | idx = operator.index(i) 173 | item, spaced_item = self._coerce(x) 174 | slicepos = self._spaced_position(idx) if idx < len(self) else len(self.spaced) 175 | self.spaced.insert(slicepos, spaced_item) 176 | if not spacey(item): 177 | super().insert(idx, item) 178 | self.dirty = True 179 | 180 | 181 | def add(self, i: "SupportsIndex", x: Any) -> None: 182 | """Insert object before index.""" 183 | idx = operator.index(i) 184 | item, spaced_item = self._coerce(x) 185 | slicepos = self._spaced_position(idx) if idx < len(self) else len(self.spaced) 186 | self.spaced.insert(slicepos, spaced_item) 187 | 188 | def append(self, x: Any) -> None: 189 | """Append object to the end of the list.""" 190 | item, spaced_item = self._coerce(x) 191 | self.spaced.append(spaced_item) 192 | if not spacey(item): 193 | super().append(item) 194 | self.dirty = True 195 | 196 | def extend(self, x: Any) -> None: 197 | """Extend list by appending elements from the iterable.""" 198 | item, spaced_item = self._coerce(x) 199 | self.spaced.extend(spaced_item) 200 | super().extend(item) 201 | self.dirty = True 202 | 203 | def __add__(self, other: List[Any]) -> "UnspacedList": 204 | new_list = copy.deepcopy(self) 205 | new_list.extend(other) 206 | new_list.dirty = True 207 | return new_list 208 | 209 | def pop(self, *args: Any, **kwargs: Any) -> None: 210 | """Function pop() is not implemented for UnspacedList""" 211 | raise NotImplementedError("UnspacedList.pop() not yet implemented") 212 | 213 | def remove(self, *args: Any, **kwargs: Any) -> None: 214 | """Function remove() is not implemented for UnspacedList""" 215 | raise NotImplementedError("UnspacedList.remove() not yet implemented") 216 | 217 | def reverse(self) -> None: 218 | """Function reverse() is not implemented for UnspacedList""" 219 | raise NotImplementedError("UnspacedList.reverse() not yet implemented") 220 | 221 | def sort(self, *_args: Any, **_kwargs: Any) -> None: 222 | """Function sort() is not implemented for UnspacedList""" 223 | raise NotImplementedError("UnspacedList.sort() not yet implemented") 224 | 225 | def __setslice__(self, *args: Any, **kwargs: Any) -> None: 226 | raise NotImplementedError("Slice operations on UnspacedLists not yet implemented") 227 | 228 | def __setitem__(self, i: Union["SupportsIndex", slice], value: Any) -> None: 229 | if isinstance(i, slice): 230 | raise NotImplementedError("Slice operations on UnspacedLists not yet implemented") 231 | item, spaced_item = self._coerce(value) 232 | self.spaced.__setitem__(self._spaced_position(i), spaced_item) 233 | if not spacey(item): 234 | super().__setitem__(i, item) 235 | self.dirty = True 236 | 237 | def __delitem__(self, i: Union["SupportsIndex", slice]) -> None: 238 | if isinstance(i, slice): 239 | raise NotImplementedError("Slice operations on UnspacedLists not yet implemented") 240 | self.spaced.__delitem__(self._spaced_position(i)) 241 | super().__delitem__(i) 242 | self.dirty = True 243 | 244 | def __deepcopy__(self, memo: Any) -> "UnspacedList": 245 | new_spaced = copy.deepcopy(self.spaced, memo=memo) 246 | new_list = UnspacedList(new_spaced) 247 | new_list.dirty = self.dirty 248 | return new_list 249 | 250 | def is_dirty(self) -> bool: 251 | """Recurse through the parse tree to figure out if any sublists are dirty""" 252 | if self.dirty: 253 | return True 254 | return any((isinstance(x, UnspacedList) and x.is_dirty() for x in self)) 255 | 256 | def _spaced_position(self, idx: "SupportsIndex") -> int: 257 | """Convert from indexes in the unspaced list to positions in the spaced one""" 258 | int_idx = operator.index(idx) 259 | pos = spaces = 0 260 | # Normalize indexes like list[-1] etc, and save the result 261 | if int_idx < 0: 262 | int_idx = len(self) + int_idx 263 | if not 0 <= int_idx < len(self): 264 | raise IndexError("list index out of range") 265 | int_idx0 = int_idx 266 | # Count the number of spaces in the spaced list before int_idx in the unspaced one 267 | while int_idx != -1: 268 | if spacey(self.spaced[pos]): 269 | spaces += 1 270 | else: 271 | int_idx -= 1 272 | pos += 1 273 | return int_idx0 + spaces 274 | 275 | 276 | # Shortcut functions to respect Python's serialization interface 277 | # (like pyyaml, picker or json) 278 | 279 | def loads(source: str) -> UnspacedList: 280 | """Parses from a string. 281 | :param str source: The string to parse 282 | :returns: The parsed tree 283 | :rtype: list 284 | """ 285 | return UnspacedList(RawNginxParser(source).as_list()) 286 | 287 | 288 | def load(file_: IO[Any]) -> UnspacedList: 289 | """Parses from a file. 290 | :param file file_: The file to parse 291 | :returns: The parsed tree 292 | :rtype: list 293 | """ 294 | return loads(file_.read()) 295 | 296 | 297 | def dumps(blocks: UnspacedList) -> str: 298 | """Dump to a Unicode string. 299 | :param UnspacedList blocks: The parsed tree 300 | :rtype: six.text_type 301 | """ 302 | return str(RawNginxDumper(blocks.spaced)) 303 | 304 | 305 | def dump(blocks: UnspacedList, file_: IO[Any]) -> None: 306 | """Dump to a file. 307 | :param UnspacedList blocks: The parsed tree 308 | :param IO[Any] file_: The file stream to dump to. It must be opened with 309 | Unicode encoding. 310 | :rtype: None 311 | """ 312 | file_.write(dumps(blocks)) 313 | -------------------------------------------------------------------------------- /installer/opsconfig/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | import requests 5 | from yaml import dump 6 | 7 | jarUrl = "https://github.com/open-pdf-sign/open-pdf-sign/releases/latest/download/open-pdf-sign.jar" 8 | serviceContent = "[Unit]\n" \ 9 | "Description=Open-Pdf-Sign-Server\n" \ 10 | "\n" \ 11 | "[Install]\n" \ 12 | "WantedBy=multi-user.target\n" \ 13 | "\n" \ 14 | "[Service]\n" \ 15 | "Restart=always\n" \ 16 | "RuntimeMaxSec=2592000\n" \ 17 | "User=root\n" \ 18 | "StandardOutput=null\n" \ 19 | "StandardError=journal\n" \ 20 | "ExecStart=/usr/bin/java -jar /etc/openpdfsign/openpdfsign.jar --config " 21 | 22 | 23 | def saveConfigToYml(services, configFile): 24 | config = {} 25 | config["port"] = 8090 26 | config["host"] = "127.0.0.1" 27 | for service in services: 28 | service.pop("index", None) 29 | service["host"] = " ".join(service["host"]) 30 | config["certificates"] = services 31 | with open(configFile, 'w') as ymlConfig: 32 | dump(config, ymlConfig) 33 | pass 34 | 35 | 36 | def createInstallDirs(path): 37 | isdir = os.path.isdir(path) 38 | if not isdir: 39 | os.mkdir(path) 40 | 41 | 42 | def getNginxConfigs(path): 43 | paths = os.listdir(path) 44 | return paths 45 | 46 | 47 | def startServerAsService(configFile, installpath, stage="prod"): 48 | if stage == "prod": 49 | with open("/etc/systemd/system/openpdfsign.service", "w") as serviceFile: 50 | serviceFile.write(serviceContent + configFile) 51 | with open(installpath + "openpdfsign.jar", "wb") as jarFile: 52 | print("Downloading jar file") 53 | response = requests.get(jarUrl, stream=True) 54 | total_length = response.headers.get('content-length') 55 | 56 | if total_length is None: # no content length header 57 | jarFile.write(response.content) 58 | else: 59 | dl = 0 60 | total_length = int(total_length) 61 | for data in response.iter_content(chunk_size=4096): 62 | dl += len(data) 63 | jarFile.write(data) 64 | done = int(50 * dl / total_length) 65 | sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50 - done))) 66 | sys.stdout.flush() 67 | if stage == "prod": 68 | subprocess.run("service nginx reload;echo;", shell=True) 69 | subprocess.run("chmod +x /etc/openpdfsign/openpdfsign.jar", shell=True) 70 | subprocess.run("systemctl daemon-reload", shell=True) 71 | subprocess.run("systemctl start openpdfsign.service", shell=True) 72 | if stage == "test": 73 | subprocess.run("service nginx reload;echo;", shell=True) 74 | # write the service file 75 | # subprocess.check_output("systemctl enable openpdfsign") 76 | # (re)start service 77 | -------------------------------------------------------------------------------- /installer/pyproject.toml: -------------------------------------------------------------------------------- 1 | # pyproject.toml 2 | 3 | [build-system] 4 | requires = ["setuptools>=61.0.0", "wheel"] 5 | build-backend = "setuptools.build_meta" 6 | 7 | [project] 8 | name = "openpdfsign-configurator" 9 | version = "0.0.1" 10 | description = "This installs open-pdf-sign as server and signs all your PDFs served with Nginx with your SSL certificate" 11 | readme = "README.md" 12 | authors = [{ name = "Thomas Schreiber", email = "thomas@netzbeweis.com" }, 13 | { name = "Philipp Omenitsch", email = "philipp@netzbeweis.com" } 14 | ] 15 | license = { file = "LICENSE" } 16 | classifiers = [ 17 | "License :: OSI Approved :: Apache Software License", 18 | "Programming Language :: Python", 19 | "Programming Language :: Python :: 3", 20 | ] 21 | keywords = ["configurator", "sign", "pdf", "installer"] 22 | dependencies = [ 23 | "pyparsing>=3.0.9", 24 | "PyYAML>=6.0", 25 | "requests>=2.28.1" 26 | ] 27 | requires-python = ">=3.9" 28 | 29 | [project.urls] 30 | Homepage = "https://github.com/open-pdf-sign/open-pdf-sign-configurator" 31 | 32 | [project.scripts] 33 | opsconfig = "opsconfig.installer:main" 34 | -------------------------------------------------------------------------------- /installer/requirements.txt: -------------------------------------------------------------------------------- 1 | ansiwrap==0.8.4 2 | bleach==5.0.1 3 | build==0.9.0 4 | certifi==2022.9.24 5 | charset-normalizer==2.1.1 6 | click==8.1.3 7 | commonmark==0.9.1 8 | console-menu==0.7.1 9 | docutils==0.19 10 | idna==3.4 11 | importlib-metadata==5.0.0 12 | jaraco.classes==3.2.3 13 | keyring==23.11.0 14 | more-itertools==9.0.0 15 | packaging==21.3 16 | pep517==0.13.0 17 | pip-tools==6.10.0 18 | pkginfo==1.8.3 19 | Pygments==2.13.0 20 | pyparsing==3.0.9 21 | PyYAML==6.0 22 | readme-renderer==37.3 23 | requests==2.28.1 24 | requests-toolbelt==0.10.1 25 | rfc3986==2.0.0 26 | rich==12.6.0 27 | six==1.16.0 28 | textwrap3==0.9.2 29 | tomli==2.0.1 30 | twine==4.0.1 31 | urllib3==1.26.13 32 | webencodings==0.5.1 33 | zipp==3.10.0 34 | -------------------------------------------------------------------------------- /installer/tests/config.yml: -------------------------------------------------------------------------------- 1 | # location: /etc/openpdfsign/config.yml 2 | # CLI Aufruf java -jar open-pdf-sign.jar --config /etc/openpdfsign/config.yml 3 | 4 | port: 8081 # port where open-pdf-sign is listening 5 | host: 127.0.0.1 6 | # page: -1 # if not set, no visible signature 7 | certificates: 8 | - host: _ # default case 9 | key: /etc/letsencrypt/live/example.com/key.pem 10 | certificate: /etc/letsencrypt/live/example.com/fullchaim.pem 11 | - host: 12 | - exampleA.com 13 | - exampleB.com 14 | key: /etc/letsencrypt/live/example.com/key.pem 15 | certificate: /etc/letsencrypt/live/example.com/fullchaim.pem 16 | - host: example.com 17 | key: /etc/letsencrypt/live/example.com/key.pem 18 | certificate: /etc/letsencrypt/live/example.com/fullchaim.pem 19 | - host: www.example.com 20 | key: /etc/letsencrypt/live/www.example.com/key.pem 21 | certificate: /etc/letsencrypt/live/www.example.com/fullchaim.pem -------------------------------------------------------------------------------- /installer/tests/nginxconfig/both.com: -------------------------------------------------------------------------------- 1 | server { 2 | server_name ssl.both.com; 3 | } 4 | 5 | # a duplicate vhost 6 | server { 7 | server_name ssl.both.com; 8 | } 9 | 10 | # a duplicate by means of wildcard 11 | server { 12 | server_name *.both.com; 13 | } 14 | 15 | # combined HTTP and HTTPS 16 | server { 17 | server_name ssl.both.com; 18 | listen 80; 19 | listen 5001 ssl; 20 | 21 | ssl_certificate cert.pem; 22 | ssl_certificate_key cert.key; 23 | } 24 | 25 | # HTTPS, duplicate by means of wildcard 26 | server { 27 | server_name *.both.com; 28 | listen 5001 ssl; 29 | 30 | ssl_certificate cert.pem; 31 | ssl_certificate_key cert.key; 32 | } 33 | -------------------------------------------------------------------------------- /installer/tests/nginxconfig/cssblur: -------------------------------------------------------------------------------- 1 | server { 2 | 3 | root /var/www/cssblur/html; 4 | server_name cssblur.com www.cssblur.com; 5 | location / { 6 | try_files $uri $uri/ =404; 7 | } 8 | 9 | 10 | 11 | listen [::]:443 ssl ipv6only=on; # managed by Certbot 12 | listen 443 ssl; # managed by Certbot 13 | ssl_certificate /etc/letsencrypt/live/cssblur.com/fullchain.pem; # managed by Certbot 14 | ssl_certificate_key /etc/letsencrypt/live/cssblur.com/privkey.pem; # managed by Certbot 15 | include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot 16 | ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot 17 | 18 | 19 | } 20 | server { 21 | if ($host = www.cssblur.com) { 22 | return 301 https://$host$request_uri; 23 | } # managed by Certbot 24 | 25 | 26 | if ($host = cssblur.com) { 27 | return 301 https://$host$request_uri; 28 | } # managed by Certbot 29 | 30 | 31 | listen 80; 32 | listen [::]:80; 33 | server_name cssblur.com www.cssblur.com; 34 | return 404; # managed by Certbot 35 | 36 | 37 | 38 | 39 | } -------------------------------------------------------------------------------- /installer/tests/nginxconfig/multiple.com: -------------------------------------------------------------------------------- 1 | server { 2 | server_name one.com; 3 | 4 | ssl_certificate cert1.pem; 5 | ssl_certificate_key cert1.key; 6 | } 7 | 8 | server { 9 | server_name two.com; 10 | ssl_certificate cert2.pem; 11 | ssl_certificate_key cert2.key; 12 | } 13 | 14 | # combined HTTP and HTTPS 15 | server { 16 | server_name three.com four.com; 17 | listen 80; 18 | listen 5001 ssl; 19 | 20 | ssl_certificate cert.pem; 21 | ssl_certificate_key cert.key; 22 | } 23 | -------------------------------------------------------------------------------- /installer/tests/nginxconfig/test.com: -------------------------------------------------------------------------------- 1 | server { 2 | server_name ssl.both.com; 3 | } 4 | 5 | 6 | 7 | # combined HTTP and HTTPS 8 | server { 9 | server_name ssl.both.com; 10 | listen 80; 11 | listen 5001 ssl; 12 | 13 | ssl_certificate cert.pem; 14 | ssl_certificate_key cert.key; 15 | 16 | } 17 | 18 | # HTTPS, duplicate by means of wildcard 19 | server { 20 | server_name *..com; 21 | listen 5001 ssl; 22 | 23 | ssl_certificate cert.pem; 24 | ssl_certificate_key cert.key; 25 | } 26 | -------------------------------------------------------------------------------- /instructions.md: -------------------------------------------------------------------------------- 1 | # Installation Instructions for open-pdf-sign 2 | Following these instructions will make all PDFs served by your webserver signed by your SSL certificate 3 | 4 | ## Requirements 5 | - comfort with the command line 6 | - a Nginx webserver that is online and running debian or Ubuntu 7 | - a LetsEncrypt or other SSL certificate installed with Nginx 8 | - SSH access to your server with sudo rights 9 | 10 | ## Installation 11 | 12 | ### 1. SSH into your server 13 | 14 | SSH into the server running your HTTP website as a user with sudo privileges. 15 | ### 2. Install Dependencies 16 | ```bash 17 | apt-get install default-jre python3 python3-pip 18 | ``` 19 | ### 3. Install openpdfsign-configurator 20 | ```bash 21 | pip install openpdfsign-configurator 22 | ``` 23 | ### 4. Run the Configurator 24 | ```bash 25 | opsconfig 26 | ``` 27 | You can select the domain names where open-pdf-sign will be installed 28 | ### 5. Confirm that its working 29 | 30 | Go to the URL where you are currently serving a PDF 31 | Download it and check your signature i.e. here: https://ec.europa.eu/cefdigital/DSS/webapp-demo/validation 32 | --------------------------------------------------------------------------------