Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if password_required:
# This password is repeatable, but random so long as SECRET_KEY is not compromised
cdata['password'] = cortex.lib.systems.generate_repeatable_password(system['id'])
# Create puppet ENC entry if it does not already exist
if puppet_required:
cdata['certname'] = fqdn
if 'puppet_certname' in system and system['puppet_certname'] is None:
# A system record exists but no puppet_nodes entry. We'll create one!
# We set the environment to what we determined above, which defaults
# to production, but updates from the CMDB
curd = g.db.cursor(mysql.cursors.DictCursor)
curd.execute("INSERT INTO `puppet_nodes` (`id`, `certname`, `env`) VALUES (%s, %s, %s)", (system['id'], fqdn, app.config['PUPPET_DEFAULT_ENVIRONMENT']))
g.db.commit()
app.logger.info('Created Puppet ENC entry for certname "' + fqdn + '"')
# Get the satellite registration key (if any)
if satellite_required:
if ident in app.config['SATELLITE_KEYS']:
data = app.config['SATELLITE_KEYS'][ident]
app.logger.warn("TESTING: USING ENV {} with data {}".format(cdata['environment'], data))
if cdata['environment'] in data:
cdata['satellite_activation_key'] = data[cdata['environment']]
else:
app.logger.warn('No Satellite activation key configured for OS ident, ' + str(ident) + ' with environment ' + cdata['environment'] + ' - a Satellite activation key will not be returned')
else:
app.logger.warn('No Satellite activation keys configured for OS ident (' + str(ident) + ') - a Satellite activation key will not be returned')
if interactive:
cortex.lib.core.log(__name__, "api.register.system", "New system '" + fqdn + "' registered via the API by " + request.form['username'], username=request.form['username'])
else:
def get_users_groups_from_ldap(username):
app.logger.debug("cortex.core.get_users_groups_from_ldap: building cache for " + username)
## connect to LDAP and turn off referals
l = ldap.initialize(app.config['LDAP_URI'])
l.set_option(ldap.OPT_REFERRALS, 0)
## and bind to the server with a username/password if needed in order to search for the full DN for the user who is logging in.
try:
if app.config['LDAP_ANON_BIND']:
l.simple_bind_s()
else:
l.simple_bind_s( (app.config['LDAP_BIND_USER']), (app.config['LDAP_BIND_PW']) )
except ldap.LDAPError as e:
flash('Internal Error - Could not connect to LDAP directory: ' + str(e),'alert-danger')
app.logger.error("Could not bind to LDAP: " + str(e))
abort(500)
app.logger.debug("cortex.core.get_users_groups_from_ldap: searching for username in base " + app.config['LDAP_SEARCH_BASE'] + " looking for attribute " + app.config['LDAP_USER_ATTRIBUTE'])
## Now search for the user object
try:
results = l.search_s(app.config['LDAP_SEARCH_BASE'], ldap.SCOPE_SUBTREE,(app.config['LDAP_USER_ATTRIBUTE']) + "=" + username)
except ldap.LDAPError as e:
app.logger.debug("cortex.core.get_users_groups_from_ldap: no user object found")
return None
app.logger.debug("cortex.core.get_users_groups_from_ldap: found user object")
## handle the search results
for result in results:
dn = result[0]
if not does_user_have_permission("systems.all.view") and not does_user_have_permission("systems.all.edit.cmdb"):
if not does_user_have_any_system_permission("edit.cmdb"):
abort(403)
# Extract information from DataTables
(draw, start, length, order_column, order_asc, search) = _systems_extract_datatables()
# Validate and convert the ordering column number to the name of the
# column as it is in the database
if order_column == 0:
order_column = 'u_number'
elif order_column == 1:
order_column = 'short_description'
else:
app.logger.warn('Invalid ordering column parameter in DataTables request')
abort(400)
# Get results of query
total_count = cortex.lib.cmdb.get_ci_count()
filtered_count = cortex.lib.cmdb.get_ci_count(search)
results = cortex.lib.cmdb.get_cis(start, length, search, order_column, order_asc)
system_data = []
for row in results:
system_data.append([row['u_number'], row['name'], row['sys_id']])
# Return JSON data in the format DataTables wants
return jsonify(draw=draw, recordsTotal=total_count, recordsFiltered=filtered_count, data=system_data)
def add_permission(self, name, desc):
if not name.startswith("workflows."):
name = "workflows." + name
app.permissions.add_workflow_permission(name, desc)
app.logger.info("Workflows: Added permission '" + name + "'")
def logerr():
# Get the username
if 'username' in session:
username = session['username']
else:
username = 'Not logged in'
## Log the critical error (so that it goes to e-mail)
app.logger.error("""Request details:
HTTP Host: %s
HTTP Path: %s
HTTP Method: %s
Client IP Address: %s
User Agent: %s
User Platform: %s
User Browser: %s
User Browser Version: %s
Username: %s
Traceback:
%s
""" % (
request.host,
request.path,
def connect():
# Connect to LDAP and turn off referrals
server = ldap3.Server(app.config['LDAP_URI'])
conn = ldap3.Connection(server, app.config['LDAP_BIND_USER'], app.config['LDAP_BIND_PW'], auto_bind=False, auto_referrals=False)
# Bind to the server either with a defined user/pass in the config
try:
assert conn.bind() # Ensure the bind is successful
except (AssertionError, ldap3.core.exceptions.LDAPException) as ex:
flash('Internal Error - Could not connect to LDAP directory: ' + str(ex), 'alert-danger')
app.logger.error("Could not bind to LDAP: " + str(ex))
abort(500)
return conn
endpoint = options.pop('endpoint', None)
# Add a URL rule
app.add_url_rule("/workflows/" + self.name + "/" + rule, endpoint, func, **options)
# Store the workflow route details in a hash for the
app.wf_functions.append({
'title': title,
'name': func.__name__,
'workflow': self.name,
'order': order,
'permission': permission,
'menu': menu,
})
app.logger.info("Workflows: Registered a new workflow function '" + func.__name__ + "' in '" + self.name + "'")
return func
# Validate and convert the ordering column number to the name of the
# column as it is in the database
if order_column == 0:
order_column = 'name'
elif order_column == 1:
order_column = 'allocation_comment'
elif order_column == 2:
order_column = 'cmdb_environment'
elif order_column == 3:
order_column = 'allocation_who'
elif order_column == 4:
order_column = 'allocation_date'
elif order_column == 5:
order_column = 'cmdb_operational_status'
else:
app.logger.warn('Invalid ordering column parameter in DataTables request')
abort(400)
# Validate the system class filter group. This is the name of the
# currently selected tab on the page that narrows down by system
# class, e.g .srv, vhost, etc.
filter_group = None
if 'filter_group' in request.form:
# The filtering on starting with * ignores some special filter groups
if request.form['filter_group'] != '' and request.form['filter_group'][0] != '*':
filter_group = str(request.form['filter_group'])
# Filter group being *OTHER should hide our group names and filter on
only_other = False
if request.form['filter_group'] == '*OTHER':
only_other = True
### they have workflows.all
### they have the per-system permission set in the workflow action
### they have the global permission set in the workflow action
if does_user_have_permission("workflows.all"):
actions.append(action)
elif does_user_have_system_permission(id,action['system_permission']):
app.logger.debug("User " + session['username'] + " does not have workflows.all")
actions.append(action)
elif action['permission'] is not None:
app.logger.debug("User " + session['username'] + " does not have " + action['system_permission'])
if does_user_have_permission("workflows." + action['permission']):
actions.append(action)
else:
app.logger.debug("User " + session['username'] + " does not have " + action['permission'])
return render_template('systems/actions.html', system=system, active='systems', actions=actions, title=system['name'])
def api_puppet_enc(certname):
"""Returns the YAML associated with the given node."""
# The request should contain a parameter in the headers which contains
# the autthentication pre-shared key. Validate this:
if 'X-Auth-Token' not in request.headers:
app.logger.warn('auth_token missing from Puppet ENC API request (certname: ' + certname + ')')
return abort(401)
if request.headers['X-Auth-Token'] != app.config['ENC_API_AUTH_TOKEN']:
app.logger.warn('Incorrect auth_token on request to Puppet ENC API (certname: ' + certname + ')')
return abort(401)
# Check that we've got a valid hostname
if not cortex.lib.core.is_valid_hostname(certname):
app.logger.warn('Invalid certname presented to Puppet ENC API (certname: ' + certname + ')')
abort(400)
# Generate the Puppet configuration
node_yaml = cortex.lib.puppet.generate_node_config(certname)
# If we don't get any configuration, return 404
if node_yaml is None:
return abort(404)
# Make a response and return it
r = make_response(node_yaml)