From efe0307a1d8c4b3afc025a9f763b9e091760c66f Mon Sep 17 00:00:00 2001 From: Diederik de Groot Date: Sun, 25 Nov 2018 21:14:09 +0100 Subject: [PATCH] Update rewrite ruls to handled encrypted and signed files Add certutils from usecallmanager.nz Add etc/certs directory --- etc/certs/encrypt | 7 + etc/certs/gencerts | 17 + etc/certs/gentlv | 16 + etc/certs/signfile | 6 + etc/nginx/sites-available/tftpboot | 122 +++--- etc/tftpd-hpa/rewrite.rules | 16 +- tools/certutils/COPYING | 339 +++++++++++++++++ tools/certutils/TLV/Builder.pm | 76 ++++ tools/certutils/TLV/Parser.pm | 96 +++++ tools/certutils/TLV/Tags.pm | 74 ++++ tools/certutils/certhash | 43 +++ tools/certutils/gencert | 234 ++++++++++++ tools/certutils/sgnfile | 384 +++++++++++++++++++ tools/certutils/stripsgn | 73 ++++ tools/certutils/tlvfile | 570 +++++++++++++++++++++++++++++ 15 files changed, 2009 insertions(+), 64 deletions(-) create mode 100755 etc/certs/encrypt create mode 100755 etc/certs/gencerts create mode 100755 etc/certs/gentlv create mode 100755 etc/certs/signfile create mode 100644 tools/certutils/COPYING create mode 100644 tools/certutils/TLV/Builder.pm create mode 100644 tools/certutils/TLV/Parser.pm create mode 100644 tools/certutils/TLV/Tags.pm create mode 100755 tools/certutils/certhash create mode 100755 tools/certutils/gencert create mode 100755 tools/certutils/sgnfile create mode 100755 tools/certutils/stripsgn create mode 100755 tools/certutils/tlvfile diff --git a/etc/certs/encrypt b/etc/certs/encrypt new file mode 100755 index 0000000..832575e --- /dev/null +++ b/etc/certs/encrypt @@ -0,0 +1,7 @@ +#!/bin/bash + +if [ $# -gt 0 ]; then + # Encrypt SEPMAC.cnf.xml + openssl enc -aes-256-cbc -salt -in ../../tftpboot/settings/${1} -out ../../tftpboot/settings/${1}.enc -k tftp.pem + ../../tools/certutils/sgnfile -b ../../tftpboot/settings/${1}.enc -c tftp.pem +fi \ No newline at end of file diff --git a/etc/certs/gencerts b/etc/certs/gencerts new file mode 100755 index 0000000..895a814 --- /dev/null +++ b/etc/certs/gencerts @@ -0,0 +1,17 @@ +#!/bin/bash +[ -f CA.pem ] && rm *.pem +# Create a CA certificate valid for 20 years. This will function as the SAST (System Administrator Security Token) certificate. +../../tools/certutils/gencert -n -C "Certificate Authority" -b 2048 -y 20 -o CA.pem +# Create a certificate for Asterisk signed by the CA for 1 year. This will function as the CCM certificate. +../../tools/certutils/gencert -c CA.pem -C Asterisk -b 2048 -y 1 -o asterisk.pem +# Create a certificate for TFTP signed by the CA for 1 year. This will function as the TFTP certificate. +../../tools/certutils/gencert -c CA.pem -C Asterisk -b 2048 -y 1 -o tftp.pem +# Create a certificate for webserver signed by the CA for 1 year (optional). This will function as an HTTPS certificate. +../../tools/certutils/gencert -c CA.pem -C WebServer -b 2048 -y 1 -o webserver.pem +# Create a certificate for VPN signed by the CA for 1 year (optional). +../../tools/certutils/gencert -c CA.pem -C VPN -b 2048 -y 1 -o vpn.pem +# Create a certificate for CAPF signed by the CA for 1 year (optional). +../../tools/certutils/gencert -c CA.pem -C CAPF -b 2048 -y 1 -o capf.pem +# Create a certificate for TVS signed by the CA for 1 year (optional). +../../tools/certutils/gencert -c CA.pem -C TVS -b 2048 -y 1 -o tvs.pem + diff --git a/etc/certs/gentlv b/etc/certs/gentlv new file mode 100755 index 0000000..ad3e6ba --- /dev/null +++ b/etc/certs/gentlv @@ -0,0 +1,16 @@ +#!/bin/bash + +if [ $# == 0 ]; then +# Create ITLFile.tlv in the tftpboot provisioning directory, the certificate used to sign the .tlv file is automatically included as providing the SAST function. +../../tools/certutils/tlvfile -b ../../tftpboot/settings/ITLFile.tlv -c CA.pem -r asterisk.pem -f ccm -r capf.pem -f capf -r tvs.pem -f tvs -r tftp.pem -f tftp -r webserver.pem -f https + +else +# Optionally, the default ITLFile.tlv can be overridden using a file name based on the MAC address of the phone, eg: ITLSEP58971ECC97C1.tlv. +../../tools/certutils/tlvfile -b ../../tftpboot/settings/ITL${1}.tlv -c CA.pem -r asterisk.pem -f ccm -r capf.pem -f capf -r tvs.pem -f tvs -r tftp.pem -f tftp -r webserver.pem -f https -F ITLFile.tlv + +# Optionally, additional certificates can be included using a file name based on the MAC address of the phone, eg: CTLSEP58971ECC97C1.tlv. +# Example for the VPN certificate +../../tools/certutils/tlvfile -b ../../tftpboot/settings/CTL${1}.tlv -c CA.pem -r vpn.pem -f https -F CTLFile.tlv + +# Enable SIP-TLS mode by setting to 3 and setting to either 2 (Authenticated) or 3 (Encrypted) in SEPMAC.cnf.xml. Optionally, any XML services can be configured to use HTTPS. +fi diff --git a/etc/certs/signfile b/etc/certs/signfile new file mode 100755 index 0000000..d0bcaa9 --- /dev/null +++ b/etc/certs/signfile @@ -0,0 +1,6 @@ +#!/bin/bash + +if [ $# -gt 0 ]; then +# Sign SEPMAC.cnf.xml +../../tools/certutils/sgnfile -b ../../tftpboot/settings/$1 -c tftp.pem +fi diff --git a/etc/nginx/sites-available/tftpboot b/etc/nginx/sites-available/tftpboot index 130a46a..1c58547 100644 --- a/etc/nginx/sites-available/tftpboot +++ b/etc/nginx/sites-available/tftpboot @@ -16,21 +16,21 @@ server { location / { # settings - rewrite ^/((.*)(\.cnf\.xml|\.tlv))$ /settings/$1 last; + rewrite ^/((.*)(\.cnf\.xml|\.tlv)(\.enc)?(\.sgn)?)$ /settings/$1 last; # firmware - rewrite ^/((.*).(bin|bin.|loads|LOADS|sbn|SBN|sb2|sbin|zz|zup)(|\.sgn))$ /firmware/$1 last; + rewrite ^/((.*).(bin|bin.|loads|LOADS|sbn|SBN|sb2|sbin|zz|zup)(\.sgn)?)$ /firmware/$1 last; # locales - rewrite ^/(.*)/((.*)-tones\.xml)$ /locales/countries/$1/$2 last; - rewrite ^/(.*)/((.*)(-dictionary\.xml|\.jar))$ /locales/languages/$1/$2 last; + rewrite ^/(.*)/((.*)-tones\.xml(\.sgn)?)$ /locales/countries/$1/$2 last; + rewrite ^/(.*)/((.*)(-dictionary\.xml|\.jar)(\.sgn)?)$ /locales/languages/$1/$2 last; # ringtones rewrite ^/([D|d]istinctive)?([R|r]ing[L|l]ist)\.(xml|XML)(\.sgn)?$ /ringtones/ringlist.xml last; - #rewrite ^/((.*)(\.raw|\.pcm)(|\.sgn))$ /ringtones/$1 last; + #rewrite ^/((.*)(\.raw|\.pcm)(\.sgn))?$ /ringtones/$1 last; # wallpapers - rewrite ^/Desktops/(.*)/(.*)$ /wallpapers/$1/$2 last; + rewrite ^/Desktops/(.*)/((.*)(\.sgn)?)$ /wallpapers/$1/$2 last; try_files $uri $uri/ =404; autoindex off; } @@ -78,14 +78,14 @@ server { rewrite ^/firmware/(CP7905080003SCCP070409A.zup)$ /firmware/7905/$1 last; # 7906_7911 firmware (java-based) - rewrite ^/firmware/(apps11.+\.sbn)$ /firmware/7906/$1 last; - rewrite ^/firmware/(cnu11.+\.sbn)$ /firmware/7906/$1 last; - rewrite ^/firmware/(cvm11sccp.+\.sbn)$ /firmware/7906/$1 last; - rewrite ^/firmware/(dsp11.+\.sbn)$ /firmware/7906/$1 last; - rewrite ^/firmware/(jar11sccp.+\.sbn)$ /firmware/7906/$1 last; - rewrite ^/firmware/(SCCP11.+\.loads)$ /firmware/7906/$1 last; - rewrite ^/firmware/(term06.+\.loads)$ /firmware/7906/$1 last; - rewrite ^/firmware/(term11.+\.loads)$ /firmware/7906/$1 last; + rewrite ^/firmware/(apps11.+\.sbn)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(cnu11.+\.sbn)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(cvm11sccp.+\.sbn)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(dsp11.+\.sbn)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(jar11sccp.+\.sbn)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(SCCP11.+\.loads)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(term06.+\.loads)$ /firmware/7906_7911/$1 last; + rewrite ^/firmware/(term11.+\.loads)$ /firmware/7906_7911/$1 last; # 7910 firmware (ancient) rewrite ^/firmware/(P00405000700.bin)$ /firmware/7910/$1 last; @@ -104,13 +104,13 @@ server { rewrite ^/firmware/(cmterm_7920.4.0-03-02.bin)$ /firmware/7920/$1 last; # 7921_7925 firmware (ancient) - rewrite ^/firmware/(APPS-1.4.3.4.SBN)$ /firmware/7921/$1 last; - rewrite ^/firmware/(CP7921G-1.4.3.4.LOADS)$ /firmware/7921/$1 last; - rewrite ^/firmware/(GUI-1.4.3.4.SBN)$ /firmware/7921/$1 last; - rewrite ^/firmware/(SYS-1.4.3.4.SBN)$ /firmware/7921/$1 last; - rewrite ^/firmware/(TNUX-1.4.3.4.SBN)$ /firmware/7921/$1 last; - rewrite ^/firmware/(TNUXR-1.4.3.4.SBN)$ /firmware/7921/$1 last; - rewrite ^/firmware/(WLAN-1.4.3.4.SBN)$ /firmware/7921/$1 last; + rewrite ^/firmware/(APPS-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(CP7921G-1.4.3.4.LOADS)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(GUI-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(SYS-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(TNUX-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(TNUXR-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; + rewrite ^/firmware/(WLAN-1.4.3.4.SBN)$ /firmware/7921_7925/$1 last; # 7926 firmware (ancient) rewrite ^/firmware/(APPSS-1.4.1SR1.SBN)$ /firmware/7926/$1 last; @@ -143,50 +143,50 @@ server { rewrite ^/firmware/(apps37sccp.1-4-5-7.bin)$ /firmware/7937/$1 last; # 7940_7960 firmware (ancient) - rewrite ^/firmware/(P0030801SR01.bin)$ /firmware/7940/$1 last; - rewrite ^/firmware/(P0030801SR01.loads)$ /firmware/7940/$1 last; - rewrite ^/firmware/(P0030801SR01.sb2)$ /firmware/7940/$1 last; - rewrite ^/firmware/(P0030801SR01.sbn)$ /firmware/7940/$1 last; + rewrite ^/firmware/(P0030801SR01.bin)$ /firmware/7940_7960/$1 last; + rewrite ^/firmware/(P0030801SR01.loads)$ /firmware/7940_7960/$1 last; + rewrite ^/firmware/(P0030801SR01.sb2)$ /firmware/7940_7960/$1 last; + rewrite ^/firmware/(P0030801SR01.sbn)$ /firmware/7940_7960/$1 last; # 7941_7961 firmware (java-based) - rewrite ^/firmware/(apps41.+\.sbn)$ /firmware/7941/$1 last; - rewrite ^/firmware/(cnu41.+\.sbn)$ /firmware/7941/$1 last; - rewrite ^/firmware/(cvm41sccp.+\.sbn)$ /firmware/7941/$1 last; - rewrite ^/firmware/(dsp41.+\.sbn)$ /firmware/7941/$1 last; - rewrite ^/firmware/(jar41sccp.+\.sbn)$ /firmware/7941/$1 last; - rewrite ^/firmware/(SCCP41.+\.loads)$ /firmware/7941/$1 last; - rewrite ^/firmware/(term41.+\.loads)$ /firmware/7941/$1 last; - rewrite ^/firmware/(term61.+\.loads)$ /firmware/7941/$1 last; + rewrite ^/firmware/(apps41.+\.sbn)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(cnu41.+\.sbn)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(cvm41sccp.+\.sbn)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(dsp41.+\.sbn)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(jar41sccp.+\.sbn)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(SCCP41.+\.loads)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(term41.+\.loads)$ /firmware/7941_7961/$1 last; + rewrite ^/firmware/(term61.+\.loads)$ /firmware/7941_7961/$1 last; # 7942_7962 firmware (java-based) - rewrite ^/firmware/(apps42.+\.sbn)$ /firmware/7942/$1 last; - rewrite ^/firmware/(cnu42.+\.sbn)$ /firmware/7942/$1 last; - rewrite ^/firmware/(cvm42sccp.+\.sbn)$ /firmware/7942/$1 last; - rewrite ^/firmware/(dsp42.+\.sbn)$ /firmware/7942/$1 last; - rewrite ^/firmware/(jar42sccp.+\.sbn)$ /firmware/7942/$1 last; - rewrite ^/firmware/(SCCP42.+\.loads)$ /firmware/7942/$1 last; - rewrite ^/firmware/(term42.+\.loads)$ /firmware/7942/$1 last; - rewrite ^/firmware/(term62.+\.loads)$ /firmware/7942/$1 last; + rewrite ^/firmware/(apps42.+\.sbn)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(cnu42.+\.sbn)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(cvm42sccp.+\.sbn)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(dsp42.+\.sbn)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(jar42sccp.+\.sbn)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(SCCP42.+\.loads)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(term42.+\.loads)$ /firmware/7942_7962/$1 last; + rewrite ^/firmware/(term62.+\.loads)$ /firmware/7942_7962/$1 last; # 7945_7965 firmware (java-based) - rewrite ^/firmware/(apps45.+\.sbn)$ /firmware/7945/$1 last; - rewrite ^/firmware/(cnu45.+\.sbn)$ /firmware/7945/$1 last; - rewrite ^/firmware/(cvm45sccp.+\.sbn)$ /firmware/7945/$1 last; - rewrite ^/firmware/(dsp45.+\.sbn)$ /firmware/7945/$1 last; - rewrite ^/firmware/(jar45sccp.+\.sbn)$ /firmware/7945/$1 last; - rewrite ^/firmware/(SCCP45.+\.loads)$ /firmware/7945/$1 last; - rewrite ^/firmware/(term45.+\.loads)$ /firmware/7945/$1 last; - rewrite ^/firmware/(term65.+\.loads)$ /firmware/7945/$1 last; + rewrite ^/firmware/(apps45.+\.sbn)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(cnu45.+\.sbn)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(cvm45sccp.+\.sbn)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(dsp45.+\.sbn)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(jar45sccp.+\.sbn)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(SCCP45.+\.loads)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(term45.+\.loads)$ /firmware/7945_7965/$1 last; + rewrite ^/firmware/(term65.+\.loads)$ /firmware/7945_7965/$1 last; # 7970_7971 firmware (java-based) - rewrite ^/firmware/(apps70.+\.sbn)$ /firmware/7970/$1 last; - rewrite ^/firmware/(cnu70.+\.sbn)$ /firmware/7970/$1 last; - rewrite ^/firmware/(cvm70sccp.+\.sbn)$ /firmware/7970/$1 last; - rewrite ^/firmware/(dsp70.+\.sbn)$ /firmware/7970/$1 last; - rewrite ^/firmware/(jar70sccp.+\.sbn)$ /firmware/7970/$1 last; - rewrite ^/firmware/(SCCP70.+\.loads)$ /firmware/7970/$1 last; - rewrite ^/firmware/(term70.+\.loads)$ /firmware/7970/$1 last; - rewrite ^/firmware/(term71.+\.loads)$ /firmware/7970/$1 last; + rewrite ^/firmware/(apps70.+\.sbn)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(cnu70.+\.sbn)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(cvm70sccp.+\.sbn)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(dsp70.+\.sbn)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(jar70sccp.+\.sbn)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(SCCP70.+\.loads)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(term70.+\.loads)$ /firmware/7970_7971/$1 last; + rewrite ^/firmware/(term71.+\.loads)$ /firmware/7970_7971/$1 last; # 7975 firmware (java-based) rewrite ^/firmware/(apps75.+\.sbn)$ /firmware/7975/$1 last; @@ -205,9 +205,15 @@ server { rewrite ^/firmware/(SCCP894x.+\.sgn)$ /firmware/894x/$1 last; rewrite ^/firmware/(SCCP894x.+\.loads)$ /firmware/894x/$1 last; - # ata186 / ata188 firmware (ancient) + # ata186 firmware (ancient) rewrite ^/firmware/(ATA030204SCCP090202A.zup)$ /firmware/ata186/$1 last; + # ata188 firmware (ancient) + rewrite ^/firmware/(ATA030204SCCP090202A.zup)$ /firmware/ata188/$1 last; + + # SPA50x + rewrite ^/firmware/(SPA504G-762.BIN)$ /firmware/spa50x/$1 last; + try_files $uri $uri/ =404; autoindex off; } diff --git a/etc/tftpd-hpa/rewrite.rules b/etc/tftpd-hpa/rewrite.rules index dd9b4b0..81c512f 100644 --- a/etc/tftpd-hpa/rewrite.rules +++ b/etc/tftpd-hpa/rewrite.rules @@ -166,18 +166,20 @@ ri ^(ATA030204SCCP090202A.zup)$ firmware/ata186/\1 # Sub-Directory Handling # settings -ri ^(.+\.cnf.xml)$ settings/\1 -ri ^\/(.+\-cnf.xml)$ settings/\1 -ri ^\/(SPA504G-cfg.xml)$ settings/\1 +ri ^(.+\.tlv)?$ settings/\1 +ri ^\/(.+\.tlv)?$ settings/\1 +ri ^((.+\.cnf.xml)(\.enc)?(\.sgn)?)$ settings/\1 +ri ^\/((.+\-cnf.xml)(\.enc)?(\.sgn)?)$ settings/\1 +ri ^\/((SPA504G-cfg.xml)(\.enc)?(\.sgn)?)$ settings/\1 # Keep firmware in a separate directory (optional) #ri ^(.+\.loads)$ firmware/\1 #ri ^(.+\.sbn)$ firmware/\1 # Keep locales in a separate directory (optional) -ri ^(.+)/(.+-sccp.jar)$ locales/languages/\1/\2 -ri ^(.+)/(.+-dictionary.xml)$ locales/languages/\1/\2 -ri ^(.+)/(.+-tones.xml)$ locales/countries/\1/\2 +ri ^(.+)\/(.+-sccp.jar)$ locales/languages/\1/\2 +ri ^(.+)\/(.+-dictionary.xml)$ locales/languages/\1/\2 +ri ^(.+)\/(.+-tones.xml)$ locales/countries/\1/\2 # Keep ring-tones in a separate directory (optional) ri ^([R|r]ing[L|l]ist)(\.xml|-wb\.xml)(\.sgn)?$ ringtones/ringlist.xml @@ -188,6 +190,8 @@ ri ^(.+)(\.raw|\.rwb)(\.sgn)?$ ringtones/\1\2\3 ri ^Desktops/(.+)/(List\.xml)(\.sgn)?$ wallpapers/\1/\2\3 ri ^Desktops/(.+)/(.+\.png)(\.sgn)?$ wallpapers/\1/\2\3 +ri ^authorized_keys$ settings/authorized_keys + # # Generic Rules # diff --git a/tools/certutils/COPYING b/tools/certutils/COPYING new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/tools/certutils/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/tools/certutils/TLV/Builder.pm b/tools/certutils/TLV/Builder.pm new file mode 100644 index 0000000..7e21178 --- /dev/null +++ b/tools/certutils/TLV/Builder.pm @@ -0,0 +1,76 @@ +#!/usr/bin/perl + +package TLV::Builder; + +use strict; +use parent qw/Exporter/; +use Carp qw/croak/; + +our $VERSION = '1.0'; + +sub new { + my $class = shift; + + my $self = { + content => undef, + index => 0 + }; + + return bless ($self, $class); +} + +sub next_tag { + my ($self, $tag); + + $self = shift; + $tag = shift; + + $self->{content} .= pack ('C', $tag); + $self->{index} += 1; + + return $self->{tag}; +} + +sub next_length { + my ($self, $length); + + $self = shift; + $length = shift; + + croak 'Length is 0' unless ($length); + + $self->{content} .= pack ('S>', $length); + $self->{index} += 2; +} + +sub next_value { + my ($self, $value); + + $self = shift; + $value = shift; + + $self->{content} .= $value; + $self->{index} += length $value; +} + +sub index { + my $self = shift; + return $self->{index}; +} + +sub length { + my ($self, $index, $length); + + $self = shift; + $index = shift; + $length = shift; + + substr ($self->{content}, $index, 2, pack ('S>', $length)); +} + +sub content { + my $self = shift; + return $self->{content}; +} + +1; diff --git a/tools/certutils/TLV/Parser.pm b/tools/certutils/TLV/Parser.pm new file mode 100644 index 0000000..5c27215 --- /dev/null +++ b/tools/certutils/TLV/Parser.pm @@ -0,0 +1,96 @@ +#!/usr/bin/perl + +package TLV::Parser; + +use strict; +use parent qw/Exporter/; +use Carp qw/croak/; + +our $VERSION = '1.0'; + +sub new { + my ($class, $content); + + $class = shift; + $content = shift; + + croak 'No content' unless (length $content); + + my $self = { + content => $content, + content_length => length $content, + index => 0, + tag => undef, + length => 0, + value => undef + }; + + return bless ($self, $class); +} + +sub next_tag { + my $self = shift; + + croak 'No space for tag' if ($self->{index} + 1 > $self->{content_length}); + + $self->{tag} = unpack ('C', substr ($self->{content}, $self->{index}, 1)); + $self->{index} += 1; + + return $self->{tag}; +} + +sub next_length { + my $self = shift; + + croak 'No space for length' if ($self->{index} + 2 > $self->{content_length}); + + $self->{length} = unpack ('S>', substr ($self->{content}, $self->{index}, 2)); + $self->{index} += 2; + + croak 'Length is 0' unless ($self->{length}); + + return $self->{length}; +} + +sub next_value { + my $self = shift; + + croak 'No space for value' if ($self->{index} + $self->{length} > $self->{content_length}); + + $self->{value} = substr ($self->{content}, $self->{index}, $self->{length}); + $self->{index} += $self->{length}; + + return $self->{value}; +} + +sub index { + my $self = shift; + return $self->{index}; +} + +sub tag { + my $self = shift; + return $self->{tag}; +} + +sub length { + my $self = shift; + return $self->{length}; +} + +sub value { + my $self = shift; + return $self->{value}; +} + +sub content { + my $self = shift; + return $self->{content}; +} + +sub done { + my $self = shift; + return $self->{index} == $self->{content_length}; +} + +1; diff --git a/tools/certutils/TLV/Tags.pm b/tools/certutils/TLV/Tags.pm new file mode 100644 index 0000000..a38504e --- /dev/null +++ b/tools/certutils/TLV/Tags.pm @@ -0,0 +1,74 @@ +#!/usr/bin/perl + +package TLV::Tags; + +use strict; +use parent qw/Exporter/; + +our $VERSION = '1.0'; + +our %EXPORT_TAGS = (header => [qw/HEADER_VERSION HEADER_LENGTH HEADER_SIGNER_ID HEADER_SIGNER_NAME HEADER_SERIAL_NUMBER + HEADER_CA_NAME HEADER_SIGNATURE_INFO HEADER_DIGEST_ALGORITHM + HEADER_SIGNATURE_ALGORITHM_INFO HEADER_SIGNATURE_ALGORITHM HEADER_SIGNATURE_MODULUS + HEADER_SIGNATURE HEADER_PADDING HEADER_FILENAME HEADER_TIMESTAMP/], + record => [qw/RECORD_LENGTH RECORD_DNS_NAME RECORD_SUBJECT_NAME RECORD_FUNCTION RECORD_ISSUER_NAME + RECORD_SERIAL_NUMBER RECORD_PUBLIC_KEY RECORD_SIGNATURE RECORD_CERTIFICATE + RECORD_IP_ADDRESS RECORD_CERTIFICATE_HASH RECORD_HASH_ALGORITHM/], + digest => [qw/DIGEST_SHA1 DIGEST_SHA256 DIGEST_SHA384 DIGEST_SHA512/], + function => [qw/FUNCTION_SAST FUNCTION_CCM FUNCTION_CCM_TFTP FUNCTION_TFTP FUNCTION_CAPF FUNCTION_SRST + FUNCTION_HTTPS FUNCTION_TVS/]); + +our @EXPORT_OK = (@{$EXPORT_TAGS{header}}, @{$EXPORT_TAGS{record}}, @{$EXPORT_TAGS{digest}}, @{$EXPORT_TAGS{function}}); + +use constant { + HEADER_VERSION => 1, + HEADER_LENGTH => 2, + HEADER_SIGNER_ID => 3, + HEADER_SIGNER_NAME => 4, + HEADER_SERIAL_NUMBER => 5, + HEADER_CA_NAME => 6, + HEADER_SIGNATURE_INFO => 7, + HEADER_DIGEST_ALGORITHM => 8, + HEADER_SIGNATURE_ALGORITHM_INFO => 9, + HEADER_SIGNATURE_ALGORITHM => 10, + HEADER_SIGNATURE_MODULUS => 11, + HEADER_SIGNATURE => 12, + HEADER_PADDING => 13, + HEADER_FILENAME => 14, + HEADER_TIMESTAMP => 15 +}; + +use constant { + RECORD_LENGTH => 1, + RECORD_DNS_NAME => 2, + RECORD_SUBJECT_NAME => 3, + RECORD_FUNCTION => 4, + RECORD_ISSUER_NAME => 5, + RECORD_SERIAL_NUMBER => 6, + RECORD_PUBLIC_KEY => 7, + RECORD_SIGNATURE => 8, + RECORD_CERTIFICATE => 9, + RECORD_IP_ADDRESS => 10, + RECORD_CERTIFICATE_HASH => 11, + RECORD_HASH_ALGORITHM => 12 +}; + +use constant { + DIGEST_SHA1 => 1, + DIGEST_SHA256 => 2, + DIGEST_SHA384 => 3, + DIGEST_SHA512 => 4 +}; + +use constant { + FUNCTION_SAST => 0, + FUNCTION_CCM => 1, + FUNCTION_CCM_TFTP => 2, + FUNCTION_TFTP => 3, + FUNCTION_CAPF => 4, + FUNCTION_SRST => 5, + FUNCTION_HTTPS => 7, + FUNCTION_TVS => 21 +}; + +1; diff --git a/tools/certutils/certhash b/tools/certutils/certhash new file mode 100755 index 0000000..f9c18c4 --- /dev/null +++ b/tools/certutils/certhash @@ -0,0 +1,43 @@ +#!/usr/bin/perl +# +# Copyright (c) 2017 Gareth Palmer +# This program is free software, distributed under the terms of +# the GNU General Public License Version 2. + +use strict; +use POSIX qw/EXIT_FAILURE EXIT_SUCCESS/; +use English qw/-no_match_vars/; +use IO::File; +use Crypt::OpenSSL::X509 qw/FORMAT_ASN1 FORMAT_PEM/; +use Digest; + +eval { + my $certificate_file = shift; + die 'No certificate file specified' unless (length $certificate_file); + + my ($file, $content); + + unless ($file = IO::File->new ($certificate_file, '<:raw')) { + die 'Unable to read ' . $certificate_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($content, FORMAT_PEM); + die 'Unable to load record x509 certificate' unless ($x509); + + my $digest = Digest->new ('SHA-1'); + + $digest->add ($x509->as_string (FORMAT_ASN1)); + print $digest->b64digest, "\n"; +}; + +if (length $EVAL_ERROR) { + $EVAL_ERROR =~ s/ at \S+ line \d+\.//; + warn $EVAL_ERROR; + + exit EXIT_FAILURE; +} + +exit EXIT_SUCCESS; diff --git a/tools/certutils/gencert b/tools/certutils/gencert new file mode 100755 index 0000000..775184f --- /dev/null +++ b/tools/certutils/gencert @@ -0,0 +1,234 @@ +#!/bin/bash +# +# Copyright (c) 2017 Gareth Palmer +# This program is free software, distributed under the terms of +# the GNU General Public License Version 2. + +OPTIONS=$(getopt -n ${0##*/} -o "C:O:l:s:t:e:b:y:d:o:c:nh" \ + -l "common:,organization:,locality:,state:,country:,email:,bits:,years:,digest:,output:,cacert:,newca,help" -- "$@") + +if test $? -ne 0; then + echo "Try \`${0##*/} --help' for more information" + exit 1 +fi + +eval set -- "$OPTIONS" + +COMMON_NAME="" ORGANIZATION="" LOCALITY="" STATE="" COUNTRY="" EMAIL_ADDRESS="" BITS="2048" YEARS="10" DIGEST="sha256" CA_CERT="" OUTPUT_FILE="" NEW_CA=false + +while true; do + test -n "$1" || break + + case "$1" in + -C|--common) + COMMON_NAME="$2" + shift 2 + ;; + -O|--organization) + ORGANIZATION="$2" + shift 2 + ;; + -l|--locality) + LOCALITY="$2" + shift 2 + ;; + -s|--state) + STATE="$2" + shift 2 + ;; + -t|--country) + COUNTRY="$2" + shift 2 + ;; + -e|--email) + EMAIL_ADDRESS="$2" + shift 2 + ;; + -b|--bits) + BITS="$2" + shift 2 + + if [[ ! $BITS =~ ^[0-9]+$ || $BITS -lt 512 || $BITS -gt 4096 ]]; then + echo "Invalid --bits \`$BITS'" + exit 1 + fi + ;; + -y|--years) + YEARS="$2" + shift 2 + + if [[ ! $YEARS =~ ^[0-9]+$ || $YEARS -lt 1 ]]; then + echo "Invalid --years \`$YEARS'" + exit 1 + fi + ;; + -d|--digest) + DIGEST="${2,,[a-z]}" + shift 2 + + if [[ $DIGEST != +(sha1|sha256) ]]; then + echo "Invaid --digest \`$DIGEST'" + exit 1 + fi + ;; + -o|--output) + OUTPUT_FILE="$2" + shift 2 + ;; + -c|--cacert) + CA_CERT="$2" + shift 2 + + if ! test -f "$CA_CERT"; then + echo "CA certificate does not exist" + exit 1 + fi + ;; + -n|--newca) + NEW_CA=true + shift 1 + ;; + -h|--help) + echo "Usage: ${0##*/} [OPTIONS]" + echo "Generate and sign X509 certificates" + echo "" + echo " -C --common common name" + echo " -O --organization organization" + echo " -l --locality locality" + echo " -s --state state" + echo " -t --country country" + echo " -e --email
email address" + echo " -n --bits RSA key size (default 2048)" + echo " -y --years number of years to sign the certificate (default 10)" + echo " -d --digest message digest to use (sha1, sha256)" + echo " -o --output output file" + echo " -c --cacert CA certificate to use for signing" + echo " -n --newca generate a CA certificate instead" + echo " -h --help print this help and exit" + echo "" + + exit 0 + ;; + --) + shift 1 + break + ;; + esac +done + +if test -z "$COMMON_NAME"; then + echo "No common name specified" + exit 1 +fi + +SUBJECT="/commonName=$COMMON_NAME" + +if test -n "$ORGANIZATION"; then + SUBJECT+="/organizationName=$ORGANIZATION" +fi + +if test -n "$LOCALITY"; then + SUBJECT+="/localityName=$LOCALITY" +fi + +if test -n "$STATE"; then + SUBJECT+="/stateOrProvinceName=$STATE" +fi + +if test -n "$COUNTRY"; then + SUBJECT+="/countryName=$COUNTRY" +fi + +if test -n "$EMAIL_ADDRESS"; then + SUBJECT+="/emailAddress=$EMAIL_ADDRESS" +fi + +if test -z "$OUTPUT_FILE"; then + OUTPUT_FILE=$(echo "$COMMON_NAME" | sed -e "s/[^A-Za-z0-9\.\-]/_/g").pem +fi + +START_DATE=$(date +"%Y%m%d000000Z") +END_DATE=$(date -d "now + $YEARS years" +"%Y%m%d000000Z") + +TEMP_DIR=$(mktemp -d /tmp/gencert-XXXXXXXX) +test -n $TEMP_DIR || exit 1 + +trap "rm -rf $TEMP_DIR" EXIT +touch $TEMP_DIR/database.txt $TEMP_DIR/database.txt.attr + +SERIAL_NUMBER=$(hexdump -n 16 -v -e "1/1 \"%02X\"" /dev/urandom) +echo "$SERIAL_NUMBER" > $TEMP_DIR/serial.txt + +cat > $TEMP_DIR/openssl.cnf < /dev/null; then + echo "Error while generating RSA key" + exit 1 +fi + +if ! openssl req -config $TEMP_DIR/openssl.cnf -new -batch -$DIGEST -key $TEMP_DIR/key.pem -subj "$SUBJECT" \ + -out $TEMP_DIR/req.pem 2> /dev/null; then + echo "Error while creating signing request" + exit 1 +fi + +if $NEW_CA; then + if ! openssl ca -config $TEMP_DIR/openssl.cnf -selfsign -batch -startdate $START_DATE -enddate $END_DATE -md $DIGEST \ + -extensions req_extensions -keyfile $TEMP_DIR/key.pem -notext -in $TEMP_DIR/req.pem -out $TEMP_DIR/crt.pem 2> /dev/null; then + echo "Error while signing CA certificate" + exit 1 + fi + + cat $TEMP_DIR/key.pem $TEMP_DIR/crt.pem > $OUTPUT_FILE + echo "New CA certificate created. Certificate and private-key saved in $OUTPUT_FILE" +else + if test -z "$CA_CERT"; then + echo "No CA certificate specified" + exit 1 + fi + + if ! openssl ca -config $TEMP_DIR/openssl.cnf -batch -startdate $START_DATE -enddate $END_DATE -md $DIGEST -extensions ca_extensions \ + -keyfile $CA_CERT -cert $CA_CERT -notext -in $TEMP_DIR/req.pem -out $TEMP_DIR/crt.pem 2>/dev/null; then + echo "Error while signing certificate" + exit 1 + fi + + cat $TEMP_DIR/key.pem $TEMP_DIR/crt.pem > $OUTPUT_FILE + echo "New certificate signed by the CA. Certificate and private-key saved to $OUTPUT_FILE" +fi + +exit 0 diff --git a/tools/certutils/sgnfile b/tools/certutils/sgnfile new file mode 100755 index 0000000..873fc83 --- /dev/null +++ b/tools/certutils/sgnfile @@ -0,0 +1,384 @@ +#!/usr/bin/perl +# +# Copyright (c) 2017 Gareth Palmer +# This program is free software, distributed under the terms of +# the GNU General Public License Version 2. + +use strict; +use FindBin; +use lib $FindBin::RealBin; +use POSIX qw/EXIT_FAILURE EXIT_SUCCESS strftime/; +use English qw/-no_match_vars/; +use IO::File; +use Crypt::OpenSSL::RSA; +use Crypt::OpenSSL::X509 qw/FORMAT_ASN1 FORMAT_PEM/; +use Convert::ASN1; +use Math::BigInt; +use File::Basename qw/basename/; +use Getopt::Long qw//; +use TLV::Tags qw/:header :digest/; +use TLV::Parser; +use TLV::Builder; + +sub parse_sgn { + my ($sgn_file, $certificate_file); + + $sgn_file = shift; + $certificate_file = shift; + + my ($file, $content); + + unless ($file = IO::File->new ($certificate_file, '<:raw')) { + die 'Unable to read ' . $certificate_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($content, FORMAT_PEM); + die 'Unable to load certificate' unless ($x509); + + unless ($file = IO::File->new ($sgn_file, '<:raw')) { + die 'Unable to read ' . $sgn_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $parser = TLV::Parser->new ($content); + + # Header + die 'Not a version tag: ' . $parser->tag if ($parser->next_tag != HEADER_VERSION); + die 'Wrong version length: ' . $parser->length if ($parser->next_length != 2); + + my $version = join ('.', unpack ('CC', $parser->next_value)); + + die 'Not a header_length tag: ' . $parser->tag if ($parser->next_tag != HEADER_LENGTH); + die 'Wrong header_length length: ' . $parser->length if ($parser->next_length != 2); + + my $header_length = unpack ('S>', $parser->next_value); + + print 'Version: ', $version, "\n", + 'Header Length: ', $header_length, ' bytes', "\n"; + + my ($header_digest_algorithm, $header_signature_index, $header_signature_length); + + while ($parser->index < $header_length) { + $parser->next_tag; + next if ($parser->tag == HEADER_PADDING); + $parser->next_length; + + if ($parser->tag == HEADER_SIGNER_ID) { + my $signer_id = $parser->length; + + print 'Signer ID: ', $signer_id, "\n"; + } elsif ($parser->tag == HEADER_SIGNER_NAME) { + my $signer_name = unpack ('Z*', $parser->next_value); + + print 'Signer Name: ', $signer_name, "\n"; + } elsif ($parser->tag == HEADER_SERIAL_NUMBER) { + my $serial_number = uc unpack ('H*', $parser->next_value); + + print 'Serial Number: ', join (':', $serial_number =~ m/(..)/g), "\n"; + } elsif ($parser->tag == HEADER_CA_NAME) { + my $ca_name = unpack ('Z*', $parser->next_value); + + print 'CA Name: ', $ca_name, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_INFO) { + my $signature_info = $parser->length; + + print 'Signature Info: ', $signature_info, "\n"; + } elsif ($parser->tag == HEADER_DIGEST_ALGORITHM) { + die 'Invalid digest_algorithm length: ' . $parser->length if ($parser->length != 1); + + my $digest_algorithm = unpack ('C', $parser->next_value); + + $header_digest_algorithm = $digest_algorithm; + + print 'Digest Algorithm: '; + + if ($digest_algorithm == DIGEST_SHA1) { + print 'SHA1'; + } elsif ($digest_algorithm == DIGEST_SHA256) { + print 'SHA256'; + } + + print "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_ALGORITHM_INFO) { + my $signature_algorithm_info = $parser->length; + + print 'Signature Algorithm Info: ', $signature_algorithm_info, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_ALGORITHM) { + die 'Invalid signature_algorithm length: ' . $parser->length if ($parser->length != 1); + + my $signature_algorithm = unpack ('C', $parser->next_value); + + print 'Signature Algorithm: ', $signature_algorithm, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_MODULUS) { + die 'Invalid signature_modulus length: ' . $parser->length if ($parser->length != 1); + + my $signature_modulus = unpack ('C', $parser->next_value); + + print 'Signature Modulus: ', $signature_modulus, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE) { + my $signature = $parser->next_value; + + # The removal index for the signature + $header_signature_index = $parser->index - $parser->length - 3; + $header_signature_length = $parser->length + 3; + + print 'Signature: ', length ($signature), ' bytes', "\n"; + } elsif ($parser->tag == HEADER_FILENAME) { + my $filename = unpack ('Z*', $parser->next_value); + + print 'Filename: ', $filename, "\n"; + } elsif ($parser->tag == HEADER_TIMESTAMP) { + die 'Invalid timestamp length: ' . $parser->length if ($parser->length != 4); + + my $timestamp = unpack ('L>', $parser->next_value); + + print 'Timestamp: ', strftime ('%a, %d %b %Y %H:%M:%S %z', localtime $timestamp), "\n"; + } else { + die 'Unknown tag: ' . $parser->tag . ' at index: ' . ($parser->index - 3); + } + } + + print "\n"; + + die 'No header digest algorithm' unless ($header_digest_algorithm); + die 'No header signature' unless ($header_signature_index); + + my $rsa = Crypt::OpenSSL::RSA->new_public_key ($x509->pubkey); + die 'Unable to parse RSA public key' unless ($rsa); + + if ($header_digest_algorithm == DIGEST_SHA1) { + $rsa->use_sha1_hash; + } elsif ($header_digest_algorithm == DIGEST_SHA256) { + $rsa->use_sha256_hash; + } else { + die 'Unknown header_digest_algorithm: ' . $header_digest_algorithm; + } + + $content = $parser->content; + my $signature = substr ($content, $header_signature_index + 3, $header_signature_length - 3); + + # Remove the signature block + substr ($content, $header_signature_index, $header_signature_length, ''); + + if ($rsa->verify ($content, $signature)) { + print 'Valid signature', "\n"; + } else { + print 'Invalid signature', "\n"; + } +} + +sub build_sgn { + my ($content_file, $certificate_file, $digest_algorithm, $filename); + + $content_file = shift; + $certificate_file = shift; + $digest_algorithm = shift; + $filename = shift; + + my ($file, $content); + + unless ($file = IO::File->new ($certificate_file, '<:raw')) { + die 'Unable to read ' . $certificate_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($content, FORMAT_PEM); + die 'Unable to load header certificate' unless ($x509); + + my $rsa = Crypt::OpenSSL::RSA->new_private_key ($content); + die 'Unable to load header private key' unless ($rsa); + + if ($digest_algorithm eq 'SHA1') { + $rsa->use_sha1_hash; + } elsif ($digest_algorithm eq 'SHA256') { + $rsa->use_sha256_hash; + } else { + die 'Unknown digest_algorithm: ' . $digest_algorithm; + } + + my $builder = TLV::Builder->new; + my $header_signature_index; + + do { + # Header + $builder->next_tag (HEADER_VERSION); + $builder->next_length (2); + $builder->next_value (pack ('CC', 1, 2)); + + $builder->next_tag (HEADER_LENGTH); + $builder->next_length (2); + $builder->next_value (pack ('S>', 0)); + + (my $signer_name = $x509->subject) =~ s/, /;/g; + (my $ca_name = $x509->issuer) =~ s/, /;/g; + my $serial_number = pack ('H*', $x509->serial); + + # Combined TLV length for signer_name, serial_number and ca_name + my $signer_id = 3 + length ($signer_name) + 1 + 3 + length ($serial_number) + 3 + length ($ca_name) + 1; + + $builder->next_tag (HEADER_SIGNER_ID); + $builder->next_length ($signer_id); + + $builder->next_tag (HEADER_SIGNER_NAME); + $builder->next_length (length ($signer_name) + 1); + $builder->next_value (pack ('Z*', $signer_name)); + + $builder->next_tag (HEADER_SERIAL_NUMBER); + $builder->next_length (length $serial_number); + $builder->next_value ($serial_number); + + $builder->next_tag (HEADER_CA_NAME); + $builder->next_length (length ($ca_name) + 1); + $builder->next_value (pack ('Z*', $ca_name)); + + $builder->next_tag (HEADER_SIGNATURE_INFO); + $builder->next_length (15); # Unknown + + $builder->next_tag (HEADER_DIGEST_ALGORITHM); + $builder->next_length (1); + $builder->next_value (pack ('C', do { + if ($digest_algorithm eq 'SHA1') { + DIGEST_SHA1; + } elsif ($digest_algorithm eq 'SHA256') { + DIGEST_SHA256; + } else { + die 'Unknown digest algorithm: ' . $digest_algorithm; + } + })); + + $builder->next_tag (HEADER_SIGNATURE_ALGORITHM_INFO); + $builder->next_length (8); # Unknown + + $builder->next_tag (HEADER_SIGNATURE_ALGORITHM); + $builder->next_length (1); + $builder->next_value (pack ('C', 0)); # Unknown + + my $signature_modulus; + + if ($rsa->size == 64) { + $signature_modulus = 0; + } elsif ($rsa->size == 128) { + $signature_modulus = 1; + } elsif ($rsa->size == 256) { + $signature_modulus = 2; + } elsif ($rsa->size == 512) { + $signature_modulus = 3; + } else { + die 'Unsupported RSA key size: ' . $rsa->size; + } + + $builder->next_tag (HEADER_SIGNATURE_MODULUS); + $builder->next_length (1); + $builder->next_value (pack ('C', $signature_modulus)); + + # The insertion index of the signature + $header_signature_index = $builder->index; + + $builder->next_tag (HEADER_FILENAME); + $builder->next_length (length ($filename) + 1); + $builder->next_value (pack ('Z*', $filename)); + + $builder->next_tag (HEADER_TIMESTAMP); + $builder->next_length (4); + $builder->next_value (pack ('L>', time)); + + # Header must be padded to 32-bit boundary + while (($builder->index + 3 + $rsa->size) % 4) { + $builder->next_tag (HEADER_PADDING); + } + + # Signed content includes the length of the signature block + $builder->length (8, $builder->index + 3 + $rsa->size); + }; + + unless ($file = IO::File->new ($content_file, '<:raw')) { + die 'Unable to read ' . $content_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + $builder->next_value ($content); + + $content = $builder->content; + die 'Unable to sign content' unless (my $signature = $rsa->sign ($content)); + + # Insert signature into content + substr ($content, $header_signature_index, 0, pack ('CS>a*', HEADER_SIGNATURE, $rsa->size, $signature)); + + my $sgn_file = $content_file . '.sgn'; + + unless ($file = IO::File->new ($sgn_file, '>:raw')) { + die 'Unable to write ' . $sgn_file . ': ' . $OS_ERROR; + } + + $file->print ($content); + $file->close; + + print 'Built ', $sgn_file, "\n"; +} + +eval { + my ($mode, $content_file, $sgn_file, $certificate_file, $digest_algorithm, $filename, $show_help); + + my $getopt = Getopt::Long::Parser->new; + + $getopt->configure (qw/no_ignore_case/); + + unless ($getopt->getoptions ('p|parse' => sub {shift; $mode = 'parse'}, + 'b|build' => sub {shift; $mode = 'build'}, + 'c|certificate=s' => sub {shift; $certificate_file = shift}, + 'd|digest=s' => sub {shift; $digest_algorithm = uc shift}, + 'F|filename=s' => sub {shift; $filename = shift}, + 'h|help' => sub {shift; $show_help = shift})) { + die 'Error parsing options'; + } + + if ($show_help) { + print 'Usage: ', basename ($PROGRAM_NAME), ' [OPTIONS]', "\n", + 'Parse or build a .sgn file', "\n", + "\n", + ' -p --parse parse a .sgn file', "\n", + ' -b --build build a .sgn file', "\n", + ' -c --certificate certificate to use for verifying or signing', "\n", + ' -d --digest signature digest (sha1, sha256)', "\n", + ' -F --filename header filename in built .sgn file (optional)', "\n", + ' -h --help print this help and exit', "\n", + "\n"; + + return; + } + + die 'No verifying/signing certificate file specified' unless (length $certificate_file); + + if ($mode eq 'parse') { + die 'No .sgn file specified' unless (length ($sgn_file = shift)); + + parse_sgn ($sgn_file, $certificate_file); + } elsif ($mode eq 'build') { + die 'No file specified' unless (length ($content_file = shift)); + + $digest_algorithm = 'SHA1' unless (length $digest_algorithm); + $filename = basename ($content_file) . '.sgn' unless (length $filename); + + build_sgn ($content_file, $certificate_file, $digest_algorithm, $filename); + } else { + die 'No mode specified'; + } +}; + +if (length $EVAL_ERROR) { + $EVAL_ERROR =~ s/ at \S+ line \d+\.//; + warn $EVAL_ERROR; + + exit EXIT_FAILURE; +} + +exit EXIT_SUCCESS; diff --git a/tools/certutils/stripsgn b/tools/certutils/stripsgn new file mode 100755 index 0000000..541ed7d --- /dev/null +++ b/tools/certutils/stripsgn @@ -0,0 +1,73 @@ +#!/usr/bin/perl +# +# Copyright (c) 2017 Gareth Palmer +# This program is free software, distributed under the terms of +# the GNU General Public License Version 2. + +use strict; +use POSIX qw/EXIT_FAILURE EXIT_SUCCESS/; +use English qw/-no_match_vars/; +use IO::File qw/SEEK_SET/; + +eval { + my $sgn_file = shift; + die 'No .sgn file specified' unless (length $sgn_file); + + (my $content_file = $sgn_file) =~ s/\.sgn$//; + + my $input_file; + + unless ($input_file = IO::File->new ($sgn_file, '<:raw')) { + die 'Unable to read ' .$sgn_file . ' :' . $OS_ERROR; + } + + my $content; + + die 'Unable to read header: ' . $OS_ERROR if ($input_file->read ($content, 10) != 10); + + my ($tag, $length, $index); + + $index = 0; + + ($tag, $length) = unpack ('CS>', substr ($content, $index, 3)); + $index += 3; + + die 'Not a version tag: ' . $tag if ($tag != 1); + die 'Wrong version length: ' . $length if ($length != 2); + + my $version = join ('.', unpack ('CC', substr ($content, $index, $length))); + $index += $length; + + ($tag, $length) = unpack ('CS>', substr ($content, $index, 3)); + $index += 3; + + die 'Not a header_length tag: ' . $tag if ($tag != 2); + die 'Wrong header_length length: ' . $length if ($length != 2); + + my $header_length = unpack ('S>', substr ($content, $index, $length)); + $index += $length; + + die 'Unable to seek: ' . $OS_ERROR unless ($input_file->seek ($header_length, SEEK_SET)); + + my $output_file; + + unless ($output_file = IO::File->new ($content_file, '>:raw')) { + die 'Unable to write ' . $content_file . ': ' . $OS_ERROR; + } + + while ($input_file->read ($content, 4096)) { + $output_file->write ($content); + } + + $input_file->close; + $output_file->close; +}; + +if (length $EVAL_ERROR) { + $EVAL_ERROR =~ s/ at \S+ line \d+\.//; + warn $EVAL_ERROR; + + exit EXIT_FAILURE; +} + +exit EXIT_SUCCESS; diff --git a/tools/certutils/tlvfile b/tools/certutils/tlvfile new file mode 100755 index 0000000..80fc353 --- /dev/null +++ b/tools/certutils/tlvfile @@ -0,0 +1,570 @@ +#!/usr/bin/perl +# +# Copyright (c) 2017 Gareth Palmer +# This program is free software, distributed under the terms of +# the GNU General Public License Version 2. + +use strict; +use FindBin; +use lib $FindBin::RealBin; +use POSIX qw/EXIT_FAILURE EXIT_SUCCESS strftime/; +use English qw/-no_match_vars/; +use IO::File; +use Crypt::OpenSSL::RSA; +use Crypt::OpenSSL::X509 qw/FORMAT_ASN1 FORMAT_PEM/; +use Convert::ASN1; +use Math::BigInt; +use File::Basename qw/basename/; +use Getopt::Long qw//; +use TLV::Tags qw/:header :digest :record :function/; +use TLV::Parser; +use TLV::Builder; + +sub parse_tlv { + my $tlv_file = shift; + + my ($file, $content); + + unless ($file = IO::File->new ($tlv_file, '<:raw')) { + die 'Unable to read ' . $tlv_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $parser = TLV::Parser->new ($content); + + # Header + die 'Not a version tag: ' . $parser->tag if ($parser->next_tag != HEADER_VERSION); + die 'Wrong version length: ' . $parser->length if ($parser->next_length != 2); + + my $version = join ('.', unpack ('CC', $parser->next_value)); + + die 'Not a header_length tag: ' . $parser->tag if ($parser->next_tag != HEADER_LENGTH); + die 'Wrong header_length length: ' . $parser->length if ($parser->next_length != 2); + + my $header_length = unpack ('S>', $parser->next_value); + + print 'Version: ', $version, "\n", + 'Header Length: ', $header_length, ' bytes', "\n"; + + my ($header_serial_number, $header_digest_algorithm, $header_signature_index, $header_signature_length); + + while ($parser->index < $header_length) { + $parser->next_tag; + next if ($parser->tag == HEADER_PADDING); + $parser->next_length; + + if ($parser->tag == HEADER_SIGNER_ID) { + my $signer_id = $parser->length; + + print 'Signer ID: ', $signer_id, "\n"; + } elsif ($parser->tag == HEADER_SIGNER_NAME) { + my $signer_name = unpack ('Z*', $parser->next_value); + + print 'Signer Name: ', $signer_name, "\n"; + } elsif ($parser->tag == HEADER_SERIAL_NUMBER) { + my $serial_number = uc unpack ('H*', $parser->next_value); + + # Used to locate the signing certificate record + $header_serial_number = $serial_number; + + print 'Serial Number: ', join (':', $serial_number =~ m/(..)/g), "\n"; + } elsif ($parser->tag == HEADER_CA_NAME) { + my $ca_name = unpack ('Z*', $parser->next_value); + + print 'CA Name: ', $ca_name, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_INFO) { + my $signature_info = $parser->length; + + print 'Signature Info: ', $signature_info, "\n"; + } elsif ($parser->tag == HEADER_DIGEST_ALGORITHM) { + die 'Invalid digest_algorithm length: ' . $parser->length if ($parser->length != 1); + + my $digest_algorithm = unpack ('C', $parser->next_value); + + $header_digest_algorithm = $digest_algorithm; + + print 'Digest Algorithm: '; + + if ($digest_algorithm == DIGEST_SHA1) { + print 'SHA1'; + } elsif ($digest_algorithm == DIGEST_SHA256) { + print 'SHA256'; + } + + print "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_ALGORITHM_INFO) { + my $signature_algorithm_info = $parser->length; + + print 'Signature Algorithm Info: ', $signature_algorithm_info, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_ALGORITHM) { + die 'Invalid signature_algorithm length: ' . $parser->length if ($parser->length != 1); + + my $signature_algorithm = unpack ('C', $parser->next_value); + + print 'Signature Algorithm: ', $signature_algorithm, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE_MODULUS) { + die 'Invalid signature_modulus length: ' . $parser->length if ($parser->length != 1); + + my $signature_modulus = unpack ('C', $parser->next_value); + + print 'Signature Modulus: ', $signature_modulus, "\n"; + } elsif ($parser->tag == HEADER_SIGNATURE) { + my $signature = $parser->next_value; + + # The removal index for the signature + $header_signature_index = $parser->index - $parser->length - 3; + $header_signature_length = $parser->length + 3; + + print 'Signature: ', length ($signature), ' bytes', "\n"; + } elsif ($parser->tag == HEADER_FILENAME) { + my $filename = unpack ('Z*', $parser->next_value); + + print 'Filename: ', $filename, "\n"; + } elsif ($parser->tag == HEADER_TIMESTAMP) { + die 'Invalid timestamp length: ' . $parser->length if ($parser->length != 4); + + my $timestamp = unpack ('L>', $parser->next_value); + + print 'Timestamp: ', strftime ('%a, %d %b %Y %H:%M:%S %z', localtime $timestamp), "\n"; + } else { + die 'Unknown tag: ' . $parser->tag . ' at index: ' . ($parser->index - 3); + } + } + + print "\n"; + + die 'No header serial number' unless (length $header_serial_number); + die 'No header digest algorithm' unless ($header_digest_algorithm); + die 'No header signature' unless ($header_signature_index); + + # Records + my ($record_number, $record_certificate); + + $record_number = 0; + + until ($parser->done) { + die 'Not a record_length tag: ' . $parser->tag if ($parser->next_tag != RECORD_LENGTH); + die 'Wrong record_length length: ' . $parser->length if ($parser->next_length != 2); + + my $record_length = unpack ('S>', $parser->next_value); + my $record_index = $parser->index - $parser->length - 3; + + $record_number++; + + print 'Record Number: ', $record_number, "\n", + 'Record Length: ', $record_length, ' bytes', "\n"; + + my ($record_function, $record_serial_number); + + while ($parser->index - $record_index < $record_length) { + $parser->next_tag; + $parser->next_length; + + if ($parser->tag == RECORD_DNS_NAME) { + my $dns_name = unpack ('Z*', $parser->next_value); + + print 'DNS Name: ', $dns_name, "\n"; + } elsif ($parser->tag == RECORD_SUBJECT_NAME) { + my $subject_name = unpack ('Z*', $parser->next_value); + + print 'Subject Name: ', $subject_name, "\n"; + } elsif ($parser->tag == RECORD_FUNCTION) { + my $function = unpack ('S>', $parser->next_value); + + $record_function = $function; + + print 'Function: '; + + if ($function == FUNCTION_SAST) { + print 'SAST'; + } elsif ($function == FUNCTION_CCM) { + print 'CCM'; + } elsif ($function == FUNCTION_CCM_TFTP) { + print 'CCM+TFTP'; + } elsif ($function == FUNCTION_TFTP) { + print 'TFTP'; + } elsif ($function == FUNCTION_CAPF) { + print 'CAPF'; + } elsif ($function == FUNCTION_SRST) { + print 'SRST'; + } elsif ($function == FUNCTION_HTTPS) { + print 'HTTPS'; + } elsif ($function == FUNCTION_TVS) { + print 'TVS'; + } + + print "\n"; + } elsif ($parser->tag == RECORD_ISSUER_NAME) { + my $issuer_name = unpack ('Z*', $parser->next_value); + + print 'Issuer Name: ', $issuer_name, "\n"; + } elsif ($parser->tag == RECORD_SERIAL_NUMBER) { + my $serial_number = uc unpack ('H*', $parser->next_value); + + $record_serial_number = $serial_number; + + print 'Serial Number: ', join (':', $serial_number =~ m/(..)/g), "\n"; + } elsif ($parser->tag == RECORD_PUBLIC_KEY) { + my $public_key = $parser->next_value; + + print 'Public Key: ', length ($public_key), ' bytes', "\n"; + } elsif ($parser->tag == RECORD_SIGNATURE) { + my $signature = $parser->next_value; + + print 'Signature: ', length ($signature), ' bytes', "\n"; + } elsif ($parser->tag == RECORD_CERTIFICATE) { + my $certificate = $parser->next_value; + + # Records that have the same serial number as the header and SAST function are used for signing + if ($record_serial_number eq $header_serial_number && defined ($record_function) && $record_function == FUNCTION_SAST) { + $record_certificate = $certificate; + } + + print 'Certificate: ', length ($certificate), ' bytes', "\n"; + } else { + die 'Invalid record tag: ' . $parser->tag . ' at index: ' . ($parser->index - 3); + } + } + + print "\n"; + } + + die 'No record certificate' unless (length $record_certificate); + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($record_certificate, FORMAT_ASN1); + die 'Unable to load record x509 certificate' unless ($x509); + + my $rsa = Crypt::OpenSSL::RSA->new_public_key ($x509->pubkey); + die 'Unable to parse RSA public key' unless ($rsa); + + if ($header_digest_algorithm == DIGEST_SHA1) { + $rsa->use_sha1_hash; + } elsif ($header_digest_algorithm == DIGEST_SHA256) { + $rsa->use_sha256_hash; + } else { + die 'Unknown header_digest_algorithm: ' . $header_digest_algorithm; + } + + $content = $parser->content; + my $signature = substr ($content, $header_signature_index + 3, $header_signature_length - 3); + + # Remove the signature block + substr ($content, $header_signature_index, $header_signature_length, ''); + + if ($rsa->verify ($content, $signature)) { + print 'Valid signature', "\n"; + } else { + print 'Invalid signature', "\n"; + } +} + +sub build_tlv { + my ($tlv_file, $certificate_file, $digest_algorithm, $filename, $records); + + $tlv_file = shift; + $certificate_file = shift; + $digest_algorithm = shift; + $filename = shift; + $records = shift; + + # Automatically grant the signing certificate the SAST function + unshift (@{$records}, {certificate_file => $certificate_file, function => 'SAST'}); + + my ($file, $content); + + unless ($file = IO::File->new ($certificate_file, '<:raw')) { + die 'Unable to read ' . $certificate_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($content, FORMAT_PEM); + die 'Unable to load header certificate' unless ($x509); + + my $rsa = Crypt::OpenSSL::RSA->new_private_key ($content); + die 'Unable to load header private key' unless ($rsa); + + if ($digest_algorithm eq 'SHA1') { + $rsa->use_sha1_hash; + } elsif ($digest_algorithm eq 'SHA256') { + $rsa->use_sha256_hash; + } else { + die 'Unknown digest_algorithm: ' . $digest_algorithm; + } + + my $builder = TLV::Builder->new; + my $header_signature_index; + + do { + # Header + $builder->next_tag (HEADER_VERSION); + $builder->next_length (2); + $builder->next_value (pack ('CC', 1, 2)); + + $builder->next_tag (HEADER_LENGTH); + $builder->next_length (2); + $builder->next_value (pack ('S>', 0)); + + (my $signer_name = $x509->subject) =~ s/, /;/g; + (my $ca_name = $x509->issuer) =~ s/, /;/g; + my $serial_number = pack ('H*', $x509->serial); + + # Combined TLV length for signer_name, serial_number and ca_name + my $signer_id = 3 + length ($signer_name) + 1 + 3 + length ($serial_number) + 3 + length ($ca_name) + 1; + + $builder->next_tag (HEADER_SIGNER_ID); + $builder->next_length ($signer_id); + + $builder->next_tag (HEADER_SIGNER_NAME); + $builder->next_length (length ($signer_name) + 1); + $builder->next_value (pack ('Z*', $signer_name)); + + $builder->next_tag (HEADER_SERIAL_NUMBER); + $builder->next_length (length $serial_number); + $builder->next_value ($serial_number); + + $builder->next_tag (HEADER_CA_NAME); + $builder->next_length (length ($ca_name) + 1); + $builder->next_value (pack ('Z*', $ca_name)); + + $builder->next_tag (HEADER_SIGNATURE_INFO); + $builder->next_length (15); # Unknown + + $builder->next_tag (HEADER_DIGEST_ALGORITHM); + $builder->next_length (1); + $builder->next_value (pack ('C', do { + if ($digest_algorithm eq 'SHA1') { + DIGEST_SHA1; + } elsif ($digest_algorithm eq 'SHA256') { + DIGEST_SHA256; + } else { + die 'Unknown digest algorithm: ' . $digest_algorithm; + } + })); + + $builder->next_tag (HEADER_SIGNATURE_ALGORITHM_INFO); + $builder->next_length (8); # Unknown + + $builder->next_tag (HEADER_SIGNATURE_ALGORITHM); + $builder->next_length (1); + $builder->next_value (pack ('C', 0)); # Unknown + + my $signature_modulus; + + if ($rsa->size == 64) { + $signature_modulus = 0; + } elsif ($rsa->size == 128) { + $signature_modulus = 1; + } elsif ($rsa->size == 256) { + $signature_modulus = 2; + } elsif ($rsa->size == 512) { + $signature_modulus = 3; + } else { + die 'Unsupported RSA key size: ' . $rsa->size; + } + + $builder->next_tag (HEADER_SIGNATURE_MODULUS); + $builder->next_length (1); + $builder->next_value (pack ('C', $signature_modulus)); + + # The insertion index of the signature + $header_signature_index = $builder->index; + + $builder->next_tag (HEADER_FILENAME); + $builder->next_length (length ($filename) + 1); + $builder->next_value (pack ('Z*', $filename)); + + $builder->next_tag (HEADER_TIMESTAMP); + $builder->next_length (4); + $builder->next_value (pack ('L>', time)); + + # Header must be padded to 32-bit boundary + while (($builder->index + 3 + $rsa->size) % 4) { + $builder->next_tag (HEADER_PADDING); + } + + # Signed content includes the length of the signature block + $builder->length (8, $builder->index + 3 + $rsa->size); + }; + + # Records + foreach my $record (@{$records}) { + my ($certificate_file, $function) = ($record->{certificate_file}, $record->{function}); + + my ($file, $content); + + unless ($file = IO::File->new ($certificate_file, '<:raw')) { + die 'Unable to read ' . $certificate_file . ': ' . $OS_ERROR; + } + + $content = do {local $INPUT_RECORD_SEPARATOR; $file->getline}; + $file->close; + + my $x509 = Crypt::OpenSSL::X509->new_from_string ($content, FORMAT_PEM); + die 'Unable to load record certificate' unless ($x509); + + my $record_index = $builder->index; + + $builder->next_tag (RECORD_LENGTH); + $builder->next_length (2); + $builder->next_value (pack ('S>', 0)); + + unless ($function eq 'SAST') { + (my $dns_name) = ($x509->subject =~ m/\bCN=([^,]+)/); + + # DNS name is included even if empty + $builder->next_tag (RECORD_DNS_NAME); + $builder->next_length (length ($dns_name) + 1); + $builder->next_value (pack ('Z*', $dns_name)); + } + + (my $subject_name = $x509->subject) =~ s/, /;/g; + + $builder->next_tag (RECORD_SUBJECT_NAME); + $builder->next_length (length ($subject_name) + 1); + $builder->next_value (pack ('Z*', $subject_name)); + + $builder->next_tag (RECORD_FUNCTION); + $builder->next_length (2); + $builder->next_value (pack ('S>', do { + if ($function eq 'SAST') { + FUNCTION_SAST; + } elsif ($function eq 'CCM') { + FUNCTION_CCM; + } elsif ($function eq 'CCM+TFTP') { + FUNCTION_CCM_TFTP; + } elsif ($function eq 'TFTP') { + FUNCTION_TFTP; + } elsif ($function eq 'CAPF') { + FUNCTION_CAPF; + } elsif ($function eq 'SRST') { + FUNCTION_SRST; + } elsif ($function eq 'HTTPS') { + FUNCTION_HTTPS; + } elsif ($function eq 'TVS') { + FUNCTION_TVS; + } else { + die 'Unknown record function: ' . $function; + }; + })); + + (my $issuer_name = $x509->issuer) =~ s/, /;/g; + + $builder->next_tag (RECORD_ISSUER_NAME); + $builder->next_length (length ($issuer_name) + 1); + $builder->next_value (pack ('Z*', $issuer_name)); + + my $serial_number = pack ('H*', $x509->serial); + + $builder->next_tag (RECORD_SERIAL_NUMBER); + $builder->next_length (length $serial_number); + $builder->next_value ($serial_number); + + my $asn1 = Convert::ASN1->new; + + $asn1->prepare ('SEQUENCE { modulus INTEGER, exponent INTEGER }'); + + my $public_key = $asn1->encode ({modulus => Math::BigInt->from_hex ($x509->modulus), + exponent => hex $x509->exponent}); + + $builder->next_tag (RECORD_PUBLIC_KEY); + $builder->next_length (length $public_key); + $builder->next_value ($public_key); + + my $signature = pack ('H*', $x509->sig_print); + + $builder->next_tag (RECORD_SIGNATURE); + $builder->next_length (length $signature); + $builder->next_value ($signature); + + my $certificate = $x509->as_string (FORMAT_ASN1); + + $builder->next_tag (RECORD_CERTIFICATE); + $builder->next_length (length $certificate); + $builder->next_value ($certificate); + + my $record_length = $builder->index - $record_index; + + $builder->length ($record_index + 3, $record_length); + }; + + $content = $builder->content; + die 'Unable to sign content' unless (my $signature = $rsa->sign ($content)); + + # Insert signature into content + substr ($content, $header_signature_index, 0, pack ('CS>a*', HEADER_SIGNATURE, $rsa->size, $signature)); + + unless ($file = IO::File->new ($tlv_file, '>:raw')) { + die 'Unable to write ' . $tlv_file . ': ' . $OS_ERROR; + } + + $file->print ($content); + $file->close; + + print 'Built ', $tlv_file, "\n"; +} + +eval { + my ($mode, $tlv_file, $certificate_file, $digest_algorithm, $filename, $records, $record, $show_help); + + $records = []; + + my $getopt = Getopt::Long::Parser->new; + + $getopt->configure (qw/no_ignore_case/); + + unless ($getopt->getoptions ('p|parse' => sub {shift; $mode = 'parse'}, + 'b|build' => sub {shift; $mode = 'build'}, + 'c|certificate=s' => sub {shift; $certificate_file = shift}, + 'd|digest=s' => sub {shift; $digest_algorithm = uc shift}, + 'r|record=s' => sub {shift; push (@{$records}, $record = {certificate_file => shift})}, + 'f|function=s' => sub {shift; $record->{function} = uc shift if $record}, + 'F|filename=s' => sub {shift; $filename = shift}, + 'h|help' => sub {shift; $show_help = shift})) { + die 'Error parsing options'; + } + + if ($show_help) { + print 'Usage: ', basename ($PROGRAM_NAME), ' [OPTIONS]', "\n", + 'Parse or build a .tlv file', "\n", + "\n", + ' -p --parse parse a .tlv file', "\n", + ' -b --build build a .tlv file', "\n", + ' -c --certificate certificate to use for verifying or signing', "\n", + ' -d --digest signature digest (sha1, sha256)', "\n", + ' -F --filename header filename in built .tlv file (optional)', "\n", + ' -r --record additional record certificate', "\n", + ' -f --function record function (sast, ccm, ccm+tftp tftp, https)', "\n", + ' -h --help print this help and exit', "\n", + "\n"; + + return; + } + + die 'No .tlv file specified' unless (length ($tlv_file = shift)); + + if ($mode eq 'parse') { + parse_tlv ($tlv_file); + } elsif ($mode eq 'build') { + die 'No signing certificate file specified' unless (length $certificate_file); + + $digest_algorithm = 'SHA1' unless (length $digest_algorithm); + $filename = basename ($tlv_file) unless (length $filename); + + build_tlv ($tlv_file, $certificate_file, $digest_algorithm, $filename, $records); + } else { + die 'No mode specified'; + } +}; + +if (length $EVAL_ERROR) { + $EVAL_ERROR =~ s/ at \S+ line \d+\.//; + warn $EVAL_ERROR; + + exit EXIT_FAILURE; +} + +exit EXIT_SUCCESS;