/* apps/ciphers.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include #include #include #ifdef OPENSSL_NO_STDIO #define APPS_WIN16 #endif #include "apps.h" #include #include #undef PROG #define PROG ciphers_main static const char *ciphers_usage[]={ "usage: ciphers args\n", " -v - verbose mode, a textual listing of the ciphers in SSLeay\n", " -ssl2 - SSL2 mode\n", " -ssl3 - SSL3 mode\n", " -tls1 - TLS1 mode\n", NULL }; int MAIN(int, char **); int MAIN(int argc, char **argv) { int ret=1,i; int verbose=0; const char **pp; const char *p; int badops=0; SSL_CTX *ctx=NULL; SSL *ssl=NULL; char *ciphers=NULL; SSL_METHOD *meth=NULL; STACK_OF(SSL_CIPHER) *sk; char buf[512]; BIO *STDout=NULL; #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) meth=SSLv23_server_method(); #elif !defined(OPENSSL_NO_SSL3) meth=SSLv3_server_method(); #elif !defined(OPENSSL_NO_SSL2) meth=SSLv2_server_method(); #endif apps_startup(); if (bio_err == NULL) bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); STDout=BIO_new_fp(stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); STDout = BIO_push(tmpbio, STDout); } #endif argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-v") == 0) verbose=1; #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv,"-ssl2") == 0) meth=SSLv2_client_method(); #endif #ifndef OPENSSL_NO_SSL3 else if (strcmp(*argv,"-ssl3") == 0) meth=SSLv3_client_method(); #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv,"-tls1") == 0) meth=TLSv1_client_method(); #endif else if ((strncmp(*argv,"-h",2) == 0) || (strcmp(*argv,"-?") == 0)) { badops=1; break; } else { ciphers= *argv; } argc--; argv++; } if (badops) { for (pp=ciphers_usage; (*pp != NULL); pp++) BIO_printf(bio_err,"%s",*pp); goto end; } OpenSSL_add_ssl_algorithms(); ctx=SSL_CTX_new(meth); if (ctx == NULL) goto err; if (ciphers != NULL) { if(!SSL_CTX_set_cipher_list(ctx,ciphers)) { BIO_printf(bio_err, "Error in cipher list\n"); goto err; } } ssl=SSL_new(ctx); if (ssl == NULL) goto err; if (!verbose) { for (i=0; ; i++) { p=SSL_get_cipher_list(ssl,i); if (p == NULL) break; if (i != 0) BIO_printf(STDout,":"); BIO_printf(STDout,"%s",p); } BIO_printf(STDout,"\n"); } else { sk=SSL_get_ciphers(ssl); for (i=0; i99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
"""
IR database daemon.

Usage: python irdbd.py [ { -c | --config } configfile ] [ { -h | --help } ]

This is the old (pre-Django) version of irdbd, still used by smoketest
and perhaps still useful as a minimal example.

$Id$

Copyright (C) 2009--2012  Internet Systems Consortium ("ISC")

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

Portions copyright (C) 2007--2008  American Registry for Internet Numbers ("ARIN")

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND ARIN DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS.  IN NO EVENT SHALL ARIN BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""

import sys
import os
import time
import getopt
import urlparse
import rpki.http
import rpki.config
import rpki.resource_set
import rpki.relaxng
import rpki.exceptions
import rpki.left_right
import rpki.log
import rpki.x509

from rpki.mysql_import import MySQLdb

class main(object):


  def handle_list_resources(self, q_pdu, r_msg):

    r_pdu = rpki.left_right.list_resources_elt()
    r_pdu.tag = q_pdu.tag
    r_pdu.self_handle = q_pdu.self_handle
    r_pdu.child_handle = q_pdu.child_handle

    self.cur.execute(
      "SELECT registrant_id, valid_until FROM registrant WHERE registry_handle = %s AND registrant_handle = %s",
      (q_pdu.self_handle, q_pdu.child_handle))

    if self.cur.rowcount != 1:
      raise rpki.exceptions.NotInDatabase, \
            "This query should have produced a single exact match, something's messed up (rowcount = %d, self_handle = %s, child_handle = %s)" \
            % (self.cur.rowcount, q_pdu.self_handle, q_pdu.child_handle)

    registrant_id, valid_until = self.cur.fetchone()

    r_pdu.valid_until = valid_until.strftime("%Y-%m-%dT%H:%M:%SZ")

    r_pdu.asn  = rpki.resource_set.resource_set_as.from_sql(
      self.cur,
      "SELECT start_as, end_as FROM registrant_asn WHERE registrant_id = %s",
      (registrant_id,))

    r_pdu.ipv4 = rpki.resource_set.resource_set_ipv4.from_sql(
      self.cur,
      "SELECT start_ip, end_ip FROM registrant_net WHERE registrant_id = %s AND version = 4",
      (registrant_id,))

    r_pdu.ipv6 = rpki.resource_set.resource_set_ipv6.from_sql(
      self.cur,
      "SELECT start_ip, end_ip FROM registrant_net WHERE registrant_id = %s AND version = 6",
      (registrant_id,))

    r_msg.append(r_pdu)


  def handle_list_roa_requests(self, q_pdu, r_msg):

    self.cur.execute(
      "SELECT roa_request_id, asn FROM roa_request WHERE roa_request_handle = %s",
      (q_pdu.self_handle,))

    for roa_request_id, asn in self.cur.fetchall():

      r_pdu = rpki.left_right.list_roa_requests_elt()
      r_pdu.tag = q_pdu.tag
      r_pdu.self_handle = q_pdu.self_handle
      r_pdu.asn = asn

      r_pdu.ipv4 = rpki.resource_set.roa_prefix_set_ipv4.from_sql(
        self.cur,
        "SELECT prefix, prefixlen, max_prefixlen FROM roa_request_prefix WHERE roa_request_id = %s AND version = 4",
        (roa_request_id,))

      r_pdu.ipv6 = rpki.resource_set.roa_prefix_set_ipv6.from_sql(
        self.cur,
        "SELECT prefix, prefixlen, max_prefixlen FROM roa_request_prefix WHERE roa_request_id = %s AND version = 6",
        (roa_request_id,))

      r_msg.append(r_pdu)


  def handle_list_ghostbuster_requests(self, q_pdu, r_msg):

    self.cur.execute(
      "SELECT vcard  FROM ghostbuster_request WHERE self_handle = %s AND parent_handle = %s",
      (q_pdu.self_handle, q_pdu.parent_handle))

    vcards = [result[0] for result in self.cur.fetchall()]

    if not vcards:

      self.cur.execute(
        "SELECT vcard  FROM ghostbuster_request WHERE self_handle = %s AND parent_handle IS NULL",
        (q_pdu.self_handle,))

      vcards = [result[0] for result in self.cur.fetchall()]

    for vcard in vcards:
      r_pdu = rpki.left_right.list_ghostbuster_requests_elt()
      r_pdu.tag = q_pdu.tag
      r_pdu.self_handle = q_pdu.self_handle
      r_pdu.parent_handle = q_pdu.parent_handle
      r_pdu.vcard = vcard
      r_msg.append(r_pdu)


  handle_dispatch = {
    rpki.left_right.list_resources_elt            : handle_list_resources,
    rpki.left_right.list_roa_requests_elt         : handle_list_roa_requests,
    rpki.left_right.list_ghostbuster_requests_elt : handle_list_ghostbuster_requests}


  def handler(self, query, path, cb):
    try:

      self.db.ping(True)

      r_msg = rpki.left_right.msg.reply()

      try:

        q_msg = rpki.left_right.cms_msg(DER = query).unwrap((self.bpki_ta, self.rpkid_cert))

        if not isinstance(q_msg, rpki.left_right.msg) or not q_msg.is_query():
          raise rpki.exceptions.BadQuery, "Unexpected %r PDU" % q_msg

        for q_pdu in q_msg:

          try:

            try:
              h = self.handle_dispatch[type(q_pdu)]
            except KeyError:
              raise rpki.exceptions.BadQuery, "Unexpected %r PDU" % q_pdu
            else:
              h(self, q_pdu, r_msg)

          except (rpki.async.ExitNow, SystemExit):
            raise

          except Exception, e:
            rpki.log.traceback()
            r_msg.append(rpki.left_right.report_error_elt.from_exception(e, q_pdu.self_handle, q_pdu.tag))

      except (rpki.async.ExitNow, SystemExit):
        raise

      except Exception, e:
        rpki.log.traceback()
        r_msg.append(rpki.left_right.report_error_elt.from_exception(e))

      cb(200, body = rpki.left_right.cms_msg().wrap(r_msg, self.irdbd_key, self.irdbd_cert))

    except (rpki.async.ExitNow, SystemExit):
      raise

    except Exception, e:
      rpki.log.traceback()

      # We only get here in cases where we couldn't or wouldn't generate
      # <report_error/>, so just return HTTP failure.

      cb(500, reason = "Unhandled exception %s: %s" % (e.__class__.__name__, e))


  def __init__(self):

    os.environ["TZ"] = "UTC"
    time.tzset()

    cfg_file = None

    opts, argv = getopt.getopt(sys.argv[1:], "c:dh?", ["config=", "debug", "help"])
    for o, a in opts:
      if o in ("-h", "--help", "-?"):
        print __doc__
        sys.exit(0)
      if o in ("-c", "--config"):
        cfg_file = a
      elif o in ("-d", "--debug"):
        rpki.log.use_syslog = False
    if argv:
      raise rpki.exceptions.CommandParseFailure, "Unexpected arguments %s" % argv

    rpki.log.init("irdbd")

    self.cfg = rpki.config.parser(cfg_file, "irdbd")

    startup_msg = self.cfg.get("startup-message", "")
    if startup_msg:
      rpki.log.info(startup_msg)

    self.cfg.set_global_flags()

    self.db = MySQLdb.connect(user   = self.cfg.get("sql-username"),
                              db     = self.cfg.get("sql-database"),
                              passwd = self.cfg.get("sql-password"))

    self.cur = self.db.cursor()
    self.db.autocommit(True)

    self.bpki_ta         = rpki.x509.X509(Auto_update = self.cfg.get("bpki-ta"))
    self.rpkid_cert      = rpki.x509.X509(Auto_update = self.cfg.get("rpkid-cert"))
    self.irdbd_cert      = rpki.x509.X509(Auto_update = self.cfg.get("irdbd-cert"))
    self.irdbd_key       = rpki.x509.RSA( Auto_update = self.cfg.get("irdbd-key"))

    u = urlparse.urlparse(self.cfg.get("http-url"))

    assert u.scheme in ("", "http") and \
           u.username is None and \
           u.password is None and \
           u.params   == "" and \
           u.query    == "" and \
           u.fragment == ""

    rpki.http.server(host         = u.hostname or "localhost",
                     port         = u.port or 443,
                     handlers     = ((u.path, self.handler),))