Browse Source

init

master
nervuri 4 months ago
commit
44eb7bb264
  1. 373
      LICENSE
  2. 26
      README.md
  3. 725
      trust-seeker

373
LICENSE

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

26
README.md

@ -0,0 +1,26 @@
# Trust Seeker
Verify TLS certificates using different network perspectives.
Trust Seeker mixes ideas from:
* Moxie Marlinspike's [Convergence](https://youtu.be/UawS3_iuHoA?t=2100) project
* Recommendations made in ["Public Key Pinning for TLS Using a Trust on First Use Model"](https://rp.delaat.net/2012-2013/p56/report.pdf) (Gabor X Toth & Tjebbe Vlieg, 2013)
It is a certificate pinning program that can be run either privately, on the command line, or publicly, as a server-side CGI script. Each public trust seeker can be asked what certificate it sees for a certain host. Client software can query multiple trust seekers, to check for consensus.
It aims to bring as much relevant information as possible to bear on any trust decision. This includes the TLS version and cipher suite, to help defend against downgrade attacks.
It can verify TLS certificates on any host and port, regardless of the protocol underneath: HTTP, DNS (DoT and DoH), e-mail (SMTP, IMAP, POP3), IRC, FTP, Gemini, [Gopher](https://github.com/curl/curl/commit/a1f06f32b8603427535fc21183a84ce92a9b96f7)), etc.
SSH support is on the roadmap.
Trust Seeker can be used with command line tools that support public key pinning, such as [curl](https://curl.se/libcurl/c/CURLOPT_PINNEDPUBLICKEY.html) and wget, to protect every connection they make. The holy grail is to enable this kind of dynamic key pinning for e-mail server-to-server communication, which currently relies on opportunistic encryption.
## Current status
The code is in an early exploratory stage. You can experiment with it, but big changes are planned and there is no regard for backward compatibility at this point.
## Contributing
The project is hosted at [https://tildegit.org/nervuri/trust-seeker](https://tildegit.org/nervuri/trust-seeker). Just [shoot me an email](https://nervuri.net/contact) if you don't want to [make a tildegit account](https://tildegit.org/user/sign_up).

725
trust-seeker

@ -0,0 +1,725 @@
#!/usr/bin/env python3
import sqlite3
import sys
import os
import getopt
import urllib
import io
import ipaddress
import socket
import hashlib
import codecs
import base64
import time
from datetime import datetime, timezone
import ssl
import OpenSSL
import cryptography.hazmat.primitives.serialization
import idna # punycode
import pycurl
remote_protocol = '' # command line by default
# CGI
if 'REQUEST_METHOD' in os.environ:
import cgi
# CGI debugging
#import cgitb; cgitb.enable()
#print('Content-Type: text/html')
#cgi.test()
if os.environ['REQUEST_SCHEME'] == 'gemini':
remote_protocol = 'gemini'
else:
remote_protocol = 'http'
pin_status: dict = {
'active': 1,
'inactive': 0,
'rejected': -1,
}
# Get path to database.
pathname = os.path.dirname(sys.argv[0])
basepath = os.path.abspath(os.path.realpath(pathname))
dbpath = basepath + '/trust-seeker.db'
# Print to stderr (https://stackoverflow.com/a/14981125).
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# Outputs response in the appropriate format
def respond(response: str, status='success', mime_type: str = ''):
# Status codes for CLI, Gemini and HTTP.
# Inspired by Convergence's Notary Protocol:
# https://github.com/moxie0/Convergence/wiki/Notary-Protocol
status_codes: dict = {
'success': [0, 20, 200],
'mismatch': [1, 50, 409], # fingerprint mismatch
'no_info': [2, 51, 303], # host not found in database
'bad_input': [3, 59, 400],
'internal_error': [4, 41, 503],
'error': [5, status, status], # general error
}
if type(response) not in [str, list]:
status = 'internal_error'
response = 'Response type unknown'
# If status is an integer, get its corresponding string value
if type(status) == int:
def get_status(status: int) -> str:
for sc in status_codes:
for c in status_codes[sc]:
if status == c:
return sc
return 'error'
status = get_status(status)
status_code = status_codes[status][0]
# TODO: find a better way
if response[:6] == 'Usage:':
mime_type = 'text/plain'
# build CSV response - https://tools.ietf.org/html/rfc4180
if not mime_type:
mime_type = 'text/csv'
if mime_type == 'text/csv':
if type(response) == str:
if ',' in response and '\n' not in response:
response = '"' + response + '"'
if response[:7] != 'status,':
response = 'status,response\n' + status + ',' + response
elif type(response) == list:
csv = 'status,fingerprint,expires,tls_version,cipher_suite,first_seen,last_seen,seen_count' # CSV header
for pin in response:
csv += '\n' + status +\
',' + pin['fingerprint'] +\
',' + str(pin['expires']) +\
',' + str(pin['tls_version']) +\
',' + pin['cipher_suite'] +\
',' + str(pin['first_seen']) +\
',' + str(pin['last_seen']) +\
',' + str(pin['seen_count'])
response = csv
# No CGI
if remote_protocol == '':
if status == 'success':
print(response)
else:
eprint(response)
# CGI
else:
if remote_protocol == 'gemini':
remote_status_code = status_codes[status][1]
print(str(remote_status_code) + ' ' + mime_type + '\r\n', end='')
elif remote_protocol == 'http':
remote_status_code = str(status_codes[status][2])
print('Status: ' + remote_status_code + '\r\nContent-Type: ' + mime_type + '\r\n\r\n', end='')
# Note: setting the "Status" header won't work in Python's built-in CGIHTTPServer
# https://stackoverflow.com/a/32079589
print(response, end='')
exit(status_code)
# Split <hostname:port> into (<hostname>, <port>)
def split_host(host: str) -> tuple:
# Hostname might be an IPv6 address
hs = host.split(':')
hostname = ':'.join(hs[:-1]).lower() # all but the last element
port = hs[len(hs)-1] # the last element
return (hostname, port)
def normalize_host(host: str, exit_on_fail: bool = False) -> str:
# Host has the form <hostname:port>
hostname, port = split_host(host)
def exit_or_return(response: str, exit_on_fail: bool):
if exit_on_fail:
respond(response, 'bad_input')
else:
eprint(response)
return False
if hostname.count(':') >= 2: # IPv6
# Compress IPv6 address
hostname = hostname.replace('[', '').replace(']', '')
try:
hostname = '[' + ipaddress.IPv6Address(hostname).compressed + ']'
except:
exit_or_return('Bad input: ' + host, exit_on_fail)
else:
try:
# If hostname is punycode, convert it to IDN (UTF-8)
hostname = idna.decode(hostname)
# Also check the port for forbidden characters
port = idna.decode(port)
except:
exit_or_return('Bad input: ' + host, exit_on_fail)
# Check port
try:
port = int(port)
except:
exit_or_return('Bad input: ' + host, exit_on_fail)
if int(port) < 1 or int(port) > 65535:
exit_or_return('Port not in allowed range: ' + host, exit_on_fail)
# Block remote queries of private IP ranges (TODO: do this properly)
if remote_protocol:
if (hostname == 'localhost'
or hostname == '127.0.0.1'
or hostname == '::1' # IPv6
or hostname[:2] == 'fd' # IPv6
or hostname[:3] == '10.'
# TODO: 172.16.0.0 – 172.31.255.255 ( 172.16.0.0/12 )
or hostname[:8] == '192.168.'):
exit_or_return("Can't query this host remotely: " + host, exit_on_fail)
return hostname + ':' + str(port)
def create_database():
if os.path.isfile(dbpath):
return # DB already created
if not os.access(basepath, os.W_OK):
respond("No write permission for \"" + basepath + "\".\n\
Can't create database.", 'internal_error')
connection = sqlite3.connect(dbpath)
cursor = connection.cursor()
# Fingerprint = hash of SubjectPublicKeyInfo (SPKI), not of entire cert.
cursor.execute('''
CREATE TABLE certs (
id INTEGER PRIMARY KEY,
cert BLOB UNIQUE,
fingerprint TEXT NOT NULL,
expires INTEGER NOT NULL
);''')
cursor.execute('CREATE INDEX idx_certs_fp ON certs (fingerprint);')
cursor.execute('''
CREATE TABLE pins (
status INTEGER NOT NULL DEFAULT 1,
host TEXT NOT NULL,
cert_id INTEGER NOT NULL,
first_seen INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
seen_count INTEGER NOT NULL DEFAULT 1 CHECK(seen_count > 0),
tls_version REAL NOT NULL CHECK(tls_version >= 1),
cipher_suite TEXT NOT NULL,
PRIMARY KEY (host, cert_id),
FOREIGN KEY(cert_id) REFERENCES certs(id)
);''')
connection.commit()
cursor.close()
connection.close()
def get_TLS_info(host: str, timeout: int = 2) -> dict:
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
#context.verify_mode = ssl.CERT_REQUIRED
hostname, port = split_host(host)
try:
conn = socket.create_connection((hostname, port), timeout)
sock = context.wrap_socket(conn, server_hostname=hostname) # SNI
except:
eprint('Connection failed for ' + host)
return
connection_details = sock.cipher()
TLS_info = {
'cert': sock.getpeercert(True), # DER format
'cipher_suite': connection_details[0],
'tls_version': float(connection_details[1][4:]),
}
sock.close()
#PEM_cert = ssl.DER_cert_to_PEM_cert(TLS_info['cert'])
# Get hash of the SubjectPublicKeyInfo (SPKI).
# https://www.imperialviolet.org/2011/05/04/pinning.html
# gemini://makeworld.space/gemlog/2020-07-03-tofu-rec.gmi
s = cryptography.hazmat.primitives.serialization
e = s.Encoding.DER
f = s.PublicFormat.SubjectPublicKeyInfo
#pubkey = s.load_der_public_key(TLS_info['cert'])
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, TLS_info['cert'])
pubkey = x509.get_pubkey().to_cryptography_key()
spki = pubkey.public_bytes(encoding=e, format=f)
TLS_info['fingerprint'] = 'sha256:' + hashlib.sha256(spki).hexdigest()
# Get cert expiration value as UNIX timestamp.
TLS_info['expires']: int = int(
time.mktime(
time.strptime(
x509.get_notAfter().decode('ascii'),
'%Y%m%d%H%M%SZ')))
return TLS_info
# Check the database for this host
def find_pins(host: str, status: str = '') -> list:
connection = sqlite3.connect(dbpath)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
status_query = ''
if status:
# status = active, inactive or rejected
if status == 'active':
status_query = ' AND p.status > 0'
else:
status_query = ' AND p.status = ' + str(pin_status[status])
cursor.execute('SELECT * FROM certs c, pins p\
WHERE p.cert_id = c.id AND p.host = ?' + status_query + '\
ORDER BY p.last_seen DESC;',
[host])
pins = cursor.fetchall()
cursor.close()
connection.close()
return pins
# Get active certs
def get_certs(host: str) -> list:
pins = find_pins(host, 'active')
certs = []
for pin in pins:
certs.append(pin['cert'])
return certs
# Export certs to PEM string
def export_certs(host: str) -> str:
certs = get_certs(host)
certs_string = ''
for cert in certs:
certs_string += ssl.DER_cert_to_PEM_cert(cert)
return certs_string
def verify_host(host: str, fingerprint: str):
executed_import_host = False
pins = find_pins(host, 'active')
if not pins:
# If trust-seeker is called remotely, connect to the host and get its cert.
if remote_protocol:
import_host(host)
executed_import_host = True
pins = find_pins(host, 'active')
if not pins:
respond('No certs found for ' + host, 'no_info')
# Search for a pin matching the user-provided fingerprint.
def find_matching_pin(pins: list, fingerprint: str):
for pin in pins:
if pin['fingerprint'] == fingerprint:
respond([pin], 'success')
find_matching_pin(pins, fingerprint)
# No matching pins.
# Refresh the host's cert if we haven't already.
if remote_protocol and not executed_import_host:
import_host(host)
pins = find_pins(host, 'active')
find_matching_pin(pins, fingerprint)
# Again no matching pins.
# Output whatever pins we have for this host.
respond(pins, 'mismatch')
def import_host(host: str):
# Get TLS info.
TLS_info = get_TLS_info(host)
if TLS_info is None:
eprint('Retrying...')
time.sleep(2)
TLS_info = get_TLS_info(host)
if TLS_info is None:
return
timestamp_now: int = int(datetime.now(timezone.utc).timestamp())
cert_id: int = -1
pin_updated: bool = False
connection = sqlite3.connect(dbpath)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute('PRAGMA foreign_keys=ON;')
# Check for mismatch.
# If mismatch, display a warning and continue.
cursor.execute('''SELECT c.cert FROM certs c, pins p
WHERE p.cert_id = c.id AND host = ? AND status > 0;''',
[host])
pins = cursor.fetchall()
mismatch: bool = True if pins else False
for pin in pins:
if pin['cert'] == TLS_info['cert']:
mismatch = False
break
if mismatch:
eprint('Certificate changed for ' + host)
# Check if the cert is already in the DB (for some other host).
cursor.execute('SELECT * FROM certs WHERE cert = :cert;', TLS_info)
cert = cursor.fetchone()
if cert:
# Update the corresponding pin for this (host, cert) tuple.
cert_id = cert['id']
cursor.execute('SELECT seen_count FROM pins WHERE host = ? AND cert_id = ?;',
(host, cert_id))
pin = cursor.fetchone()
if pin:
sql = '''UPDATE pins
SET status = 1,
last_seen = :last_seen,
seen_count = :seen_count,
tls_version = :tls_version,
cipher_suite = :cipher_suite
WHERE cert_id = :cert_id AND host = :host;'''
cursor.execute(sql, {
'last_seen': timestamp_now,
'seen_count': pin['seen_count'] + 1,
'tls_version': TLS_info['tls_version'],
'cipher_suite': TLS_info['cipher_suite'],
'cert_id': cert['id'],
'host': host,
})
pin_updated = True
else:
# Cert not found, so add it.
sql = '''INSERT INTO certs ( cert, fingerprint, expires)
VALUES (:cert,:fingerprint,:expires);'''
cursor.execute(sql, TLS_info)
cert_id = cursor.lastrowid
if not pin_updated:
# Insert pin.
pin = {
'host' : host,
'cert_id' : cert_id,
'first_seen' : timestamp_now,
'last_seen' : timestamp_now,
'tls_version' : TLS_info['tls_version'],
'cipher_suite': TLS_info['cipher_suite'],
}
sql = '''INSERT INTO pins
( status, host, cert_id, first_seen, last_seen, seen_count, tls_version, cipher_suite)
VALUES ( 1,:host,:cert_id,:first_seen,:last_seen, 1,:tls_version,:cipher_suite);'''
cursor.execute(sql, pin)
# Make other (non-rejected) pins for this host inactive.
sql = '''UPDATE pins SET status = 0
WHERE status != -1 AND cert_id != :cert_id AND host = :host;'''
cursor.execute(sql, {
'cert_id': cert_id,
'host': host,
})
connection.commit()
cursor.close()
connection.close()
def import_file(hosts_file: str, default_port: str):
with open(hosts_file, 'r') as f:
for line in f:
line = line.strip()
if not line: # empty line
continue
if line[0] == '#': # comment
continue
host = line
if ':' not in host:
host += ':' + default_port
host = normalize_host(host)
if not host: # bad input
continue
print('Importing ' + host)
import_host(host)
time.sleep(0.3)
def check_input(argv: list) -> dict:
help_text = """Usage: trust-seeker [options...] <host[:port]>/<file>
--import Import host's cert / Import from file
--verify Verify host; --fingerprint is required
--fingerprint sha256:<hash> Provide cert fingerprint (SubjectPublicKeyInfo hash)
--port <port> Specify (default) port
--lookup Look up host in the trust seeker's database
--output[=certs] Specify what to output; only "certs" is accepted, for now
--ask <URL> Ask another trust seeker to check a cert fingerprint; --fingerprint is required"""
# TODO: ask without fingerprint = remote --lookup
command: dict = {
'actions': [] # import, verify, lookup, ask
}
try:
opts, args = getopt.gnu_getopt(argv, '', [
'help',
'import',
'verify',
'port=',
'fingerprint=',
'lookup',
'output=',
'ask=',
])
except getopt.GetoptError:
respond(help_text, 'bad_input')
if not opts:
respond(help_text, 'bad_input')
if len(args) > 1:
respond('Only one argument is accepted.', 'bad_input')
elif len(args) == 1:
arg = args[0]
filename, file_extension = os.path.splitext(arg)
if file_extension in ('', 'txt') and ':' not in arg and filename != 'localhost':
# Assume file.
command['file'] = arg
else:
# Assume host.
command['host'] = arg
for opt, arg in opts:
if opt in ('--help'):
respond(help_text, 'success')
elif opt in ('--import'):
command['actions'].append('import')
elif opt in ('--lookup'):
command['actions'].append('lookup')
elif opt in ('--output'):
if arg == 'certs':
command['output'] = arg
# TODO: specify exact output, for ex:
# --lookup=spki:sha256:base64,tls_version
elif opt in ('--verify'):
command['actions'].append('verify')
elif opt in ('-p', '--port'):
command['port'] = arg
elif opt in ('--fingerprint'):
command['fingerprint'] = arg
elif opt in ('--ask'):
command['actions'].append('ask')
command['trust_seeker_url'] = arg
if not command['actions']:
respond('No action specified.', 'bad_input')
# If --lookup is specified, ignore every other action
if 'lookup' in command['actions']:
command['actions'] = ['lookup']
# If --ask is specified, ignore --import and --verify
if 'ask' in command['actions']:
if 'import' in command['actions']:
command['actions'].remove('import')
if 'verify' in command['actions']:
command['actions'].remove('verify')
if 'fingerprint' not in command:
respond("Can't ask without fingerprint.", 'bad_input')
if 'verify' in command['actions']:
if 'fingerprint' not in command:
respond("Can't verify without fingerprint.", 'bad_input')
if 'file' in command:
respond("Can't verify a file, only a host.", 'bad_input')
if 'file' in command and 'port' not in command:
respond('Please specify the default --port.', 'bad_input')
if 'host' in command:
if ':' not in command['host']:
if 'port' in command:
command['host'] += ':' + command['port'] # TODO: [IPv6]:port
else:
respond('Please specify the port.', 'bad_input')
command['host'] = normalize_host(command['host'], exit_on_fail=True)
return command
def check_cgi_input() -> dict:
command: dict = {
'actions': [] # verify, lookup
}
# Get URL parameters
url_params = cgi.FieldStorage()
if 'host' in url_params:
command['host'] = url_params['host'].value
command['host'] = normalize_host(command['host'], exit_on_fail=True)
else:
html_help_text = """<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Trust Seeker</title>
<h1>Trust Seeker</h1>
<p>Parameters:<br>
• host=hostname:port <i>(required)</i><br>
• fingerprint=sha256:SPKI-hash <i>(optional)</i></p>
<p>Examples:<br>
• <a href="trust-seeker?host=rawtext.club:443">Request info about rawtext.club:443</a><br>
• <a href="trust-seeker?host=gemini.circumlunar.space:1965&fingerprint=sha256:1a03a15619200db4496494ec90381c1fe8bd9e0142260f6d8a3d962ed3cfc72f">Verify fingerprint of gemini.circumlunar.space:1965</a></p>
</html>"""
respond(html_help_text, 'bad_input', 'text/html')
if 'fingerprint' in url_params:
command['actions'] = ['verify']
command['fingerprint'] = url_params['fingerprint'].value
else:
command['actions'] = ['lookup']
return command
def ask(trust_seeker_url: str, host: str, fingerprint: str, timeout: int = 2):
# TODO: add --timeout option
parsed_url = urllib.parse.urlparse(trust_seeker_url)
ts_scheme = parsed_url.scheme
if ts_scheme not in ['gemini', 'https']:
respond('For --ask, only gemini and https schemes are allowed.', 'bad_input')
ts_hostname = parsed_url.hostname
ts_port = parsed_url.port
if not ts_port:
ts_port = 1965 if parsed_url.scheme == 'gemini' else 443
ts_host = ts_hostname + ':' + str(ts_port)
# Trust seekers' certificates must be in the database
# before they can be queried.
ts_fingerprint = ''
ts_pins = find_pins(ts_host, 'active')
for pin in ts_pins:
ts_fingerprint = pin['fingerprint']
if not ts_fingerprint:
respond("`" + ts_host + "` can't be queried unless its certificate has been imported.")
query = {'host': host, 'fingerprint': fingerprint}
query = '?' + urllib.parse.urlencode(query)
url = trust_seeker_url + query
# Connect to trust seeker
if ts_scheme == 'gemini':
# TODO: add Gemini support
respond('Gemini requests not yet implemented.', 'internal_error')
else: # http
# convert fingerprint to base64, for curl:
# https://curl.se/libcurl/c/CURLOPT_PINNEDPUBLICKEY.html
fp = ts_fingerprint.split(':')[1]
ts_fingerprint = base64.b64encode(codecs.decode(fp, 'hex')).decode('ascii')
buf = io.BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
#c.setopt(c.VERBOSE, True)
c.setopt(c.TIMEOUT, timeout)
c.setopt(c.USERAGENT, '')
c.setopt(c.SSLVERSION, c.SSLVERSION_TLSv1_2) # TLS 1.2 or later
c.setopt(c.SSL_VERIFYHOST, 0)
c.setopt(c.PINNEDPUBLICKEY, 'sha256//' + ts_fingerprint)
c.setopt(c.WRITEDATA, buf)
try:
c.perform()
except:
respond('Could not connect to ' + trust_seeker_url, 'internal_error')
status = c.getinfo(pycurl.RESPONSE_CODE)
response = buf.getvalue().decode('ascii')
c.close()
if response:
respond(response, status)
respond('No response from ' + ts_host, 'internal_error')
def main(argv: list):
if remote_protocol:
# CGI
command: dict = check_cgi_input()
else:
# Not CGI
create_database()
command: dict = check_input(argv)
if 'lookup' in command['actions']:
if 'output' in command:
if command['output'] == 'certs':
certs_string = export_certs(command['host'])
if certs_string == '':
respond('No active certs found for ' + command['host'], 'no_info')
respond(certs_string, 'success')
pins = find_pins(command['host'], 'active')
if not pins:
# If trust-seeker is called remotely, connect to the host and get its cert.
if remote_protocol:
import_host(command['host'])
executed_import_host = True
pins = find_pins(command['host'], 'active')
if not pins:
respond('No certs found for ' + command['host'], 'no_info')
respond(pins, 'success')
if 'import' in command['actions']:
# TLSv1.3 is required for import operations, in order to put
# the highest available TLS version in the 'tls_version' field.
if not ssl.HAS_TLSv1_3:
respond('TLS 1.3 not supported. Please update OpenSSL.', 'internal_error')
if 'file' in command:
print('Importing hosts...')
import_file(command['file'], command['port'])
else:
print('Importing ' + command['host'])
import_host(command['host'])
if 'verify' in command['actions']:
#print('Verifying ' + command['host'])
verify_host(command['host'], command['fingerprint'])
if 'ask' in command['actions']:
#print('Asking `' + command['trust_seeker_url'] + '` about `' + command['host'] + '`')
ask(command['trust_seeker_url'], command['host'], command['fingerprint'])
if __name__ == "__main__":
main(sys.argv[1:])
Loading…
Cancel
Save