pax_global_header00006660000000000000000000000064126420605070014514gustar00rootroot0000000000000052 comment=cb4e2d7f2dc9325083a5a1bec47049fd4caaf604 hash-slinger-2.7/000077500000000000000000000000001264206050700137505ustar00rootroot00000000000000hash-slinger-2.7/.gitignore000066400000000000000000000000141264206050700157330ustar00rootroot00000000000000*.pyc *.swp hash-slinger-2.7/BUGS000066400000000000000000000000061264206050700144270ustar00rootroot00000000000000none? hash-slinger-2.7/CHANGES000066400000000000000000000041151264206050700147440ustar00rootroot00000000000000v2.7 (Jan 2, 2015) - openpgpkey: Add --keyid option to select key on keyid [Paul] - openpgpkey: fix --rootanchor option handling [Ondřej Surý] - openpgpkey: print keyid as bind zone style comment [Carsten Strotmann] - sshfp: Ignore 4th column in known_hosts [Jean-Michel Nirgal Vourgère] - sshfp: Demote obsoleted dss/dsa keys - warn if requested [Paul] - tlsa: Add support for SNI, allow port 25 certs for local files [Dirk Stöcker] - tlsa: Support --starttls for imap, pop3, smtp and ftp [Dirk Stöcker] - Remove DLV which is being sunset [Paul] v2.6 (Jan 6, 2015)) - openpgpkey: Added --fetch option to fetch a public key from DNS [Paul] - openpgpkey: Update rrtype from private use to IANA allocation (#61) [Paul] - openpgpkey: Remove no longer needed --rrtype option [Paul] - openpgpkey: Ignore uft-8/iso-8859-1 encoding errors in keyring data [Paul] - openpgpkey: Add --uid option to override id check in received key data [Paul] - openpgpkey: fix 0x99 (') character problems in base64 [Paul] - openpgpkey: Fix OPENPGPKEY native base64 output to be correct [Paul] - sshfp: Support for RFC 6594 [Gerald Turner] - sshfp: Support for draft-moonesamy-sshfp-ed25519-01 [Gerald Turner] - tlsa: New option --rootkey and --dlvkey [Paul] - tlsa: Try to find rootkey in various locations in achor or key format [Paul] - tlsa: abort unsupported STARTTLS on port 25 (rhbz#1010276) [Paul] - ipseckey: new command for generating RFC-4025 IPSECKEY records [Paul] v2.5 (Jan 14, 2014) - Updated openpgpkey support for new draft-wouters-openpgpkey-02 [Paul] v2.4 (Jan 6, 2014) - add --rrtype and --rootanchor support, some cleanup, to openpgpkey [Paul] v2.3 (Dec 31, 2013) - Added openpgpkey support [Paul] v2.2 (June 24, 2013) - quiet (-q) is the new default, use -v to get verbose output [Paul] - tlsa: fix --ipv4/--ipv6 options. Assume both if none specified - tlsa: Usage 0 fix and M2Crypto path fix [Patrick] v2.1 (Sep 15, 2012) - Clarify that the license is GPLv2+ v2.0 (Aug 24, 2012) - Initial release of hash-slinger - Pulled in sshfp from the sshfp package - Pulled in swede as tlsa from github - Added tlsa man page hash-slinger-2.7/COPYING000066400000000000000000000432541264206050700150130ustar00rootroot00000000000000 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. hash-slinger-2.7/Makefile000066400000000000000000000013151264206050700154100ustar00rootroot00000000000000# # A basic Makefile # BIN = $(DESTDIR)/usr/bin MAN = $(DESTDIR)/usr/share/man/man1 all: man install: install -m 0755 -d $(BIN) install -m 0755 sshfp $(BIN) install -m 0755 tlsa $(BIN) install -m 0755 openpgpkey $(BIN) install -m 0755 ipseckey $(BIN) install -m 0755 -d $(MAN) install -m 0644 *.1 $(MAN) gzip $(MAN)/*.1 man: man-page man-page: sshfp.1 tlsa.1 openpgpkey.1 ipseckey.1 sshfp.1: sshfp.1.xml xmlto man sshfp.1.xml tlsa.1: tlsa.1.xml xmlto man tlsa.1.xml openpgpkey.1: openpgpkey.1.xml xmlto man openpgpkey.1.xml ipseckey.1: ipseckey.1.xml xmlto man ipseckey.1.xml clean: -rm -f sshfp.1 tsla.1 openpgpkey.1 dist-clean: @echo Nothing to dist-clean - This is a python script hash-slinger-2.7/README000066400000000000000000000023531264206050700146330ustar00rootroot00000000000000LICENSE: GPLv2+, see COPYING This package contains various tools to generate special DNS records sshfp Generate RFC-4255 SSHFP DNS records from known_hosts files or ssh-keyscan tlsa Generate RFC-6698 TLSA DNS records via TLS openpgpkey Generate draft-ietf-dane-openpgpkey-01 OPENPGPKEY DNS records using gpg ipseckey Generate RFC-4025 IPSECKEY DNS records on Libreswan IPsec servers Authors: Paul Wouters (sshfp, tlsa, openpgpkey, ipseckey) Pieter Lexis (tlsa) Contributors: Chrisopher Olah James Brown Patrick Uiterwijk Gerald Turner Ondřej Surý Jan Vcelak Dirk Stöcker REQUIREMENTS: python-dns http://www.pythondns.org/ python-gnupg http://pythonhosted.org/python-gnupg/ python-ipaddr python-argparse (for python < 2.7) M2Crypto http://chandlerproject.org/Projects/MeTooCrypto unbound-python http://www.unbound.net/ ssh-keygen from openssh gpg from gnupg NOTE: There is a another package called python-gnupg at https://github.com/isislovecruft/python-gnupg that is available on FreeBSD. This is NOT the same package and will not work. hash-slinger-2.7/debian/000077500000000000000000000000001264206050700151725ustar00rootroot00000000000000hash-slinger-2.7/debian/changelog000066400000000000000000000004751264206050700170520ustar00rootroot00000000000000hash-slinger (2.6-1) wheezy; urgency=low * hash-slinger This package is NOT an official Debian/Ubuntu package. Please do not file any Debian/Ubuntu bug reports for this package but contact if you have a problem. -- Paul Wouters > Thu, 1 Jan 2015 23:59:59 -0400 hash-slinger-2.7/debian/compat000066400000000000000000000000021264206050700163700ustar00rootroot000000000000007 hash-slinger-2.7/debian/control000066400000000000000000000015461264206050700166030ustar00rootroot00000000000000Source: hash-slinger Section: net Priority: optional Maintainer: Paul Wouters Build-Depends: debhelper (>= 7.0.50~), python-support (>= 0.5.3), xmlto Homepage: http://people.redhat.com/pwouters/hash-slinger/ Standards-Version: 3.8.4 Package: hash-slinger Architecture: all Depends: ${shlibs:Depends}, ${misc:Depends}, ${python:Depends}, python-dnspython, openssh-client, python-argparse, python-unbound, python-ipaddr, python-gnupg XB-Python-Version: ${python:Versions} Description: This pacakge contains various tools to generate special DNS records sshfp Generate RFC-4255 SSHFP DNS records from known_hosts files or ssh-keyscan tlsa Generate RFC-6698 TLSA DNS records via TLS openpgpkey Generate RFC-TBD OPENPGPKEY DNS records using gnupg and a local keychain ipseckey Generate RFC-4025 IPSECKEY DNS records from libreswan IPsec servers hash-slinger-2.7/debian/copyright000066400000000000000000000015451264206050700171320ustar00rootroot00000000000000Format-Specification: http://wiki.debian.org/Proposals/CopyrightFormat Original-Source: http://people.redhat.com/pwouters/hash-slinger/ Files: debian/* Copyright © 2007, 2008, 2009, 2010 Julien Valroff Copyright © 2011, 2013 Paul Wouters License: GPL-2 The Debian packaging information is under the GPL version 2 . On Debian systems, the complete text of the GNU General Public License can be found in file "/usr/share/common-licenses/GPL-2". Files: * Copyright: Copyright © 2013 License: GPL-2 This package 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 version 2 of the License. . On Debian systems, the complete text of the GNU General Public License can be found in file "/usr/share/common-licenses/GPL-2". hash-slinger-2.7/debian/dirs000066400000000000000000000000101264206050700160450ustar00rootroot00000000000000usr/bin hash-slinger-2.7/debian/rules000077500000000000000000000001361264206050700162520ustar00rootroot00000000000000#!/usr/bin/make -f # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 %: dh $@ hash-slinger-2.7/debian/source/000077500000000000000000000000001264206050700164725ustar00rootroot00000000000000hash-slinger-2.7/debian/source/format000066400000000000000000000000151264206050700177010ustar00rootroot000000000000003.0 (native) hash-slinger-2.7/docs/000077500000000000000000000000001264206050700147005ustar00rootroot00000000000000hash-slinger-2.7/docs/CHANGES.sshfp000066400000000000000000000060151264206050700170170ustar00rootroot00000000000000v1.2.2 (Sep 6, 2011) - Fix -4 / -6 flags [Chris] - Throw errors on stderr to improve pipe usage [Ludwig Nusse] - openSUSE package information on import error [Ludwig Nusse] - Fix nameserver by IP address (ldns workaround [Chris] - Fix case where AAAA is found but no IPv6 is available [Paul] v1.2.1 (April 25th, 2011) - Fix copyright information to clearly make it is all GPLv2+ [Paul] v1.2.0 (April 13th, 2011) - dane : Added the dane command (See IETF DANE working group) [Paul] - sshfp: Fix quiet for external commands [James Brown] - sshfp: Merged in subprocess changes [James Brown] - sshfp: Use optparse, some code refactoring [James Brown] - sshfp: Added -U UDP option [James Brown] - sshfp: Rename of some functions [James Brown] - sshfp: doclifted man page, generate when needed using xmlto [Paul] v1.1.6 (October 13th, 2010) - Fix quiet for external commands [James Brown] - Merged in subprocess changes [James Brown] - Use optparse, some code refactoring [James Brown] - Added -U UDP option [James Brown] - Rename of some functions [James Brown] v1.1.5 - Fixes for https://bugs.launchpad.net/ubuntu/+source/sshfp/+bug/355886 - Fix for sha Deprecation warning [Martin Jackson] - Fix for use of os.popen3 [Martin Jackson] - Sync debian/ with Debian (thanks) - Various small pylint fixes [Simon Deziel] v1.1.4 - Fixes to man page [Maximiliano Curia] - Fixes to Makefile for Debian [Maximiliano Curia] v1.1.3 - Moved trailing-dot option from -t to -d - Added -t / --type - Added -T / --timeout - Fixed printing of bogus blanc line at the end. - Use Makefile in Fedora spec file v1.1.2 - Added -p port option - Patch by andrew@lewman.com - Added Debian package [jacob] 'fakeroot debian/rules binary' - Fixed getopt order [paul] - Added a mailinglist: http://lists.xelerance.com/mailman/listinfo/sshfp/ v1.1.1 - Ignore hashed hostname entries in known_hosts files [paul] - Fix "sshfp -k -a" [paul] v1.1.0 - All SSHFP records were created badly using a sha1() on the uuencoded keyblow instead of the raw uudecoded keyblob. - Fixed getrecord -> getRecord call when using -a (AXFR) - Added a newline when -o is used, to make dnssigner happy v1.0.6 - Added man page v1.0.5 - Fixed Debian package pointer to be python-dnspython - Fixed trailing dot for ORIGIN entry when AXFR is used - Changed -d/--dns and -f/--knownhosts to -s/--scan and -k/--knownhosts [hugh daniel] - Add timestamp in named.conf comment syntax to axfr unless -q/--quiet is used. [paul] - Exclude localhost from AXFR since it leaks information about the host that ran sshfp [paul] - Moved files into git repository. anonymous git access at http://git.xelerance.com/ - Fix "sshfp -k hostname" where hostname is not a domainname's A record. v1.0.4 - Fixed option parsing [paul] - Hardened dns failures [patrick naubert] v1.0.3 - Public release of sshfp - Added fedora spec file for packaging v1.0.1 - Renamed knownhosts2sshfp to sshfp since it no longer reflects the function [paul] - Added ssh-keyscan option on suggestion of Jake Appelbaum [paul] v1.0.0 - Internal initial release hash-slinger-2.7/docs/README.swede000066400000000000000000000055511264206050700166740ustar00rootroot00000000000000 SWEDE - a tool to create and verify TLSA (DANE) records ================================================================================ Swede aims to provide a one-stop solutions to create and test TLSA records. LICENSE -------------------------------------------------------------------------------- swede is copyright Pieter Lexis and is licensed under the terms of the GNU General Public Licence version 2 or higher. DEPENDENCIES -------------------------------------------------------------------------------- - Python (>= 2.6) - python-{unbound, argparse, ipaddr, m2crypto} swede has been tested on Debian 6 (Squeeze) using the python-unbound package from squeeze-backports. FEATURES -------------------------------------------------------------------------------- - Creation of all 24 permutations of TLSA records - Output in generic and RFC format - Ability to load certificates from disk to create records from - Verify TLSA records 'in the field' with the certificates offered by the TLS service running on the server USAGE -------------------------------------------------------------------------------- See EXAMPLES below and try the following: swede --help swede create --help swede verify --help EXAMPLES -------------------------------------------------------------------------------- swede create --usage 1 --output rfc www.os3.nl swede --insecure create --usage 0 mail.google.com swede verify -p 1516 dane.kiev.practicum.os3.nl swede verify ulthar.us TODO -------------------------------------------------------------------------------- - Create and verify should check the CN in the Subject of the certificate - The verification for usage 2 is _VERY_ naive - Creation tool that does an AXFR for a full zone, collects all hostnames, gets the certificates (or the CA certificate from the commandline) and creates all TLSA records. - Test certificates (other than using the functions in M2Crypto) when no chain is presented during the TLS session - Manpage KNOWN BUGS -------------------------------------------------------------------------------- - swede is mostly untested. - Not everything that can raise an exception is in a try/except block - No support for SRV record indirection (see Issue 28 of the DANE-WG) - No support for TLS/SSL over UDP or SCTP - No support for STARTTLS type protocols (only 'straight' SSL/TLS conections) hash-slinger-2.7/fedora/000077500000000000000000000000001264206050700152105ustar00rootroot00000000000000hash-slinger-2.7/fedora/hash-slinger.spec000066400000000000000000000033321264206050700204510ustar00rootroot00000000000000Summary: Generate and verify various DNS records such as SSHFP, TLSA and OPENPGPKEY Name: hash-slinger Version: 2.6 Release: 1%{?dist} License: GPLv2+ Url: http://people.redhat.com/pwouters/%{name}/ Source: http://people.redhat.com/pwouters/%{name}/%{name}-%{version}.tar.gz Group: Applications/Internet # Only to regenerate the man page, which is shipped per default # Buildrequires: xmlto Requires: python-dns, python-argparse, unbound-python, python-ipaddr, python-gnupg >= 0.3.5-2 Requires: openssh-clients >= 4, m2crypto BuildArch: noarch Obsoletes: sshfp < 2.0 Provides: sshfp = %{version} %description This package contains various tools to generate special DNS records: sshfp Generate RFC-4255 SSHFP DNS records from known_hosts or ssh-keyscan tlsa Generate RFC-6698 TLSA DNS records via TLS openpgpkey Generate RFC- OPENPGPKEY DNS records ipseckey Generate RFC-4025 IPSECKEY DNS records on Libreswan IPsec servers This package has incorporated the old 'sshfp' and 'swede' commands/packages %prep %setup -q %build make all %install rm -rf ${RPM_BUILD_ROOT} make DESTDIR=${RPM_BUILD_ROOT} install %clean rm -rf ${RPM_BUILD_ROOT} %files %doc BUGS CHANGES README COPYING %{_bindir}/* %doc %{_mandir}/man1/* %changelog * Mon Jan 6 2014 Paul Wouters - 2.4-1 - Updated to 2.4 which updates OPENPGPKEY support * Tue Dec 31 2013 Paul Wouters - 2.3-1 - Updated to 2.3 which adds support for OPENPGPKEY * Mon Jun 24 2013 Paul Wouters - 2.2-1 - New version * Sat Sep 15 2012 Paul Wouters - 2.1-1 - Updated COPYING to properly reflect GPLv2 "or later" * Fri Aug 24 2012 Paul Wouters - 2.0-1 - Initial package hash-slinger-2.7/ipseckey000077500000000000000000000036561264206050700155240ustar00rootroot00000000000000#!/usr/bin/python # Show IPSECKEY records generated by libreswan IPsec # might work on some versions of older openswan as well # # Copyright 2015 Paul Wouters # # 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. VERSION = "2.7" import os import sys import subprocess import optparse import base64 import time import hashlib ipsec = "/usr/sbin/ipsec" if not os.path.isfile(ipsec): ipsec = "/usr/local/sbin/ipsec" if not os.path.isfile(ipsec): print >> sys.stderr, "ipseckey: ipsec command not found (not a libreswan or openswan IPsec servers?)" sys.exit(1) def show_version(): print >> sys.stderr, "sshfp version: " + VERSION def main(): parser = optparse.OptionParser() parser.add_option("-v", "--version", action="store_true", dest="version", help="print version information and exit") (options, args) = parser.parse_args() if options.version: show_version() sys.exit(0) if os.geteuid() != 0: print >> sys.stderr, "ipseckey: root access is needed to read the IPsec NSS database for the public key" sys.exit(2) cmd = [ipsec, "showhostkey", "--ipseckey"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = process.communicate() print stdout if __name__ == "__main__": main() hash-slinger-2.7/ipseckey.1000066400000000000000000000065031264206050700156520ustar00rootroot00000000000000'\" t .\" Title: ipseckey .\" Author: [see the "AUTHORS" section] .\" Generator: DocBook XSL Stylesheets v1.78.1 .\" Date: January 5, 2015 .\" Manual: Internet / DNS .\" Source: Paul Wouters .\" Language: English .\" .TH "IPSECKEY" "1" "January 5, 2015" "Paul Wouters" "Internet / DNS" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" ipseckey \- Generate IPSECKEY records on libreswan IPsec servers .SH "SYNTAX" .PP ipseckey .SH "DESCRIPTION" .PP ipseckey generates RFC\-4025 IPSECKEY DNS records based on the public key of the IPsec server\&. Supported IPsec software is libreswan and some versions of openswan (depending on its implementation of showhostkey)\&. The record is displayed will have the label of the hostname\&. This can be manually changed\&. .PP (TODO: allow specifying \-\-hostname and allow \-\-reverse for creating in\-addr\&.arpa\&. entries) .SH "OPTIONS" .PP \fB\-h / \-\-help\fR .RS 4 Output help information and exit\&. .RE .PP \fB\-v / \-\-version\fR .RS 4 Output version information and exit\&. .RE .SH "FILES" .PP The NSS IPsec database in /etc/ipsec\&.d/*\&.db or for older openswan without NSS /etc/ipsec\&.secrets .SH "REQUIREMENTS" .PP ipseckey MUST be run on the IPsec gateway itself because unlike TLS, IPsec servers do not present their public RSA key any client\&. Currently, only libreswan IPsec is supported (\m[blue]\fBhttps://libreswan\&.org\fR\m[]) although some versions of openswan might work as well\&. Root access is needed because the public key is pulled from /etc/ipsec\&.secrets which can contain secrets and is therefor only readable by root (even though with libreswan, ipsec\&.secrets does not contain the any private RSA keys) .SH "BUGS" .PP Some other IPsec software is not yet supported .SH "SEE ALSO" .PP \fBipsec_showhostkey\fR(8) and RFC\-4025 .SH "AUTHORS" .PP Paul Wouters .SH "COPYRIGHT" .PP Copyright 2015 Paul Wouters .PP 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\&. See <\m[blue]\fBhttp://www\&.fsf\&.org/copyleft/gpl\&.txt\fR\m[]>\&. .PP 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 (file COPYING in the distribution) for more details\&. hash-slinger-2.7/ipseckey.1.xml000066400000000000000000000071251264206050700164520ustar00rootroot00000000000000 January 5, 2015 ipseckey 1 January 5, 2015 Paul Wouters Internet / DNS ipseckey Generate IPSECKEY records on libreswan IPsec servers SYNTAX ipseckey DESCRIPTION ipseckey generates RFC-4025 IPSECKEY DNS records based on the public key of the IPsec server. Supported IPsec software is libreswan and some versions of openswan (depending on its implementation of showhostkey). The record is displayed will have the label of the hostname. This can be manually changed. (TODO: allow specifying --hostname and allow --reverse for creating in-addr.arpa. entries) OPTIONS Output help information and exit. Output version information and exit. FILES The NSS IPsec database in /etc/ipsec.d/*.db or for older openswan without NSS /etc/ipsec.secrets REQUIREMENTS ipseckey MUST be run on the IPsec gateway itself because unlike TLS, IPsec servers do not present their public RSA key any client. Currently, only libreswan IPsec is supported (https://libreswan.org) although some versions of openswan might work as well. Root access is needed because the public key is pulled from /etc/ipsec.secrets which can contain secrets and is therefor only readable by root (even though with libreswan, ipsec.secrets does not contain the any private RSA keys) BUGS Some other IPsec software is not yet supported SEE ALSO ipsec_showhostkey8 and RFC-4025 AUTHORS Paul Wouters <pwouters@redhat.com> COPYRIGHT Copyright 2015 Paul Wouters 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. See <http://www.fsf.org/copyleft/gpl.txt>. 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 (file COPYING in the distribution) for more details. hash-slinger-2.7/openpgpkey000077500000000000000000000225651264206050700160710ustar00rootroot00000000000000#!/usr/bin/python # # openpgpkey: create OPENPGPKEY DNS record from a key in your keychain. # # Copyright 2012 - 2015 Paul Wouters # Copyright 2015 Dirk Stoecker # Copyright 2015 Jan Vcelak # Copyright 2015 Carsten Strotmann # Copyright 2015 Ondrej Sury # # 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. VERSION="2.7" OPENPGPKEY=61 import sys import os import gnupg import unbound import hashlib import tempfile import shutil global ctx def asctohex(s): empty = '' # I use this construct because I find ''.join() too dense return empty.join(['%02x' % ord(c) for c in s]) # the %02 pads when needed def createOPENPGPKEY(email, gpgdisk, keyid, output, debug): ekey64 = "".join(gpgdisk.export_keys(keyid,minimal=True, secret=False, armor=True).split("\n")[2:-3]) user,domain = email.lower().split("@") euser = sha256trunc(user) if output == "rfc" or output == "both": print "; keyid: %s" % keyid print "%s._openpgpkey.%s. IN OPENPGPKEY %s" % (euser, domain, ekey64) if output == "generic" or output == "both": if debug: print "Length for generic record is %s" % len(ekey) print "; keyid: %s" % keyid print "%s._openpgpkey.%s. IN TYPE61 \# %s %s" % (euser, domain, len(ekey), asctohex(ekey)) def sha256trunc(data): """Compute SHA2-256 hash truncated to 28 octets.""" return hashlib.sha256(data).hexdigest()[:56] def getOPENPGPKEY(email,insecure_ok): """This function queries for an OPENPGPKEY DNS Resource Record and compares it with the local gnupg keyring""" global ctx try: username, domainname = email.lower().split("@") except: sys.exit("Invalid email syntax") keyname = "%s._openpgpkey.%s"%(sha256trunc(username), domainname) status, result = ctx.resolve(keyname, OPENPGPKEY) if status == 0 and result.havedata: if not result.secure: if not insecure_ok: # The data is insecure and a secure lookup was requested sys.exit("Error: query data is not secured by DNSSEC - use --insecure to override") else: print >> sys.stderr, 'Warning: query data was not secured by DNSSEC.' # If we are here the data was either secure or insecure data is accepted return result.data.raw else: sys.exit('Unsuccesful lookup or no data returned for OPENPGPKEY (rrtype 61)') if __name__ == '__main__': import argparse # create the parser parser = argparse.ArgumentParser(description='Create and verify OPENPGPKEY records.', epilog='For bugs. see paul@nohats.ca') parser.add_argument('--verify','-v', action='store_true', help='Verify an OPENPGPKEY record, exit 0 when all records are matched, exit 1 on error.') parser.add_argument('--fetch','-f', action='store_true', help='Fetch an OPENPGPKEY record, and show it in ascii armor on stdout') parser.add_argument('--create','-c', action='store_true', help='Create an OPENPGKEY record') parser.add_argument('--version', action='version', version='openpgpkey version: %s'%VERSION, help='show version and exit') parser.add_argument('--insecure', action='store_true', default=False, help='Allow use of non-dnssec secured answers') parser.add_argument('--resolvconf', action='store', default='', help='Use a recursive resolver listed in a resolv.conf file (default: /etc/resolv.conf)') parser.add_argument('--rootanchor', action='store', default='', help='Location of the unbound compatible DNSSEC root.anchor (default: /var/lib/unbound/root.anchor)') parser.add_argument('email', metavar="email") parser.add_argument('--uid', action='store', default='', help='override the uid (email address) within the key') parser.add_argument('--keyid', action='store', default='', help='specify key by keyid') parser.add_argument('--debug', '-d', action='store_true', help='Print details plus the result of the validation') parser.add_argument('--quiet', '-q', action='store_true', help='Ignored for backwards compatibility') # default for now to generic - when more tools support OPENPGPKEY, switch the default to rfc parser.add_argument('--output', '-o', action='store', default='rfc', choices=['generic','rfc','both'], help='The type of output. Generic (RFC 3597, TYPE61), RFC (OPENPGPKEY) or both (default: %(default)s).') args = parser.parse_args() if args.verify and args.create: sys.exit("openpgpkey: must specify --create or --verify") if args.verify or args.fetch: # unbound setup, only for verify global ctx ctx = unbound.ub_ctx() resolvconf = "/etc/resolv.conf" rootanchor = None if args.rootanchor: if os.path.isfile(args.rootanchor): rootanchor = args.rootanchor else: print >> sys.stdout, 'openpgpkey: %s is not a file. Unable to use it as rootanchor' % args.rootanchor sys.exit(1) else: cauldron = ( "/var/lib/unbound/root.anchor", "/var/lib/unbound/root.key", "/etc/unbound/root.key" ) for root in cauldron: if os.path.isfile(root): rootanchor=root break if rootanchor: try: ctx.add_ta_file(rootanchor) except: unbound.ub_ctx_trustedkeys(ctx,rootanchor) if args.resolvconf: if os.path.isfile(args.resolvconf): resolvconf = args.resolvconf else: print >> sys.stdout, 'openpgpkey: %s is not a file. Unable to use it as resolv.conf' % args.resolvconf sys.exit(1) ctx.resolvconf(resolvconf) openpgpkeys = getOPENPGPKEY(args.email, args.insecure) if len(openpgpkeys) == 0: print >> sys.stderr, 'openpgpkey: Received nothing?' sys.exit(1) fdir = tempfile.mkdtemp(".gpg","openpgpkey-","/tmp/") gpgnet = gnupg.GPG(gnupghome=fdir) gpgnet.decode_errors = 'ignore' for openpgpkey in openpgpkeys: import_result = gpgnet.import_keys(openpgpkey) if args.fetch: if args.keyid: pubkey = gpgnet.export_keys(args.keyid, minimal=True) if not pubkey: print >> sys.stderr, 'openpgpkey: Requested keyid not present in received OpenPGP data' sys.exit(1) if args.uid: pubkey = gpgnet.export_keys(args.uid, minimal=True) if not pubkey: print >> sys.stderr, 'openpgpkey: Requested uid not present in received OpenPGP data' for id in gpgnet.list_keys()[0]['uids']: print >> sys.stderr, "# %s"%id sys.exit(1) if not args.uid and not args.keyid: pubkey = gpgnet.export_keys(args.email, minimal=True) print >> sys.stderr, 'openpgpkey: Received OpenPGP data does not contain a key with keyid %s'%args.email print >> sys.stderr, '(add --uid to override with any of the below received uids)' for id in gpgnet.list_keys()[0]['uids']: print >> sys.stderr, "# %s"%id sys.exit(1) pubkey = pubkey.replace("Version:","Comment: %s key obtained from DNS\nVersion:"%args.email) if args.insecure: pubkey = pubkey.replace("Version:","Comment: NOT VALIDATED BY DNSSEC\nVersion:") else: pubkey = pubkey.replace("Version:","Comment: key transfer was protected by DNSSEC\nVersion:") print pubkey if args.fetch: sys.exit(0) received_keys = gpgnet.list_keys() gpgdisk = gnupg.GPG() gpgdisk.decode_errors = 'ignore' disk_keys = gpgdisk.list_keys() for pkey in received_keys: if args.debug: print >> sys.stderr, "Received from DNS: Key-ID:%s Fingerprint:%s"%(pkey["keyid"], pkey["fingerprint"]) found = False for dkey in disk_keys: if args.debug: print >> sys.stderr, "Local disk: Key-ID:%s Fingerprint:%s"%(dkey["keyid"], dkey["fingerprint"]) if pkey["keyid"] == dkey["keyid"] and pkey["fingerprint"] == dkey["fingerprint"]: found = True if found == False: shutil.rmtree(fdir) sys.exit("Received key with keyid %s was not found"%pkey["keyid"]) else: if args.debug: print >> sys.stderr, "Received key with keyid %s was found"%pkey["keyid"] print "All OPENPGPKEY records matched with content from the local keyring" shutil.rmtree(fdir) sys.exit(0) else: # we want to create gpgdisk = gnupg.GPG() gpgdisk.decode_errors = 'ignore' found = False # if we have the keyid, use that if args.keyid: ekey = gpgdisk.export_keys(args.keyid,minimal=True, secret=False, armor=False) if ekey: found = True createOPENPGPKEY(args.email, gpgdisk, args.keyid, args.output, args.debug) # else find key if not found: disk_keys = gpgdisk.list_keys() for pgpkey in disk_keys: for uid in pgpkey["uids"]: if "<%s>"%args.email in uid: if args.debug: print >> sys.stderr, "Found matching KeyID: %s (%s) for %s"%(pgpkey["keyid"], pgpkey["fingerprint"], uid) ekey = gpgdisk.export_keys(pgpkey["keyid"],minimal=True, secret=False, armor=False) createOPENPGPKEY(args.email, gpgdisk, pgpkey["keyid"], args.output, args.debug) found = True # give up if not found: errt = "No key found for " if args.email: errt += "email address %s "%args.email if args.uid: errt += "or uid %s "%args.uid if args.keyid: errt += "or keyid %s "%args.keyid sys.exit(errt) hash-slinger-2.7/openpgpkey.1000066400000000000000000000076741264206050700162310ustar00rootroot00000000000000'\" t .\" Title: openpgpkey .\" Author: [see the "AUTHORS" section] .\" Generator: DocBook XSL Stylesheets v1.78.1 .\" Date: December 30, 2013 .\" Manual: Internet / DNS .\" Source: Paul Wouters .\" Language: English .\" .TH "OPENPGPKEY" "1" "December 30, 2013" "Paul Wouters" "Internet / DNS" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" openpgpkey \- Create and verify RFC\-TBD OPENPGPKEY DNS records .SH "SYNTAX" .PP openpgpkey [\fB\-\-fetch\fR | \fB\-\-verify\fR] [\fB\-\-insecure\fR] [\fB\-\-resolv\&.conf /PATH/TO/RESOLV\&.CONF\fR] \fIuser@domain\fR .PP openpgpkey [\fB\-\-create\fR] [\fB\-\-insecure\fR] [\fB\-\-resolv\&.conf /PATH/TO/RESOLV\&.CONF\fR] [\fB\-\-output {rfc,generic,both}\fR] [\fB\-\-uid \fR] [\fB\-\-keyid \fR] \fIuser@domain\fR .SH "DESCRIPTION" .PP openpgpkey generates RFC\-TBD OPENPGPKEY DNS records\&. To generate these records for older nameserver implementations that do not yet support the OPENPGPKEY record, specify \fI\-\-output generic\fR to output the openpgpkey data in Generic Record (RFC\-3597) format\&. Records are generated by taking all keys with the specified email address associated with it from the user\*(Aqs local GnuPG keychain\&. .PP Verification of OPENPGPKEY records is done by comparing the keyid and fingerprint of the OPENPGPKEY obtained from DNS with the version in the local GnuPG keychain\&. .SH "OPTIONS" .PP \fB\-\-fetch\fR .RS 4 Fetch an OPENPGPKEY public key record from DNS .RE .PP \fB\-\-create\fR .RS 4 Create an OPENPGPKEY DNS record .RE .PP \fB\-\-verify\fR .RS 4 Verify a public key from the local GPG keyring with the OPENPGPKEY DNS record .RE .PP \fB\-\-resolvconf\fR FILE .RS 4 Specify a custom resolv\&.conf file (default: /etc/resolv\&.conf) .RE .PP \fB\-\-output\fR rfc | generic | both .RS 4 Output format of OPENPGPKEY record\&. "OPENPGPKEY" for rfc, "TYPE61" for generic (default: generic) .RE .PP If neither create or verify is specified, create is used\&. .SH "REQUIREMENTS" .PP openpgpkey requires the following python libraries: unbound, gnupg and argparse\&. It also requires gnupg which provides the gpg command\&. .SH "BUGS" .PP none known .SH "EXAMPLES" .PP typical usage: .PP openpgpkey \-\-fetch paul@nohats\&.ca > paul\&.pubkey .PP openpgpkey \-\-verify paul@nohats\&.ca .PP openpgpkey \-\-create paul@nohats\&.ca .SH "SEE ALSO" .PP draft\-ietf\-dane\-openpgpkey .PP \m[blue]\fBhttp://people\&.redhat\&.com/pwouters/hash\-slinger/\fR\m[] .SH "AUTHORS" .PP Paul Wouters .SH "COPYRIGHT" .PP Copyright 2014\-2015 .PP 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\&. See <\m[blue]\fBhttp://www\&.fsf\&.org/copyleft/gpl\&.txt\fR\m[]>\&. .PP 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 (file COPYING in the distribution) for more details\&. hash-slinger-2.7/openpgpkey.1.xml000066400000000000000000000113271264206050700170160ustar00rootroot00000000000000 December 30, 2013 openpgpkey 1 January 6, 2014 Paul Wouters Internet / DNS openpgpkey Create and verify RFC-TBD OPENPGPKEY DNS records SYNTAX openpgpkey [ | ] [] [] user@domain openpgpkey [] [] [] [] [] [] user@domain DESCRIPTION openpgpkey generates RFC-TBD OPENPGPKEY DNS records. To generate these records for older nameserver implementations that do not yet support the OPENPGPKEY record, specify --output generic to output the openpgpkey data in Generic Record (RFC-3597) format. Records are generated by taking all keys with the specified email address associated with it from the user's local GnuPG keychain. Verification of OPENPGPKEY records is done by comparing the keyid and fingerprint of the OPENPGPKEY obtained from DNS with the version in the local GnuPG keychain. OPTIONS Fetch an OPENPGPKEY public key record from DNS Create an OPENPGPKEY DNS record Verify a public key from the local GPG keyring with the OPENPGPKEY DNS record FILE Specify a custom resolv.conf file (default: /etc/resolv.conf) rfc | generic | both Output format of OPENPGPKEY record. "OPENPGPKEY" for rfc, "TYPE61" for generic (default: generic) If neither create or verify is specified, create is used. REQUIREMENTS openpgpkey requires the following python libraries: unbound, gnupg and argparse. It also requires gnupg which provides the gpg command. BUGS none known EXAMPLES typical usage: openpgpkey --fetch paul@nohats.ca > paul.pubkey openpgpkey --verify paul@nohats.ca openpgpkey --create paul@nohats.ca SEE ALSO draft-ietf-dane-openpgpkey http://people.redhat.com/pwouters/hash-slinger/ AUTHORS Paul Wouters <pwouters@redhat.com> COPYRIGHT Copyright 2014-2015 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. See <http://www.fsf.org/copyleft/gpl.txt>. 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 (file COPYING in the distribution) for more details. hash-slinger-2.7/sshfp000077500000000000000000000310361264206050700150240ustar00rootroot00000000000000#!/usr/bin/python # # Generate SSHFP DNS records (RFC4255) from knownhosts files or ssh-keyscan # # Copyright 2010 by Xelerance http://www.xelerance.com/ (Paul Wouters) # Copyright 2012 Paul Wouters # Copyright 2014 Gerald Turner # Copyright 2015 Jean-Michel Nirgal Vourgere # Copyright 2015 Dirk Stoecker # # 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. VERSION = "2.7" import os import sys import subprocess import optparse import base64 import time import hashlib import hmac import re # www.dnspython.org try: import dns.resolver import dns.query import dns.zone except ImportError: print >> sys.stderr, "sshfp requires the python-dns package from http://www.pythondns.org/" print >> sys.stderr, "Fedora: yum install python-dns" print >> sys.stderr, "Debian: apt-get install python-dnspython (NOT python-dns!)" print >> sys.stderr, "openSUSE: zypper in python-dnspython" sys.exit(1) global all_hosts global khfile global hostnames global trailing global quiet global port global timeout global algo DEFAULT_KNOWN_HOSTS_FILE = "~/.ssh/known_hosts" def show_version(): print >> sys.stderr, "sshfp version: " + VERSION def create_sshfp(hostname, keytype, keyblob, digesttype): """Creates an SSH fingerprint""" if keytype == "ssh-rsa": keytype = "1" elif keytype == "ssh-dss": keytype = "2" elif "ecdsa" in keytype: keytype = "3" elif keytype == "ssh-ed25519": # TBD http://tools.ietf.org/html/draft-moonesamy-sshfp-ed25519-01 keytype = "4" else: return "" if digesttype == "sha1": digest = hashlib.sha1 digesttype = "1" elif digesttype == "sha256": digest = hashlib.sha256 digesttype = "2" else: return "" try: rawkey = base64.b64decode(keyblob) except TypeError: print >> sys.stderr, "FAILED on hostname "+hostname+" with keyblob "+keyblob return "ERROR" fp = digest(rawkey).hexdigest().upper() # check for Reverse entries reverse = 1 parts = hostname.split(".", 3) if parts[0] != hostname: for octet in parts: if not octet.isdigit(): reverse = 0 if reverse: hostname = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa." # we don't know wether we need a trailing dot :( # eg if someone did "ssh ns.foo" we don't know if this really is "ns.foo." or "ns.foo" plus resolv.conf domainname if trailing and not reverse: if hostname[-1:] != ".": hostname = hostname + "." return hostname + " IN SSHFP " + keytype + " " + digesttype + " " + fp def get_known_host_entry(known_hosts, host): """Get a single entry out of a known_hosts file Uses the ssh-keygen utility.""" cmd = ["ssh-keygen", "-f", known_hosts, "-F", host] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = process.communicate() if not quiet and stderr: print >> sys.stderr, stderr outputl = [] for e in stdout.split("\n"): if not e.startswith("#"): outputl.append(e) return "\n".join(outputl) def sshfp_from_file(khfile, wantedHosts): global all_hosts global algo # ok, let's do it known_hosts = os.path.expanduser(khfile) try: khfp = open(known_hosts) except IOError: print >> sys.stderr, "ERROR: failed to open file "+ known_hosts sys.exit(1) hashed_known_hosts = False if khfp.readline().startswith("|1|"): hashed_known_hosts = True khfp.close() fingerprints = [] if hashed_known_hosts and all_hosts: print >> sys.stderr, "ERROR: %s is hashed, cannot use with -a" % known_hosts sys.exit(1) elif hashed_known_hosts: #only looking for some known hosts for host in wantedHosts: fingerprints.append(process_records(get_known_host_entry(known_hosts, host), (host,))) else: try: khfp = open(known_hosts) except IOError: print >> sys.stderr, "ERROR: failed to open file "+ known_hosts sys.exit(1) data = khfp.read() khfp.close() fingerprints.append(process_records(data, wantedHosts)) return "\n".join(fingerprints) def check_keytype(keytype, hostname): global algos for algo in algos: if algo == "dsa": # different name in user interface and files algo = "dss" if algo in keytype: return True if not quiet: print >> sys.stderr, "Could only find key type %s for %s" % (keytype, hostname) return False def check_hashed(entry, hostnames): (hashtype, salt64, hash64) = entry[1:].split("|") if hashtype == "1": salt = base64.b64decode(salt64) hash = base64.b64decode(hash64) for host in hostnames: if hash == hmac.new(salt, host, hashlib.sha1).digest(): return host return "" def process_records(data, hostnames): """Process all records in a string. If the global "all_hosts" is True, then return SSHFP entries for all records with the allowed key types. If "all_hosts is False and hostnames is non-empty, return only the items in hostnames """ global digests all_records = [] for record in data.split("\n"): if record.startswith("#") or record.startswith("@") or not record: continue try: # Ignore optionnal 4th column "root@localhost" (host, keytype, key) = record.split(" ")[:3] except ValueError: if not quiet: print >> sys.stdout, "Print unable to read record '%s'" % record continue if "," in host: host = host.split(",")[0] elif host[0] == '|': host = check_hashed(host, hostnames) if (all_hosts and host) or host in hostnames: if not check_keytype(keytype, host): continue for digesttype in digests: value = create_sshfp(host, keytype, key, digesttype) if not value in all_records: all_records.append(value) if all_records: all_records.sort() return "\n".join(all_records) else: return "" def get_record(domain, qtype): try: answers = dns.resolver.query(domain, qtype) except dns.resolver.NXDOMAIN: #print "NXdomain: "+domain return 0 except dns.resolver.NoAnswer: #print "NoAnswer: "+domain return 0 for rdata in answers: # just return first entry we got, answers[0].target does not work if qtype == "A": return rdata if qtype == "NS": return str(rdata.target) else: print >> sys.stderr, "ERROR: error in get_record, unknown type " + qtype sys.exit(1) def get_axfr_record(domain, nameserver): try: zone = dns.zone.from_xfr(dns.query.xfr(nameserver, domain, rdtype=dns.rdatatype.AXFR)) except dns.exception.FormError: raise dns.exception.FormError, domain else: return zone def sshfp_from_axfr(domain, nameserver): if " " in domain: print >> sys.stderr, "ERROR: space in domain '"+domain+"' can't be right, aborted" sys.exit(1) if not nameserver: nameserver = get_record(domain, "NS") if not nameserver: print >> sys.stderr, "WARNING: no NS record found for domain "+domain+". trying as host record instead" # better then nothing return sshfp_from_dns([domain]) hosts = [] #print "nameserver:" + str(ns) try: # print "trying axfr for "+domain+"@"+nameserver axfr = get_axfr_record(domain, nameserver) except dns.exception.FormError, badDomain: print >> sys.stderr, "AXFR error: %s - No permission or not authorative for %s; aborting" % (nameserver, badDomain) sys.exit(1) for (name, ttl, rdata) in axfr.iterate_rdatas('A'): #print "name:" +str(name) +", ttl:"+ str(ttl)+ ", rdata:"+str(rdata) if "@" in str(name): hosts.append(domain + ".") else: if not str(name) == "localhost": hosts.append("%s.%s." % (name, domain)) return sshfp_from_dns(hosts) def sshfp_from_dns(hosts): global quiet global port global timeout global algos if "dsa" in algos: print >> sys.stderr, "WARNING: openssh has obsoleted dsa/dss keys" cmd = ["ssh-keyscan", "-p", str(port), "-T", str(timeout), "-t", ",".join(algos)] + hosts process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = process.communicate() stderr = re.sub("#.*\n", "", stderr) # strip scan comments if not quiet: print >> sys.stderr, stderr khdns = stdout return process_records(khdns, hosts) def main(): global all_hosts global trailing global quiet global port global timeout global algos global digests parser = optparse.OptionParser() parser.add_option("-k", "--knownhosts", "--known-hosts", action="store", dest="known_hosts", metavar="KNOWN_HOSTS_FILE", default=DEFAULT_KNOWN_HOSTS_FILE, help="obtain public ssh keys from the known_hosts file KNOWN_HOSTS_FILE") parser.add_option("-s", "--scan", action="store_true", default=False, dest="scan", help="scan the listed hosts for public keys using ssh-keyscan") parser.add_option("-a", "--all", action="store_true", dest="all_hosts", help="scan all hosts in the known_hosts file when used with -k. When used with -s, attempt a zone transfer to obtain all A records in the domain provided") parser.add_option("-d", "--trailing-dot", action="store_true", dest="trailing_dot", help="add a trailing dot to the hostname in the SSHFP records") parser.add_option("-o", "--output", action="store", metavar="FILENAME", default=None, help="write to FILENAME instead of stdout") parser.add_option("-p", "--port", action="store", metavar="PORT", type="int", default=22, help="use PORT for scanning") parser.add_option("-v", "--version", action="store_true", dest="version", help="print version information and exit") parser.add_option("-q", "--quiet", action="store_true", dest="quiet") parser.add_option("-T", "--timeout", action="store", type="int", dest="timeout", default=5, help="scanning timeout (default %default)") parser.add_option("-t", "--type", action="append", type="choice", dest="algo", choices=["rsa", "ecdsa", "ed25519", "dsa"], default=[], help="key type to fetch (may be specified more than once, default rsa,ecdsa,ed25519,dsa)") parser.add_option("--digest", action="append", type="choice", dest="digest", choices=["sha1", "sha256"], default=[], help="fingerprint hash function (may be specified more than once, default sha1,sha256)") parser.add_option("-n", "--nameserver", action="store", type="string", dest="nameserver", default="", help="nameserver to use for AXFR (only valid with -s -a)") (options, args) = parser.parse_args() # parse options khfile = options.known_hosts dodns = options.scan nameserver = "" domain = "" output = options.output quiet = options.quiet data = "" trailing = options.trailing_dot timeout = options.timeout algos = options.algo or ["rsa", "ecdsa", "ed25519"] digests = options.digest or ["sha256"] all_hosts = options.all_hosts port = options.port hostnames = () if options.version: show_version() sys.exit(0) if not quiet and port != 22: print >> sys.stderr, "WARNING: non-standard port numbers are not designated in SSHFP records" if not quiet and options.known_hosts and options.scan: print >> sys.stderr, "WARNING: Ignoring known hosts option -k , -s was passed" if options.nameserver and not options.scan and not options.all_hosts: print >> sys.stderr, "ERROR: Cannot specify -n without -s and -a" sys.exit(1) if not options.scan and options.all_hosts and args: print >> sys.stderr, "WARNING: -a and hosts both passed, ignoring manual host list" if not args and (not all_hosts): print >> sys.stderr, "WARNING: Assuming -a" all_hosts = True if options.scan and options.all_hosts: datal = [] for arg in args: datal.append(sshfp_from_axfr(arg, options.nameserver)) if not quiet: datal.insert(0, ";") datal.insert(0, "; Generated by sshfp %s from %s at %s" % (VERSION, nameserver, time.ctime())) datal.insert(0, ";") data = "\n".join(datal) elif options.scan: # Scan specified hosts if not args: print >> sys.stderr, "ERROR: You asked me to scan, but didn't give any hosts to scan" sys.exit(1) data = sshfp_from_dns(args) else: # known_hosts data = sshfp_from_file(khfile, args) if output: try: fp = open(output, "w") except IOError: print >> sys.stderr, "ERROR: can't open '%s'' for writing" % output sys.exit(1) else: fp.write(data) fp.close() else: print data if __name__ == "__main__": main() hash-slinger-2.7/sshfp.1000066400000000000000000000132311264206050700151550ustar00rootroot00000000000000'\" t .\" Title: sshfp .\" Author: [see the "AUTHORS" section] .\" Generator: DocBook XSL Stylesheets v1.78.1 .\" Date: January 2, 2015 .\" Manual: Internet / DNS .\" Source: Paul Wouters .\" Language: English .\" .TH "SSHFP" "1" "January 2, 2015" "Paul Wouters" "Internet / DNS" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" sshfp \- Generate SSHFP DNS records from knownhosts files or ssh\-keyscan .SH "SYNTAX" .PP sshfp [\fB\-k\fR <\fIknownhosts_file\fR>] [\fB\-d\fR] [\fB\-a\fR] [\fB\-\-type\fR ] [\fB\-\-digest\fR ] [<\fIhost1\fR> [\fIhost2 \&.\&.\&.]\fR] .PP sshfp \fB\-s\fR [\fB\-p\fR <\fIport\fR>] [\fB\-d\fR] [\fB\-a\fR] [\fB\-\-type\fR ] [\fB\-\-digest\fR ] [\fB\-n \fI] [\fIdomain2\fR] <\fIhost1\fR> [\fIhost2 \&.\&.\&.\fR] > .SH "DESCRIPTION" .PP sshfp generates RFC\-4255 SSHFP DNS records based on the public keys stored in a known_hosts file, which implies the user has previously trusted this key, or public keys can be obtained by using ssh\-keyscan (1)\&. Using ssh\-keyscan (1) implies a secure path to connect to the hosts being scanned\&. It also implies a trust in the DNS to obtain the IP address of the hostname to be scanned\&. If the nameserver of the domain allows zone tranfers (AXFR), an entire domain can be processed for all its A records\&. .SH "OPTIONS" .PP \fB\-s / \-\-scan\fR <\fIhostname1\fR> [hostname2 \&.\&.\&.] .RS 4 Scan hosts or domain for public SSH keys using ssh\-keyscan .RE .PP \fB\-k / \-\-knownhosts <\fR\fIknownhosts_file\fR\fI> <\fR\fIhostname1\fR\fI> [hostname2 \&.\&.\&.]\fR .RS 4 Obtain public SSH keys from a known_hosts file\&. Defaults to using ~/\&.ssh/known_hosts .RE .PP \fB\-a / \-\-all\fR .RS 4 Scan all hosts in the known_hosts file when used with \-k\&. When used with \-s, it will attempt an zone transfer (AXFR) to obtain all A records in the domain specified\&. .RE .PP \fB\-d / \-\-trailing\-dot\fR .RS 4 Add a trailing dot to the hostname in the SSHFP records\&. It is not possible to determine whether a known_hosts or dns query is for a FQDN (eg www\&.redhat\&.com) or not (eg www) or not (unless \-d domainname \-a is used, in which case a trailing dot is always appended)\&. Non\-FQDN get their domainname appended through /etc/resolv\&.conf These non\-FQDN will happen when using a non\-FQDN (eg sshfp \-k www) or known_hosts entries obtained by running ssh www\&.sub where \&.domain\&.com is implied\&. When \-d is used, all hostnames not ending with a dot, that at least contain two parts in their hostname (eg www\&.sub but not www get a trailing dot\&. Note that the output of sshfp can also just be manually editted for trailing dots\&. .RE .PP \fB\-o / \-\-output\fR <\fIfilename\fR> .RS 4 Write to filename instead of stdout .RE .PP \fB\-p / \-\-port\fR <\fIportnumber\fR> .RS 4 Use portnumber for scanning\&. Note that portnumbers do NOT appear in SSHFP records\&. .RE .PP \fB\-h / \-\-help\fR .RS 4 Output help information and exit\&. .RE .PP \fB\-v / \-\-version\fR .RS 4 Output version information and exit\&. .RE .PP \fB\-q / \-\-quiet\fR .RS 4 Output less miscellany to stderr .RE .SH "FILES" .PP ~/\&.ssh/known_hosts .SH "REQUIREMENTS" .PP sshfp requires python\-dns (\m[blue]\fBhttp://www\&.pythondns\&.org\fR\m[]) .PP Fedora: yum install python\-dns .PP Debian: apt\-get install python\-dnspython .SH "BUGS" .PP if a domain contains non\-working glue A records, then ssh\-keyscan aborts instead of skipping the single broken entry\&. .PP This program can look up hashed hostnames in a known_hosts file if a recent\-enough ssh\-keygen is present .SH "EXAMPLES" .PP typical usage: .PP sshfp (implies \-k \-a) .PP sshfp \-a \-d (implies \-k) .PP sshfp \-k bofh\&.nohats\&.ca (from known_hosts) .PP sshfp \-s bofh\&.nohats\&.ca (from a scan to the host) .PP sshfp \-k ~paul/\&.ssh/known_hosts bofh\&.nohats\&.ca www\&.openswan\&.org \-o /tmp/mysshfp\&.txt .PP sshfp \-a \-d \-d nohats\&.ca \-n ns0\&.nohats\&.ca >> /var/named/primary/nohats\&.ca .SH "SEE ALSO" .PP \fBssh-keyscan\fR(1)\fBssh\fR(1)\fBtlsa\fR(1) and RFC\-4255 .SH "AUTHORS" .PP Paul Wouters , Jacob Appelbaum , James Brown .SH "COPYRIGHT" .PP Copyright 2006\-2010 Xelerance Corporation .PP Copyright 2012 Paul Wouters .PP 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\&. See <\m[blue]\fBhttp://www\&.fsf\&.org/copyleft/gpl\&.txt\fR\m[]>\&. .PP 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 (file COPYING in the distribution) for more details\&. hash-slinger-2.7/sshfp.1.xml000066400000000000000000000164321264206050700157620ustar00rootroot00000000000000 January 2, 2015 sshfp 1 January 2, 2015 Paul Wouters Internet / DNS sshfp Generate SSHFP DNS records from knownhosts files or ssh-keyscan SYNTAX sshfp [ <knownhosts_file>] [] [] [ <algo>] [ <digest>] [<host1> [host2 ...]] sshfp [ <port>] [] [] [ <algo>] [ <digest>] [>] <domain1> [domain2] <host1> [host2 ...] > DESCRIPTION sshfp generates RFC-4255 SSHFP DNS records based on the public keys stored in a known_hosts file, which implies the user has previously trusted this key, or public keys can be obtained by using ssh-keyscan (1). Using ssh-keyscan (1) implies a secure path to connect to the hosts being scanned. It also implies a trust in the DNS to obtain the IP address of the hostname to be scanned. If the nameserver of the domain allows zone tranfers (AXFR), an entire domain can be processed for all its A records. OPTIONS <hostname1> [hostname2 ...] Scan hosts or domain for public SSH keys using ssh-keyscan knownhosts_file> <hostname1> [hostname2 ...] Obtain public SSH keys from a known_hosts file. Defaults to using ~/.ssh/known_hosts Scan all hosts in the known_hosts file when used with -k. When used with -s, it will attempt an zone transfer (AXFR) to obtain all A records in the domain specified. Add a trailing dot to the hostname in the SSHFP records. It is not possible to determine whether a known_hosts or dns query is for a FQDN (eg www.redhat.com) or not (eg www) or not (unless -d domainname -a is used, in which case a trailing dot is always appended). Non-FQDN get their domainname appended through /etc/resolv.conf These non-FQDN will happen when using a non-FQDN (eg sshfp -k www) or known_hosts entries obtained by running ssh www.sub where .domain.com is implied. When -d is used, all hostnames not ending with a dot, that at least contain two parts in their hostname (eg www.sub but not www get a trailing dot. Note that the output of sshfp can also just be manually editted for trailing dots. <filename> Write to filename instead of stdout <portnumber> Use portnumber for scanning. Note that portnumbers do NOT appear in SSHFP records. Output help information and exit. Output version information and exit. Output less miscellany to stderr FILES ~/.ssh/known_hosts REQUIREMENTS sshfp requires python-dns (http://www.pythondns.org) Fedora: yum install python-dns Debian: apt-get install python-dnspython BUGS if a domain contains non-working glue A records, then ssh-keyscan aborts instead of skipping the single broken entry. This program can look up hashed hostnames in a known_hosts file if a recent-enough ssh-keygen is present EXAMPLES typical usage: sshfp (implies -k -a) sshfp -a -d (implies -k) sshfp -k bofh.nohats.ca (from known_hosts) sshfp -s bofh.nohats.ca (from a scan to the host) sshfp -k ~paul/.ssh/known_hosts bofh.nohats.ca www.openswan.org -o /tmp/mysshfp.txt sshfp -a -d -d nohats.ca -n ns0.nohats.ca >> /var/named/primary/nohats.ca SEE ALSO ssh-keyscan1 ssh1 tlsa1 and RFC-4255 AUTHORS Paul Wouters <pwouters@redhat.com>, Jacob Appelbaum <jacob@appelbaum.net>, James Brown <jbrown@yelp.com> COPYRIGHT Copyright 2006-2010 Xelerance Corporation Copyright 2012 Paul Wouters 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. See <http://www.fsf.org/copyleft/gpl.txt>. 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 (file COPYING in the distribution) for more details. hash-slinger-2.7/tlsa000077500000000000000000001045121264206050700146440ustar00rootroot00000000000000#!/usr/bin/python # tlsa - A tool to create DANE/TLSA records. (called 'swede' before) # # This tool is loosly based on the 'dane' program in the sshfp package by Paul # Wouters and Christopher Olah # # Copyright 2012 Pieter Lexis # Copyright 2014 Paul Wouters # Copyright 2015 Dirk Stoecker # # 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. VERSION="2.7" import sys import os import socket import unbound import subprocess import re from M2Crypto import X509, SSL, BIO, m2 from binascii import a2b_hex, b2a_hex from hashlib import sha256, sha512 from ipaddr import IPv4Address, IPv6Address ROOTKEY="none" cauldron = ( "/var/lib/unbound/root.anchor", "/var/lib/unbound/root.key", "/etc/unbound/root.key" ) for root in cauldron: if os.path.isfile(root): ROOTKEY=root break def genTLSA(hostname, protocol, port, certificate, output='rfc', usage=1, selector=0, mtype=1): """This function generates a TLSARecord object using the data passed in the parameters, it then validates the record and returns the RR as a string. """ # check if valid vars were passed if hostname[-1] != '.': hostname += '.' # Create the record without a certificate if port == '*': record = TLSARecord(name='%s._%s.%s'%(port,protocol,hostname), usage=usage, selector=selector, mtype=mtype, cert ='') else: record = TLSARecord(name='_%s._%s.%s'%(port,protocol,hostname), usage=usage, selector=selector, mtype=mtype, cert ='') # Check if the record is valid if record.isValid: if record.selector == 0: # Hash the Full certificate record.cert = getHash(certificate, record.mtype) else: # Hash only the SubjectPublicKeyInfo record.cert = getHash(certificate.get_pubkey(), record.mtype) record.isValid(raiseException=True) if output == 'generic': return record.getRecord(generic=True) return record.getRecord() def genRecords(hostname, protocol, port, chain, output='rfc', usage=1, selector=0, mtype=1): cert = None chained = checkChainLink(chain)[0] if not chained: print "WARN: Certificates don't chain" certsleft = len(chain) for chaincert in chain: certsleft -= 1 if usage == 1 or usage == 3: # The first cert is the end-entity cert print 'Got a certificate with Subject: %s' % chaincert.get_subject() cert = chaincert break else: if (usage == 0 and chaincert.check_ca()) or usage == 2: if certsleft: # don't ask for the last one sys.stdout.write('Got a certificate with the following Subject:\n\t%s\nUse this as certificate to match? [y/N] ' % chaincert.get_subject()) input_ok = False while not input_ok: user_input = raw_input() if user_input in ['','n','N']: input_ok=True elif user_input in ['y', 'Y']: input_ok = True cert = chaincert else: sys.stdout.write('Please answer Y or N') else: print('Using certificate with the following Subject:\n\t%s\n' % chaincert.get_subject()) cert = chaincert if cert: break if cert: # Print the requested records based on the retrieved certificates if output == 'both': print genTLSA(hostname, protocol, port, cert, 'draft', usage, selector, mtype) print genTLSA(hostname, protocol, port, cert, 'rfc', usage, selector, mtype) else: print genTLSA(hostname, protocol, port, cert, output, usage, selector, mtype) # Clear the cert from memory (to stop M2Crypto from segfaulting) cert=None def getA(hostname, secure=True): """Gets a list of A records for hostname, returns a list of ARecords""" records = "" try: records = getRecords(hostname, rrtype='A', secure=secure) except InsecureLookupException, e: print str(e) except DNSLookupError, e: print 'Unable to resolve %s: %s' % (hostname, str(e)) ret = [] for record in records: ret.append(ARecord(hostname, str(IPv4Address(int(b2a_hex(record),16))))) return ret def getAAAA(hostname, secure=True): """Gets a list of A records for hostname, returns a list of AAAARecords""" records = "" try: records = getRecords(hostname, rrtype='AAAA', secure=secure) except InsecureLookupException, e: print str(e) except DNSLookupError, e: print 'Unable to resolve %s: %s' % (hostname, str(e)) ret = [] for record in records: ret.append(AAAARecord(hostname, str(IPv6Address(int(b2a_hex(record),16))))) return ret def getVerificationErrorReason(num): """This function returns the name of the X509 Error based on int(num) """ # These were taken from the M2Crypto.m2 code return { 50: "X509_V_ERR_APPLICATION_VERIFICATION", 22: "X509_V_ERR_CERT_CHAIN_TOO_LONG", 10: "X509_V_ERR_CERT_HAS_EXPIRED", 9: "X509_V_ERR_CERT_NOT_YET_VALID", 28: "X509_V_ERR_CERT_REJECTED", 23: "X509_V_ERR_CERT_REVOKED", 7: "X509_V_ERR_CERT_SIGNATURE_FAILURE", 27: "X509_V_ERR_CERT_UNTRUSTED", 12: "X509_V_ERR_CRL_HAS_EXPIRED", 11: "X509_V_ERR_CRL_NOT_YET_VALID", 8: "X509_V_ERR_CRL_SIGNATURE_FAILURE", 18: "X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT", 14: "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD", 13: "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD", 15: "X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD", 16: "X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD", 24: "X509_V_ERR_INVALID_CA", 26: "X509_V_ERR_INVALID_PURPOSE", 17: "X509_V_ERR_OUT_OF_MEM", 25: "X509_V_ERR_PATH_LENGTH_EXCEEDED", 19: "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN", 6: "X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY", 4: "X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE", 5: "X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE", 3: "X509_V_ERR_UNABLE_TO_GET_CRL", 2: "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT", 20: "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY", 21: "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE", 0: "X509_V_OK"}[int(num)] def getRecords(hostname, rrtype='A', secure=True, noresolver=False): """Do a lookup of a name and a rrtype, returns a list of binary coded strings. Only queries for rr_class IN.""" global resolvconf ctx = unbound.ub_ctx() if os.path.isfile(ROOTKEY): # file format guessing - unbound should deal with this :( try: ctx.add_ta_file(ROOTKEY) except: unbound.ub_ctx_trustedkeys(ctx,ROOTKEY) # Use the local cache and emulate /etc/hosts ctx.hosts("/etc/hosts") if resolvconf and not noresolver: ctx.resolvconf(resolvconf) if rrtype == 52: rrtypestr = "TLSA" else: rrtypestr = rrtype if type(rrtype) == str: if 'RR_TYPE_' + rrtype in dir(unbound): rrtype = getattr(unbound, 'RR_TYPE_' + rrtype) else: raise Exception('Error: unknown RR TYPE: %s.' % rrtype) elif type(rrtype) != int: raise Exception('Error: rrtype in wrong format, neither int nor str.') status, result = ctx.resolve(hostname, rrtype=rrtype) if status == 0 and result.havedata: if not result.secure: if secure: if not noresolver and resolvconf: retval = getRecords(hostname, rrtype, secure, True) print >> sys.stderr, 'Warning: initial query using resolver config file was not secure (try option --resolvconf="").' resolvconf = None return retval # The data is insecure and a secure lookup was requested raise InsecureLookupException('Error: Answer was not DNSSEC-secure') else: print >> sys.stderr, 'Warning: query data is not secure.' # If we are here the data was either secure or insecure data is accepted return result.data.raw else: raise DNSLookupError('Unsuccessful DNS lookup or no data returned for rrtype %s (%s).' % (rrtypestr, rrtype)) # identical to Connection.connect() except for the last parameter def sslStartTLSConnect(connection, addr, starttls=None): connection.socket.connect(addr) connection.addr = addr if starttls: # primitive method, no error checks yet if starttls == "smtp": data = connection.socket.recv(500) connection.socket.send("EHLO M2Crypto\r\n") data = connection.socket.recv(500) connection.socket.send("STARTTLS\r\n") data = connection.socket.recv(500) elif starttls == "imap": data = connection.socket.recv(500) connection.socket.send(". STARTTLS\r\n") data = connection.socket.recv(500) elif starttls == "ftp": data = connection.socket.recv(500) connection.socket.send("AUTH TLS\r\n") data = connection.socket.recv(500) elif starttls == "pop3": data = connection.socket.recv(500) connection.socket.send("STLS\r\n") data = connection.socket.recv(500) connection.setup_ssl() connection.set_connect_state() ret = connection.connect_ssl() check = getattr(connection, 'postConnectionCheck', connection.clientPostConnectionCheck) if check is not None: if not check(connection.get_peer_cert(), connection.addr[0]): raise Checker.SSLVerificationError('post connection check failed') return ret def getHash(certificate, mtype): """Hashes the certificate based on the mtype. The certificate should be an M2Crypto.X509.X509 object (or the result of the get_pubkey() function on said object) """ certificate = certificate.as_der() if mtype == 0: return b2a_hex(certificate) elif mtype == 1: return sha256(certificate).hexdigest() elif mtype == 2: return sha512(certificate).hexdigest() else: raise Exception('mtype should be 0,1,2') def getTLSA(hostname, port=443, protocol='tcp', secure=True): """ This function tries to do a secure lookup of the TLSA record. At the moment it requests the TYPE52 record and parses it into a 'valid' TLSA record It returns a list of TLSARecord objects """ if hostname[-1] != '.': hostname += '.' if not protocol.lower() in ['tcp', 'udp', 'sctp']: raise Exception('Error: unknown protocol: %s. Should be one of tcp, udp or sctp' % protocol) try: if port == '*': records = getRecords('*._%s.%s' % (protocol.lower(), hostname), rrtype=52, secure=secure) else: records = getRecords('_%s._%s.%s' % (port, protocol.lower(), hostname), rrtype=52, secure=secure) except InsecureLookupException, e: print str(e) sys.exit(1) except DNSLookupError, e: print 'Unable to resolve %s: %s' % (hostname, str(e)) sys.exit(1) ret = [] for record in records: hexdata = b2a_hex(record) if port == '*': ret.append(TLSARecord('*._%s.%s' % (protocol.lower(), hostname), int(hexdata[0:2],16), int(hexdata[2:4],16), int(hexdata[4:6],16), hexdata[6:])) else: ret.append(TLSARecord('_%s._%s.%s' % (port, protocol.lower(), hostname), int(hexdata[0:2],16), int(hexdata[2:4],16), int(hexdata[4:6],16), hexdata[6:])) return ret def verifyCertMatch(record, cert): """ Verify the certificate with the record. record should be a TLSARecord and cert should be a M2Crypto.X509.X509 """ if not isinstance(cert, X509.X509): return if not isinstance(record, TLSARecord): return if record.selector == 1: certhash = getHash(cert.get_pubkey(), record.mtype) else: certhash = getHash(cert, record.mtype) if not certhash: return if certhash == record.cert: return True else: return False def verifyCertNameWithHostName(cert, hostname, with_msg=False): """Verify the name on the certificate with a hostname, we need this because we get the cert based on IP address and thusly cannot rely on M2Crypto to verify this""" if not isinstance(cert, X509.X509): return if not isinstance(hostname, str): return if hostname[-1] == '.': hostname = hostname[0:-1] hostname = hostname.lower() certnames = [] for entry in str(cert.get_subject()).lower().split("/"): if entry.startswith("cn="): certnames.append(entry[3:]) try: for value in re.split(", ?", cert.get_ext('subjectAltName').get_value().lower()): if value.startswith("dns:"): certnames.append(value[4:]) except: pass if hostname in certnames: return True for certname in certnames: if certname[0] == '*' and hostname.endswith(certname[1:]): return True if with_msg: print 'WARNING: Name on the certificate (Subject: %s, SubjectAltName: %s) doesn\'t match requested hostname (%s).' % (str(cert.get_subject()), cert.get_ext('subjectAltName').get_value(), hostname) return False def checkChainLink(chain, record=None): previous_issuer = None chained = True matched = False for cert in chain: if previous_issuer: if not str(previous_issuer) == str(cert.get_subject()): # The chain cannot be valid chained = False break previous_issuer = cert.get_issuer() if record and verifyCertMatch(record, cert): matched = True return chained, matched def getLocalChain(filename, debug): """Returns list of M2Crypto.X509.X509 objects and verification result""" chain = [] bio = BIO.openfile(filename) while True: cptr = m2.x509_read_pem(bio._ptr()) if not cptr: break chain.append(X509.X509(cptr, _pyfree=1)) if not chain: raise X509Error(Err.get_error()) # FIXME - is this possible using the library (without a call to openssl tool)? cmd = ["openssl", "verify", filename] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = process.communicate() if debug: print >> sys.stderr, stderr if stdout.endswith("OK\n"): verify_result = 0 else: verify_result = "%s%s" % (stdout, stderr) return chain, verify_result def usageText(usage): names = ["PKIX-CA", "PKIX-EE", "DANE-TA", "DANE-EE"] return "Usage %d [%s]" % (usage, names[usage]) def verifyChain(chain, verify_result, pre_exit, local, source): if local: text_cert = "Local certificate" text_chain = "certificate in the local certificate chain" else: text_cert = "Certificate offered by the server" text_chain = "certificate in the certificate chain offered by the server" if not verifyCertNameWithHostName(cert=chain[0], hostname=str(args.host), with_msg=True): # The name on the cert doesn't match the hostname... we don't verify the TLSA record print 'Caution: %s does not match hostname (%s)' % (text_cert, source) ut = usageText(record.usage) if record.usage == 1: # End-host cert chained, matched = checkChainLink((chain[0],), record) if not chained: print "WARN: Certificates don't chain" if matched: if verify_result == 0: # The cert chains to a valid CA cert according to the system-certificates print 'SUCCESS (%s): %s matches the one mentioned in the TLSA record and chains to a valid CA certificate (%s)' % (ut, text_cert, source) else: if local: reason = verify_result else: reason = getVerificationErrorReason(verify_result) print 'FAIL (%s): %s matches the one mentioned in the TLSA record but the following error was raised during PKIX validation (%s): %s' % (ut, text_cert, source, reason) if pre_exit == 0: pre_exit = 2 if args.debug: print 'The matched certificate has Subject: %s' % cert.get_subject() else: print 'FAIL: %s does not match the TLSA record (%s)' % (text_cert, source) if pre_exit == 0: pre_exit = 2 elif record.usage == 0: # CA constraint # FIXME: Does neither handle chain data in full cert TLSA records (type 0) correctly # nor handles short certification chains # In these case the chain should be completed with missing records either # from TLSA or local certificate store # Remove the first (= End-Entity cert) from the chain chained, matched = checkChainLink(chain[1:], record) if not chained: print "WARN: Certificates don't chain" if matched: if cert.check_ca(): if verify_result == 0: print 'SUCCESS (%s): A %s matches the one mentioned in the TLSA record and is a CA certificate (%s)' % (ut, text_chain, source) else: if local: reason = verify_result else: reason = getVerificationErrorReason(verify_result) print 'FAIL (%s): A %s matches the one mentioned in the TLSA record and is a CA certificate, but the following error was raised during PKIX validation (%s): %s' % (ut, text_chain, source, reason) if pre_exit == 0: pre_exit = 2 else: print 'FAIL (%s): A %s matches the one mentioned in the TLSA record but is not a CA certificate (%s)' % (ut, text_chain, source) if pre_exit == 0: pre_exit = 2 if args.debug: print 'The matched certificate has Subject: %s' % cert.get_subject() else: print 'FAIL (%s): No %s matches the TLSA record (%s)' % (ut, text_chain, source) if pre_exit == 0: pre_exit = 2 elif record.usage == 2: # Usage 2, use the cert in the record as trust anchor # FIXME: Does not handle chain data in full cert TLSA records (type 0) correctly # In this case the chain should be completed with missing records if chain is # not complete chained, matched = checkChainLink(chain, record) if matched: if not chained: print "WARN: Certificates don't chain" print 'SUCCESS (%s): A %s (including the end-entity certificate) matches the TLSA record (%s)' % (ut, text_chain, source) if args.debug: print 'The matched certificate has Subject: %s' % cert.get_subject() else: if not chained: print "FAIL: Certificates don't chain" print 'FAIL (%s): No %s (including the end-entity certificate) matches the TLSA record (%s)' % (ut, text_chain, source) if pre_exit == 0: pre_exit = 2 elif record.usage == 3: # EE cert MUST match chained, matched = checkChainLink((chain[0],), record) if not chained: print "WARN: Certificates don't chain" if matched: print 'SUCCESS (%s): %s matches the TLSA record (%s)' % (ut, text_cert, source) if args.debug: print 'The matched certificate has Subject: %s' % chain[0].get_subject() else: print 'FAIL (%s): %s does not match the TLSA record (%s)' % (ut, text_cert, source) if pre_exit == 0: pre_exit = 2 return pre_exit class TLSARecord: """When instanciated, this class contains all the fields of a TLSA record. """ def __init__(self, name, usage, selector, mtype, cert): """name is the name of the RR in the format: /^(_\d{1,5}|\*)\._(tcp|udp|sctp)\.([a-z0-9]*\.){2,}$/ usage, selector and mtype should be an integer cert should be a hexidecimal string representing the certificate to be matched field """ try: self.rrtype = 52 # TLSA per https://www.iana.org/assignments/dns-parameters self.rrclass = 1 # IN self.name = str(name) self.usage = int(usage) self.selector = int(selector) self.mtype = int(mtype) self.cert = str(cert) except: raise Exception('Invalid value passed, unable to create a TLSARecord') def getRecord(self, generic=False): """Returns the RR string of this TLSARecord, either in rfc (default) or generic format""" if generic: return '%s IN TYPE52 \# %s %s%s%s%s' % (self.name, (len(self.cert)/2)+3 , self._toHex(self.usage), self._toHex(self.selector), self._toHex(self.mtype), self.cert) return '%s IN TLSA %s %s %s %s' % (self.name, self.usage, self.selector, self.mtype, self.cert) def _toHex(self, val): """Helper function to create hex strings from integers""" return "%0.2x" % val def isValid(self, raiseException=False): """Check whether all fields in the TLSA record are conforming to the spec and check if the port, protocol and name are good""" err =[] try: if not 1 <= int(self.getPort()) <= 65535: err.append('Port %s not within correct range (1 <= port <= 65535)' % self.getPort()) except: if self.getPort() != '*': err.append('Port %s not a number' % self.getPort()) if not self.usage in [0,1,2,3]: err.append('Usage: invalid (%s is not one of 0 [PKIX-CA], 1 [PKIX-EE], 2 [DANE-TA] or 3 [DANE-EE])' % self.usage) if not self.selector in [0,1]: err.append('Selector: invalid (%s is not one of 0 [Cert] or 1 [SPKI])' % self.selector) if not self.mtype in [0,1,2]: err.append('Matching Type: invalid (%s is not one of 0 [FULL], 1 [SHA-256] or 2 [SHA-512])' % self.mtype) if not self.isNameValid(): err.append('Name (%s) is not in the correct format: _portnumber._transportprotocol.hostname.dom.' % self.name) # A certificate length of 0 is accepted if self.mtype in [1,2] and len(self.cert) != 0: if not len(self.cert) == {1:64,2:128}[self.mtype]: err.append('Certificate for Association: invalid (Hash length does not match hash-type in Matching Type(%s))' % {1:'SHA-256',2:'SHA-512'}[self.mtype]) if len(err) != 0: if not raiseException: return False else: msg = 'The TLSA record is invalid.' for error in err: msg += '\n\t%s' % error raise RecordValidityException(msg) else: return True def isNameValid(self): """Check if the name if in the correct format""" if not re.match('^(_\d{1,5}|\*)\._(tcp|udp|sctp)\.([-a-z0-9]*\.){2,}$', self.name): return False return True def getProtocol(self): """Returns the protocol based on the name""" return re.split('\.', self.name)[1][1:] def getPort(self): """Returns the port based on the name""" if re.split('\.', self.name)[0][0] == '*': return '*' else: return re.split('\.', self.name)[0][1:] class ARecord: """An object representing an A Record (IPv4 address)""" def __init__(self, hostname, address): self.rrtype = 1 self.hostname = hostname self.address = address def __str__(self): return self.address def isValid(self): try: IPv4Address(self.address) return True except: return False class AAAARecord: """An object representing an AAAA Record (IPv6 address)""" def __init__(self, hostname, address): self.rrtype = 28 self.hostname = hostname self.address = address def __str__(self): return self.address def isValid(self): try: IPv6Address(self.address) return True except: return False # Exceptions class RecordValidityException(Exception): pass class InsecureLookupException(Exception): pass class DNSLookupError(Exception): pass if __name__ == '__main__': import argparse # create the parser parser = argparse.ArgumentParser(description='Create and verify TLSA records.', epilog='For bugs. see tlsa@nohats.ca') # Caveat: For TLSA validation, this program chases through the certificate chain offered by the server, not its local certificates.' parser.add_argument('--verify','-v', action='store_true', help='Verify a TLSA record, exit 0 when all TLSA records are matched, exit 2 when a record does not match the received certificate, exit 1 on error.') parser.add_argument('--create','-c', action='store_true', help='Create a TLSA record') parser.add_argument('--version', action='version', version='tlsa version: %s'%VERSION, help='show version and exit') parser.add_argument('-4', '--ipv4', dest='ipv4', action='store_true',help='use ipv4 networking only') parser.add_argument('-6', '--ipv6', dest='ipv6', action='store_true',help='use ipv6 networking only') parser.add_argument('--insecure', action='store_true', default=False, help='Allow use of non-dnssec secured answers') parser.add_argument('--resolvconf', metavar='/PATH/TO/RESOLV.CONF', action='store', default='/etc/resolv.conf', help='Use a recursive resolver listed in a resolv.conf file (default: /etc/resolv.conf)') parser.add_argument('host', metavar="hostname") parser.add_argument('--port', '-p', action='store', default='443', help='The port, or \'*\' where running TLS is located (default: %(default)s).') parser.add_argument('--starttls', '-t', action='store', choices=['no', 'smtp', 'imap', 'pop3', 'ftp'], help='Protocol needs special start procedure, requires protocol name.') parser.add_argument('--protocol', action='store', choices=['tcp','udp','sctp'], default='tcp', help='The protocol the TLS service is using (default: %(default)s).') parser.add_argument('--only-rr', action='store_true', help='Only verify that the TLSA resource record is correct (do not check certificate)') parser.add_argument('--rootkey', metavar='/PATH/TO/ROOT.KEY', action='store', help='Specify file location containing the DNSSEC root key') if os.path.isdir("/etc/pki/tls/certs/"): cadir = "/etc/pki/tls/certs/" elif os.path.isdir("/etc/ssl/certs/"): cadir = "/etc/ssl/certs/" else: cadir = "." print ("warning: no system wide CAdir found, using current directory") parser.add_argument('--ca-cert', metavar='/PATH/TO/CERTSTORE', action='store', default = cadir, help='Path to a CA certificate or a directory containing the certificates (default: %(default)s)') parser.add_argument('--debug', '-d', action='store_true', help='Print details plus the result of the validation') parser.add_argument('--quiet', '-q', action='store_true', help='Ignored for backwards compatibility') parser.add_argument('--certificate', help='The certificate used for the host. If certificate is empty, the certificate will be downloaded from the server') parser.add_argument('--output', '-o', action='store', default='rfc', choices=['generic','rfc','both'], help='The type of output. Generic (RFC 3597, TYPE52), RFC (TLSA) or both (default: %(default)s).') # Usage of the certificate parser.add_argument('--usage', '-u', action='store', type=int, default=3, choices=[0,1,2,3], help='The Usage of the Certificate for Association. \'0\' for CA [PKIX-CA], \'1\' for End Entity [PKIX-EE], \'2\' for trust-anchor [DANE-TA], \'3\' for ONLY End-Entity match [DANE-EE] (default: %(default)s).') parser.add_argument('--selector', '-s', action='store', type=int, default=0, choices=[0,1], help='The Selector for the Certificate for Association. \'0\' for Full Certificate [Cert], \'1\' for SubjectPublicKeyInfo [SPKI] (default: %(default)s).') parser.add_argument('--mtype', '-m', action='store', type=int, default=1, choices=[0,1,2], help='The Matching Type of the Certificate for Association. \'0\' for Exact match, \'1\' for SHA-256 hash, \'2\' for SHA-512 (default: %(default)s).') args = parser.parse_args() if args.rootkey: if os.path.isfile(args.rootkey): ROOTKEY = args.rootkey else: print ("ignored specified non-existing rootkey file %s"%args.rootkey) # check whether it's ASCII or needs to be converted into Punnycode try: args.host.decode('ascii') except UnicodeDecodeError: args.host = unicode(args.host, 'utf-8').encode("idna") if args.host[-1] != '.': args.host += '.' snihost = args.host[0:-1] if not args.starttls: if args.port == "25": args.starttls = "smtp" elif args.port == "143": args.starttls = "imap" elif args.port == "110": args.starttls = "pop3" elif args.port == "21": args.starttls = "ftp" elif args.starttls == "no": args.starttls = None global resolvconf if args.resolvconf: if os.path.isfile(args.resolvconf): resolvconf = args.resolvconf else: print >> sys.stdout, '%s is not a file. Unable to use it as resolv.conf' % args.resolvconf sys.exit(1) else: resolvconf = None # not operations are fun! secure = not args.insecure if args.verify: records = getTLSA(args.host, args.port, args.protocol, secure) if len(records) == 0: sys.exit(1) for record in records: pre_exit = 0 # First, check if the first three fields have correct values. if args.debug: print 'Received the following record for name %s:' % record.name print '\tUsage:\t\t\t\t%d (%s)' % (record.usage, {0:'CA Constraint [PKIX-CA]', 1:'End-Entity Constraint + chain to CA [PKIX-EE]', 2:'Trust Anchor [DANE-TA]', 3:'End-Entity [DANE-EE]'}.get(record.usage, 'INVALID')) print '\tSelector:\t\t\t%d (%s)' % (record.selector, {0:'Certificate [Cert]', 1:'SubjectPublicKeyInfo [SPKI]'}.get(record.selector, 'INVALID')) print '\tMatching Type:\t\t\t%d (%s)' % (record.mtype, {0:'Full Certificate', 1:'SHA-256', 2:'SHA-512'}.get(record.mtype, 'INVALID')) print '\tCertificate for Association:\t%s' % record.cert try: record.isValid(raiseException=True) except RecordValidityException, e: print >> sys.stderr, 'Error: %s' % str(e) continue else: if args.debug: print 'This record is valid (well-formed).' if args.only_rr: # Go to the next record continue # When we are here, The user also wants to verify the certificates with the record if args.protocol != 'tcp': print >> sys.stderr, 'Only SSL over TCP is supported (sorry)' sys.exit(0) if args.debug: print 'Attempting to verify the record with the TLS service...' if not args.ipv4 and not args.ipv6: addresses = getA(args.host, secure=secure) + getAAAA(args.host, secure=secure) elif args.ipv4: addresses = getA(args.host, secure=secure) else: addresses = getAAAA(args.host, secure=secure) if args.certificate: try: chain, verify_result = getLocalChain(args.certificate, args.debug) pre_exit = verifyChain(chain, verify_result, pre_exit, True, args.certificate) except Exception, e: print 'Could not verify local certificate: %s.' % e sys.exit(0) for address in addresses: if args.debug: print 'Got the following IP: %s' % str(address) # We do the certificate handling here, as M2Crypto keeps segfaulting when we do it in a method ctx = SSL.Context() if os.path.isfile(args.ca_cert): if ctx.load_verify_locations(cafile=args.ca_cert) != 1: raise Exception('No CA cert') elif os.path.exists(args.ca_cert): if ctx.load_verify_locations(capath=args.ca_cert) != 1: raise Exception('No CA certs') else: print >> sys.stderr, '%s is neither a file nor a directory, unable to continue' % args.ca_cert sys.exit(1) # Don't error when the verification fails in the SSL handshake ctx.set_verify(SSL.verify_none, depth=9) if isinstance(address, AAAARecord): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) else: sock = None connection = SSL.Connection(ctx, sock=sock) try: connection.set_tlsext_host_name(snihost) if(args.debug): print 'Did set servername %s' % snihost except AttributeError: print 'Could not set SNI (old M2Crypto version?)' except: print 'Could not set SNI' try: if args.starttls: sslStartTLSConnect(connection, (str(address), int(args.port)), args.starttls) #connection.connect((str(address), int(args.port)), args.starttls) else: connection.connect((str(address), int(args.port))) #except TypeError: # print 'Cannot connect to %s (old M2Crypto version not supporting start script?)' % address # continue except SSL.Checker.WrongHost, e: # The name on the remote cert doesn't match the hostname because we connect on IP, not hostname (as we want secure lookup) pass except socket.error, e: print 'Cannot connect to %s: %s' % (address, str(e)) continue chain = connection.get_peer_cert_chain() verify_result = connection.get_verify_result() # Good, now let's verify pre_exit = verifyChain(chain, verify_result, pre_exit, False, address) # Cleanup, just in case connection.clear() connection.close() ctx.close() # END for address in addresses # END for record in records sys.exit(pre_exit) # END if args.verify else: # we want to create cert = None if not args.certificate: if args.protocol != 'tcp': print >> sys.stderr, 'Only SSL over TCP is supported (sorry)' sys.exit(1) if args.debug: print 'No certificate specified on the commandline, attempting to retrieve it from the server %s' % (args.host) connection_port = args.port if args.port == '*': sys.stdout.write('The port specified on the commandline is *, please specify the port of the TLS service on %s (443): ' % args.host) input_ok = False while not input_ok: user_input = raw_input() if user_input == '': connection_port = 443 break try: if 1 <= int(user_input) <= 65535: connection_port = user_input input_ok = True except: sys.stdout.write('Port %s not numerical or within correct range (1 <= port <= 65535), try again (hit enter for default 443): ' % user_input) # Get the address records for the host try: #addresses = getA(args.host, secure=secure) + getAAAA(args.host, secure=secure) if not args.ipv4 and not args.ipv6: addresses = getA(args.host, secure=secure) + getAAAA(args.host, secure=secure) elif args.ipv4: addresses = getA(args.host, secure=secure) else: addresses = getAAAA(args.host, secure=secure) except InsecureLookupException, e: print >> sys.stderr, str(e) sys.exit(1) for address in addresses: if args.debug: print 'Attempting to get certificate from %s' % str(address) # We do the certificate handling here, as M2Crypto keeps segfaulting when try to do stuff with the cert if we don't ctx = SSL.Context() ctx.set_verify(SSL.verify_none, depth=9) if isinstance(address, AAAARecord): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) else: sock = None connection = SSL.Connection(ctx, sock=sock) try: connection.set_tlsext_host_name(snihost) if(args.debug): print 'Did set servername %s' % snihost except AttributeError: print 'Could not set SNI (old M2Crypto version?)' except: print 'Could not set SNI' try: if args.starttls: sslStartTLSConnect(connection, (str(address), int(connection_port)), args.starttls) #connection.connect((str(address), int(connection_port)), args.starttls) else: connection.connect((str(address), int(connection_port))) #except TypeError: # print 'Cannot connect to %s (old M2Crypto version not supporting start script?)' % address # continue except SSL.Checker.WrongHost: pass except socket.error, e: print 'Cannot connect to %s: %s' % (address, str(e)) continue chain = connection.get_peer_cert_chain() genRecords(args.host, args.protocol, args.port, chain, args.output, args.usage, args.selector, args.mtype) # Cleanup the connection and context connection.clear() connection.close() ctx.close() else: # Pass the path to the certificate to the genTLSA function try: chain, verify_result = getLocalChain(args.certificate, args.debug) except Exception, e: print 'Could not verify local certificate: %s.' % e if args.usage == 0 or args.usage == 1 and not verify_result: print 'Following error was raised during PKIX validation: %s' % verify_result genRecords(args.host, args.protocol, args.port, chain, args.output, args.usage, args.selector, args.mtype) hash-slinger-2.7/tlsa.1000066400000000000000000000126611264206050700150030ustar00rootroot00000000000000'\" t .\" Title: tlsa .\" Author: [see the "AUTHORS" section] .\" Generator: DocBook XSL Stylesheets v1.78.1 .\" Date: December 7, 2015 .\" Manual: Internet / DNS .\" Source: Paul Wouters .\" Language: English .\" .TH "TLSA" "1" "December 7, 2015" "Paul Wouters" "Internet / DNS" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" tlsa \- Create and verify RFC\-6698 TLSA DNS records .SH "SYNTAX" .PP tlsa [\fB\-h\fR] [\fB\-\-verify\fR] [\fB\-create\fR] [\fB\-\-version\fR] [\fB\-4\fR] [\fB\-6\fR\fB\-\-insecure\fR] [\fB\-\-resolv\&.conf /PATH/TO/RESOLV\&.CONF\fR] [\fB\-\-port PORT\fR] [\fB\-\-starttls {auto,smtp,imap,pop3,ftp}\fR] [\fB\-\-protocol {tcp,udp,sctp}\fR] [\fB\-\-ponly\-rr\fR] [\fB\-\-rootkey /PATH/TO/ROOT\&.KEY\fR] [\fB\-\-ca\-cert /PATH/TO/CERTSTORE\fR] [\fB\-\-debug\fR] [\fB\-\-quiet\fR] [\fB\-\-certificate CERTIFICATE\fR] [\fB\-\-output {rfc,generic,both}\fR] [\fB\-\-usage {0,1,2,3}\fR] [\fB\-\-selector {0,1}\fR] [\fB\-mtype {0,1,2}\fR] \fIhostname\fR .SH "DESCRIPTION" .PP tlsa generates RFC\-6698 TLSA DNS records\&. To generate these records for older nameserver implementations that do not yet support the TLSA record, specify \fI\-\-output generic\fR to output the tlsa data in Generic Record (RFC\-3597) format\&. Records are generated by connecting to the website using SSL and grabbing the (EE) certificate and the CA chain\&. Depending on the type and selector used, this information is used to generate TLSA records\&. Currently\&. tlsa has no AXFR support for en\-mass TLSA record generation\&. .SH "OPTIONS" .PP \fB\-\-create\fR .RS 4 Create a TLSA record .RE .PP \fB\-\-verify\fR .RS 4 Verify a TLSA record .RE .PP \fB\-\-protocol\fR tcp | udp | sctp .RS 4 Use a specific transport protocol (default: tcp) .RE .PP \fB\-\-resolvconf\fR FILE .RS 4 Specify a custom resolv\&.conf file (default: /etc/resolv\&.conf)\&. Pass empty value (\-\-resolvconf="") to disable default\&. .RE .PP \fB\-\-port\fR PORT .RS 4 Use specified port (default: 443) .RE .PP \fB\-\-starttls\fR no | smtp | imap | pop3 | ftp .RS 4 Start script type for protocols which need special commands to start a TLS connection\&. Supported are \*(Aqftp\*(Aq (port 21), \*(Aqsmtp\*(Aq (port 25), \*(Aqpop3\*(Aq (port 110) and \*(Aqimap\*(Aq (port 143)\&. The default selects the type based on the port number\&. The value \*(Aqno\*(Aq overrides auto detection\&. .RE .PP \fB\-\-only\-rr\fR .RS 4 Only print the DNS TLSA record .RE .PP \fB\-\-certificate\fR file\&.crt .RS 4 Use specified certificate file, instead of retrieving the certificate from the server\&. Can be a single cert or a complete chain\&. .RE .PP \fB\-\-ca\-cert\fR directory .RS 4 Use specified directory containing CA bundles for CA validation (default: /etc/pki/tls/certs) .RE .PP \fB\-\-rootkey\fR filename .RS 4 Use specified file to read the DNSSEC root key (in anchor or bind format) .RE .PP \fB\-\-output\fR rfc | generic | both .RS 4 Output format of TLSA record\&. "TLSA" for rfc, "TYPE52" for generic (default: rfc) .RE .PP \fB\-\-usage\fR 0 | 1 | 2 | 3 .RS 4 Usage type: public CA (0), EE match validated by public CA (1), private CA (2), private EE (3) (default: 3) .RE .PP \fB\-\-selector\fR 0 | 1 .RS 4 The selector type describes what the type covers \- full certificate (0) or public key (1) (default: 0) .RE .PP \fB\-\-mtype\fR 0 | 1 | 2 .RS 4 Type of the TLSA data\&. Exact match on content (0), SHA256 (1) or SHA512 (2) (default: 0) .RE .PP If neither create or verify is specified, create is used\&. .SH "REQUIREMENTS" .PP tlsa requires the following python libraries: unbound, m2crypto, argparse and ipaddr .SH "BUGS" .PP ipv4/ipv6 handling .SH "EXAMPLES" .PP typical usage: .PP tlsa www\&.fedoraproject\&.org .PP tlsa \-\-verify \-4 nohats\&.ca .PP tlsa \-\-create \-\-insecure fedoraproject\&.org .SH "SEE ALSO" .PP \fBsshfp\fR(1)\fBssh-keygen\fR(1)and RFC\-6698 .PP \m[blue]\fBhttp://people\&.redhat\&.com/pwouters/hash\-slinger/\fR\m[] .PP \m[blue]\fBhttp://os3sec\&.org/\fR\m[] .SH "AUTHORS" .PP Pieter Lexis .SH "COPYRIGHT" .PP Copyright 2012 .PP 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\&. See <\m[blue]\fBhttp://www\&.fsf\&.org/copyleft/gpl\&.txt\fR\m[]>\&. .PP 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 (file COPYING in the distribution) for more details\&. hash-slinger-2.7/tlsa.1.xml000066400000000000000000000161561264206050700156050ustar00rootroot00000000000000 December 7, 2015 tlsa 1 December 7, 2015 Paul Wouters Internet / DNS tlsa Create and verify RFC-6698 TLSA DNS records SYNTAX tlsa [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] hostname DESCRIPTION tlsa generates RFC-6698 TLSA DNS records. To generate these records for older nameserver implementations that do not yet support the TLSA record, specify --output generic to output the tlsa data in Generic Record (RFC-3597) format. Records are generated by connecting to the website using SSL and grabbing the (EE) certificate and the CA chain. Depending on the type and selector used, this information is used to generate TLSA records. Currently. tlsa has no AXFR support for en-mass TLSA record generation. OPTIONS Create a TLSA record Verify a TLSA record tcp | udp | sctp Use a specific transport protocol (default: tcp) FILE Specify a custom resolv.conf file (default: /etc/resolv.conf). Pass empty value (--resolvconf="") to disable default. PORT Use specified port (default: 443) no | smtp | imap | pop3 | ftp Start script type for protocols which need special commands to start a TLS connection. Supported are 'ftp' (port 21), 'smtp' (port 25), 'pop3' (port 110) and 'imap' (port 143). The default selects the type based on the port number. The value 'no' overrides auto detection. Only print the DNS TLSA record file.crt Use specified certificate file, instead of retrieving the certificate from the server. Can be a single cert or a complete chain. directory Use specified directory containing CA bundles for CA validation (default: /etc/pki/tls/certs) filename Use specified file to read the DNSSEC root key (in anchor or bind format) rfc | generic | both Output format of TLSA record. "TLSA" for rfc, "TYPE52" for generic (default: rfc) 0 | 1 | 2 | 3 Usage type: public CA (0), EE match validated by public CA (1), private CA (2), private EE (3) (default: 3) 0 | 1 The selector type describes what the type covers - full certificate (0) or public key (1) (default: 0) 0 | 1 | 2 Type of the TLSA data. Exact match on content (0), SHA256 (1) or SHA512 (2) (default: 0) If neither create or verify is specified, create is used. REQUIREMENTS tlsa requires the following python libraries: unbound, m2crypto, argparse and ipaddr BUGS ipv4/ipv6 handling EXAMPLES typical usage: tlsa www.fedoraproject.org tlsa --verify -4 nohats.ca tlsa --create --insecure fedoraproject.org SEE ALSO sshfp1 ssh-keygen1and RFC-6698 http://people.redhat.com/pwouters/hash-slinger/ http://os3sec.org/ AUTHORS Pieter Lexis <pieter.lexis@os3.nl> COPYRIGHT Copyright 2012 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. See <http://www.fsf.org/copyleft/gpl.txt>. 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 (file COPYING in the distribution) for more details.