Exemplo n.º 1
0
def getProxyIdFromProxy(proxyPath):
    """
    Returns ID of proxy at the given path.

    Args:
        proxyPath: A string with path to the proxy.

    Raises:
        NoSuchProxyError: Proxy with DN and attributes of the proxy given
            in proxy path is not in the database.
        NoProxyFileError: No proxy on given path.
    """
    manager = proxymgr.ProxyManager()
    try:
        return manager.getProxyIdForProxyFile(proxyPath)
    except NoSuchProxyError as e:
        print("error: no proxy for DN=\"{}\" and attributes=\"{}\" "\
                "found in database; use actproxy".format(e.dn, e.attribute))
        sys.exit(1)

    except NoProxyFileError as e:
        print("error: no proxy file \"{}\"; create proxy first".format(e.path))
        sys.exit(2)

    except ProxyFileExpiredError:
        print("error: proxy has expired; create new proxy")
        sys.exit(3)

    except ProxyDBExpiredError:
        print("error: proxy entry in DB has expired; run actproxy")
        sys.exit(4)
Exemplo n.º 2
0
def submitProxy():
    """
    Submit a proxy certificate of a user.

    This operation requires user to provide personal certificate as
    client certificate in request. Proxy certificate that is to be submitted
    should be provided as raw data in request body.

    Function first verifies user's personal certificate against a
    CA certificate. If verification is successful, it procedes to read proxy
    certificate in body and insert it to database.

    Returns:
        status 200: A string with ID of a proxy certificate.
        status 401 or 500: A string with error message.
    """
    # The following validation procedure is done as per:
    # https://stackoverflow.com/questions/30700348/how-to-validate-verify-an-x509-certificate-chain-of-trust-in-python

    # user pem is client certificate in header
    user_pem = getCertString()
    if not user_pem:
        return 'Wrong or no client certificate', 401

    # get pem for CA
    caPath = os.path.join(os.environ['PATH'].split(':')[-1], 'ca.pem')
    try:
        caFile = open(caPath, 'r')  # TODO: ca.pem in bin directory
    except Exception as e:
        return 'Server error: {}'.format(str(e)), 500
    else:
        root_pem = caFile.read()
        caFile.close()

    # verify
    root_cert = load_certificate(FILETYPE_PEM, root_pem)
    user_cert = load_certificate(FILETYPE_PEM, user_pem)
    store = X509Store()
    store.add_cert(root_cert)
    store_ctx = X509StoreContext(store, user_cert)
    try:
        store_ctx.verify_certificate()
    except Exception as e:
        return 'Client certificate verification failed', 401

    pmgr = proxymgr.ProxyManager()  # TODO: handle error with pmgr and jmgr

    try:
        # TODO: ARC API does not fail when given genproxy script as proxy!!!!
        proxyStr = request.get_data()
        dn, exp_time = pmgr.readProxyString(proxyStr)
        proxyid = pmgr.actproxy.updateProxy(proxyStr, dn, '', exp_time)
    except Exception as e:
        return 'Server error: {}'.format(str(e)), 500
    else:
        return json.dumps(proxyid)
Exemplo n.º 3
0
def getProxies():
    """
    Return information on proxies.

    Currently there are no parameters that would allow users to select which
    columns should be fetched from table.

    Returns:
        JSON list of JSON objects with proxy information (status 200).
    """
    dn = getCertDN()
    pmgr = proxymgr.ProxyManager()
    proxies = pmgr.getProxiesWithDN(dn, columns=['id', 'attribute'])
    return json.dumps(proxies)
Exemplo n.º 4
0
def main():
    # parse arguments
    parser = argparse.ArgumentParser(description='aCT proxies utility')
    parser.add_argument('-p',
                        '--proxy',
                        default=None,
                        help='custom path to proxy')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='show more information')
    args = parser.parse_args()

    # logging
    logFormat = "[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s] - %(message)s"
    if args.verbose:
        logging.basicConfig(format=logFormat,
                            level=logging.DEBUG,
                            stream=sys.stdout)
    else:
        logging.basicConfig(format=logFormat,
                            level=logging.DEBUG,
                            filename=os.devnull)

    # determine proxy file path from args
    if not args.proxy:  # default proxy path is /tmp/x509_u<user id>
        proxyPath = '/tmp/x509up_u' + str(os.getuid())
    else:
        proxyPath = args.proxy

    manager = proxymgr.ProxyManager()
    try:
        manager.updateProxy(proxyPath)
    except NoProxyFileError as e:
        print("error: no proxy file \"{}\"; create proxy first".format(e.path))
    except ProxyFileExpiredError:
        print("error: proxy has expired; create new proxy")
        sys.exit(9)
    except Exception as e:
        print('error: {}'.format(str(e)))
        sys.exit(8)
Exemplo n.º 5
0
def deleteProxies():
    """
    Delete proxies from database.

    Parameter has to be given in url: 'id' which is a list of proxy IDs that
    should be deleted.

    Function first fetches all proxies that match the DN of a certificate
    from request. Then it deletes those whose IDs are in 'id' parameter.
    This is done so that user cannot delete any proxies but his own.

    Returns:
        status 200: A string with a number of deleted proxies.
        status 401: A string with error message.
    """
    dn = getCertDN()
    pmgr = proxymgr.ProxyManager()
    jmgr = jobmgr.JobManager()
    proxies = pmgr.getProxiesWithDN(dn, columns=['id'])

    try:
        proxyids = getIDs()
    except Exception:
        return 'Invalid id parameter', 400
    if not proxyids:
        return 'Wrong or no client certificate', 401

    numDeleted = 0
    for proxy in proxies:
        if proxy['id'] in proxyids:
            # do not remove a proxy on which jobs depend
            if not jmgr.getJobStats(proxy['id'], [], '', '', clicols=['id']):
                pmgr.arcdb.deleteProxy(proxy['id'])
                proxyids.remove(proxy['id'])  # optimize a little bit
                numDeleted += 1
    return json.dumps(numDeleted)
Exemplo n.º 6
0
def getCertDN():
    """Get cert DN from cert in current request context."""
    pmgr = proxymgr.ProxyManager()
    cert = getCertString()
    dn, _ = pmgr.readProxyString(cert)
    return dn
Exemplo n.º 7
0
def getProxyId():
    """Get proxy id from proxy info in current request context."""
    pmgr = proxymgr.ProxyManager()
    dn = getCertDN()
    proxyid = pmgr.getProxyInfo(dn, '', ['id'])['id']
    return proxyid