def main(client_id, user_arguments_dict): """Main function used by front end""" (configuration, logger, output_objects, op_name) = \ initialize_main_variables(client_id, op_header=False, op_menu=False) defaults = signature()[1] (validate_status, accepted) = validate_input(user_arguments_dict, defaults, output_objects, allow_rejects=False) if not validate_status: logger.warning('%s invalid input: %s' % (op_name, accepted)) return (accepted, returnvalues.CLIENT_ERROR) if not correct_handler('POST'): output_objects.append( {'object_type': 'error_text', 'text' : 'Only accepting POST requests to prevent unintended updates'}) return (output_objects, returnvalues.CLIENT_ERROR) title_entry = find_entry(output_objects, 'title') title_entry['text'] = '%s certificate request' % configuration.short_title title_entry['skipmenu'] = True output_objects.append({'object_type': 'header', 'text' : '%s certificate request' % \ configuration.short_title }) admin_email = configuration.admin_email smtp_server = configuration.smtp_server user_pending = os.path.abspath(configuration.user_pending) # force name to capitalized form (henrik karlsen -> Henrik Karlsen) # please note that we get utf8 coded bytes here and title() treats such # chars as word termination. Temporarily force to unicode. raw_name = accepted['cert_name'][-1].strip() try: cert_name = force_utf8(force_unicode(raw_name).title()) except Exception: cert_name = raw_name.title() country = accepted['country'][-1].strip().upper() state = accepted['state'][-1].strip().title() org = accepted['org'][-1].strip() # lower case email address email = accepted['email'][-1].strip().lower() password = accepted['password'][-1] verifypassword = accepted['verifypassword'][-1] # keep comment to a single line comment = accepted['comment'][-1].replace('\n', ' ') # single quotes break command line format - remove comment = comment.replace("'", ' ') if password != verifypassword: output_objects.append({'object_type': 'error_text', 'text' : 'Password and verify password are not identical!' }) return (output_objects, returnvalues.CLIENT_ERROR) # TODO: move this check to conf? if not forced_org_email_match(org, email, configuration): output_objects.append({'object_type': 'error_text', 'text' : '''Illegal email and organization combination: Please read and follow the instructions in red on the request page! If you are a student with only a @*.ku.dk address please just use KU as organization. As long as you state that you want the certificate for course purposes in the comment field, you will be given access to the necessary resources anyway. '''}) return (output_objects, returnvalues.CLIENT_ERROR) user_dict = { 'full_name': cert_name, 'organization': org, 'state': state, 'country': country, 'email': email, 'comment': comment, 'password': base64.b64encode(password), 'expire': int(time.time() + cert_valid_days * 24 * 60 * 60), 'openid_names': [], } fill_distinguished_name(user_dict) user_id = user_dict['distinguished_name'] user_dict['authorized'] = (user_id == client_id) if configuration.user_openid_providers and configuration.user_openid_alias: user_dict['openid_names'] += \ [user_dict[configuration.user_openid_alias]] logger.info('got reqcert request: %s' % user_dict) # For testing only if cert_name.upper().find('DO NOT SEND') != -1: output_objects.append({'object_type': 'text', 'text' : "Test request ignored!"}) return (output_objects, returnvalues.OK) req_path = None try: (os_fd, req_path) = tempfile.mkstemp(dir=user_pending) os.write(os_fd, dumps(user_dict)) os.close(os_fd) except Exception, err: logger.error('Failed to write certificate request to %s: %s' % (req_path, err)) output_objects.append({'object_type': 'error_text', 'text' : 'Request could not be sent to grid administrators. Please contact them manually on %s if this error persists.' % admin_email}) return (output_objects, returnvalues.SYSTEM_ERROR)
# Encode password if not already encoded try: base64.b64decode(user_dict['password']) except TypeError: user_dict['password'] = base64.b64encode(user_dict['password']) # Default to one year of certificate validity (only used by CA scripts) if not user_dict.has_key('expire'): user_dict['expire'] = int(time.time() + cert_valid_days * 24 * 60 * 60) if user_id: user_dict['distinguished_name'] = user_id elif not user_dict.has_key('distinguished_name'): fill_distinguished_name(user_dict) fill_user(user_dict) # Now all user fields are set and we can begin adding the user if verbose: print 'using user dict: %s' % user_dict try: create_user(user_dict, conf_path, db_path, force, verbose, ask_renew, default_renew) except Exception, exc: print exc sys.exit(1) print 'Created or updated %s in user database and in file system' % \ user_dict['distinguished_name']
def main(client_id, user_arguments_dict, environ=None): """Main function used by front end""" if environ is None: environ = os.environ (configuration, logger, output_objects, op_name) = \ initialize_main_variables(client_id, op_header=False, op_menu=False) logger = configuration.logger logger.info('%s: args: %s' % (op_name, user_arguments_dict)) prefilter_map = {} output_objects.append({'object_type': 'header', 'text' : 'Automatic %s sign up' % \ configuration.short_title }) identity = extract_client_openid(configuration, environ, lookup_dn=False) if client_id and client_id == identity: login_type = 'cert' base_url = configuration.migserver_https_cert_url elif identity: login_type = 'oid' base_url = configuration.migserver_https_oid_url for name in ('openid.sreg.cn', 'openid.sreg.fullname', 'openid.sreg.full_name'): prefilter_map[name] = filter_commonname else: output_objects.append( {'object_type': 'error_text', 'text': 'Missing user credentials'}) return (output_objects, returnvalues.CLIENT_ERROR) defaults = signature(login_type)[1] (validate_status, accepted) = validate_input( user_arguments_dict, defaults, output_objects, allow_rejects=False, prefilter_map=prefilter_map) if not validate_status: logger.warning('%s invalid input: %s' % (op_name, accepted)) return (accepted, returnvalues.CLIENT_ERROR) logger.debug('Accepted arguments: %s' % accepted) # Unfortunately OpenID redirect does not use POST if login_type != 'oid' and not correct_handler('POST'): output_objects.append( {'object_type': 'error_text', 'text' : 'Only accepting POST requests to prevent unintended updates'}) return (output_objects, returnvalues.CLIENT_ERROR) admin_email = configuration.admin_email openid_names, oid_extras = [], {} # Extract raw values if login_type == 'cert': uniq_id = accepted['cert_id'][-1].strip() raw_name = accepted['cert_name'][-1].strip() country = accepted['country'][-1].strip() state = accepted['state'][-1].strip() org = accepted['org'][-1].strip() org_unit = '' role = ','.join([i for i in accepted['role'] if i]) locality = '' timezone = '' email = accepted['email'][-1].strip() raw_login = None elif login_type == 'oid': uniq_id = accepted['openid.sreg.nickname'][-1].strip() or \ accepted['openid.sreg.short_id'][-1].strip() raw_name = accepted['openid.sreg.fullname'][-1].strip() or \ accepted['openid.sreg.full_name'][-1].strip() country = accepted['openid.sreg.country'][-1].strip() state = accepted['openid.sreg.state'][-1].strip() org = accepted['openid.sreg.o'][-1].strip() or \ accepted['openid.sreg.organization'][-1].strip() org_unit = accepted['openid.sreg.ou'][-1].strip() or \ accepted['openid.sreg.organizational_unit'][-1].strip() # We may receive multiple roles role = ','.join([i for i in accepted['openid.sreg.role'] if i]) locality = accepted['openid.sreg.locality'][-1].strip() timezone = accepted['openid.sreg.timezone'][-1].strip() email = accepted['openid.sreg.email'][-1].strip() # Fix case of values: # force name to capitalized form (henrik karlsen -> Henrik Karlsen) # please note that we get utf8 coded bytes here and title() treats such # chars as word termination. Temporarily force to unicode. try: full_name = force_utf8(force_unicode(raw_name).title()) except Exception: logger.warning("could not use unicode form to capitalize full name") full_name = raw_name.title() country = country.upper() state = state.upper() email = email.lower() if login_type == 'oid': # Remap some oid attributes if on kit format with faculty in # organization and institute in organizational_unit. We can add them # as different fields as long as we make sure the x509 fields are # preserved. # We do that to allow autocreate updating existing cert users. if org_unit not in ('', 'NA'): org_unit = org_unit.upper() oid_extras['faculty'] = org oid_extras['institute'] = org_unit org = org_unit.upper() org_unit = 'NA' # Stay on virtual host - extra useful while we test dual OpenID base_url = environ.get('REQUEST_URI', base_url).split('?')[0].replace('autocreate', 'fileman') raw_login = None for oid_provider in configuration.user_openid_providers: openid_prefix = oid_provider.rstrip('/') + '/' if identity.startswith(openid_prefix): raw_login = identity.replace(openid_prefix, '') break if raw_login: openid_names.append(raw_login) # we should have the proxy file read... proxy_content = accepted['proxy_upload'][-1] # keep comment to a single line comment = accepted['comment'][-1].replace('\n', ' ') # single quotes break command line format - remove comment = comment.replace("'", ' ') user_dict = { 'short_id': uniq_id, 'full_name': full_name, 'organization': org, 'organizational_unit': org_unit, 'locality': locality, 'state': state, 'country': country, 'email': email, 'role': role, 'timezone': timezone, 'password': '', 'comment': '%s: %s' % ('Existing certificate', comment), 'openid_names': openid_names, } user_dict.update(oid_extras) # We must receive some ID from the provider if not uniq_id and not email: output_objects.append( {'object_type': 'error_text', 'text' : 'No ID information received!'}) if accepted.get('openid.sreg.required', '') and \ identity: # Stay on virtual host - extra useful while we test dual OpenID url = environ.get('REQUEST_URI', base_url).split('?')[0].replace('autocreate', 'logout') output_objects.append( {'object_type': 'text', 'text': '''Please note that sign-up for OpenID access does not work if you are already signed in with your OpenID provider - and that appears to be the case now. You probably have to reload this page after you explicitly '''}) output_objects.append( {'object_type': 'link', 'destination': url, 'target': '_blank', 'text': "Logout" }) return (output_objects, returnvalues.CLIENT_ERROR) if login_type == 'cert': user_dict['expire'] = int(time.time() + cert_valid_days * 24 * 60 * 60) try: distinguished_name_to_user(uniq_id) user_dict['distinguished_name'] = uniq_id except: output_objects.append({'object_type': 'error_text', 'text' : '''Illegal Distinguished name: Please note that the distinguished name must be a valid certificate DN with multiple "key=val" fields separated by "/". '''}) return (output_objects, returnvalues.CLIENT_ERROR) elif login_type == 'oid': user_dict['expire'] = int(time.time() + oid_valid_days * 24 * 60 * 60) fill_distinguished_name(user_dict) uniq_id = user_dict['distinguished_name'] # If server allows automatic addition of users with a CA validated cert # we create the user immediately and skip mail if login_type == 'cert' and configuration.auto_add_cert_user or \ login_type == 'oid' and configuration.auto_add_oid_user: fill_user(user_dict) logger.info('create user: %s' % user_dict) # Now all user fields are set and we can begin adding the user db_path = os.path.join(configuration.mig_server_home, user_db_filename) try: create_user(user_dict, configuration.config_file, db_path, ask_renew=False, default_renew=True) if configuration.site_enable_griddk and \ accepted['proxy_upload'] != ['']: # save the file, display expiration date proxy_out = handle_proxy(proxy_content, uniq_id, configuration) output_objects.extend(proxy_out) except Exception, err: logger.error('create failed for %s: %s' % (uniq_id, err)) output_objects.append( {'object_type': 'error_text', 'text' : '''Could not create the user account for you: Please report this problem to the grid administrators (%s).''' % \ admin_email}) return (output_objects, returnvalues.SYSTEM_ERROR) output_objects.append({'object_type': 'html_form', 'text' : '''Created the user account for you - please open <a href="%s">your personal page</a> to proceed using it. ''' % base_url}) return (output_objects, returnvalues.OK)
def main(client_id, user_arguments_dict): """Main function used by front end""" (configuration, logger, output_objects, op_name) = initialize_main_variables( client_id, op_header=False, op_menu=False ) defaults = signature()[1] logger.debug("in extoidaction: %s" % user_arguments_dict) (validate_status, accepted) = validate_input(user_arguments_dict, defaults, output_objects, allow_rejects=False) if not validate_status: return (accepted, returnvalues.CLIENT_ERROR) # Unfortunately OpenID does not use POST # if not correct_handler('GET'): # output_objects.append( # {'object_type': 'error_text', 'text' # : 'Only accepting POST requests to prevent unintended updates'}) # return (output_objects, returnvalues.CLIENT_ERROR) title_entry = find_entry(output_objects, "title") title_entry["text"] = "%s OpenID sign up" % configuration.short_title title_entry["skipmenu"] = True output_objects.append({"object_type": "header", "text": "%s OpenID sign up" % configuration.short_title}) admin_email = configuration.admin_email smtp_server = configuration.smtp_server user_pending = os.path.abspath(configuration.user_pending) # force name to capitalized form (henrik karlsen -> Henrik Karlsen) id_url = os.environ["REMOTE_USER"].strip() openid_prefix = configuration.user_openid_providers[0].rstrip("/") + "/" raw_login = id_url.replace(openid_prefix, "") full_name = accepted["openid.sreg.full_name"][-1].strip().title() country = accepted["openid.sreg.country"][-1].strip().upper() state = accepted["state"][-1].strip().title() organization = accepted["openid.sreg.organization"][-1].strip() organizational_unit = accepted["openid.sreg.organizational_unit"][-1].strip() locality = accepted["openid.sreg.locality"][-1].strip() # lower case email address email = accepted["openid.sreg.email"][-1].strip().lower() password = accepted["password"][-1] # verifypassword = accepted['verifypassword'][-1] # keep comment to a single line comment = accepted["comment"][-1].replace("\n", " ") # single quotes break command line format - remove comment = comment.replace("'", " ") user_dict = { "full_name": full_name, "organization": organization, "organizational_unit": organizational_unit, "locality": locality, "state": state, "country": country, "email": email, "password": password, "comment": comment, "expire": int(time.time() + oid_valid_days * 24 * 60 * 60), "openid_names": [raw_login], } fill_distinguished_name(user_dict) user_id = user_dict["distinguished_name"] if configuration.user_openid_providers and configuration.user_openid_alias: user_dict["openid_names"].append(user_dict[configuration.user_openid_alias]) req_path = None try: (os_fd, req_path) = tempfile.mkstemp(dir=user_pending) os.write(os_fd, dumps(user_dict)) os.close(os_fd) except Exception, err: logger.error("Failed to write certificate request to %s: %s" % (req_path, err)) output_objects.append( { "object_type": "error_text", "text": "Request could not be sent to grid administrators. Please contact them manually on %s if this error persists." % admin_email, } ) return (output_objects, returnvalues.SYSTEM_ERROR)
def main(client_id, user_arguments_dict): """Main function used by front end""" (configuration, logger, output_objects, op_name) = \ initialize_main_variables(client_id, op_header=False) output_objects.append({'object_type': 'header', 'text' : '%s external certificate sign up' % \ configuration.short_title }) defaults = signature()[1] (validate_status, accepted) = validate_input_and_cert( user_arguments_dict, defaults, output_objects, client_id, configuration, allow_rejects=False, require_user=False ) if not validate_status: logger.warning('%s invalid input: %s' % (op_name, accepted)) return (accepted, returnvalues.CLIENT_ERROR) if not correct_handler('POST'): output_objects.append( {'object_type': 'error_text', 'text' : 'Only accepting POST requests to prevent unintended updates'}) return (output_objects, returnvalues.CLIENT_ERROR) admin_email = configuration.admin_email smtp_server = configuration.smtp_server user_pending = os.path.abspath(configuration.user_pending) cert_id = accepted['cert_id'][-1].strip() # force name to capitalized form (henrik karlsen -> Henrik Karlsen) # please note that we get utf8 coded bytes here and title() treats such # chars as word termination. Temporarily force to unicode. raw_name = accepted['cert_name'][-1].strip() try: cert_name = force_utf8(force_unicode(raw_name).title()) except Exception: cert_name = raw_name.title() country = accepted['country'][-1].strip().upper() state = accepted['state'][-1].strip().title() org = accepted['org'][-1].strip() # lower case email address email = accepted['email'][-1].strip().lower() # keep comment to a single line comment = accepted['comment'][-1].replace('\n', ' ') # single quotes break command line format - remove comment = comment.replace("'", ' ') is_diku_email = False is_diku_org = False if email.find('@diku.dk') != -1: is_diku_email = True if 'DIKU' == org.upper(): # Consistent upper casing org = org.upper() is_diku_org = True if is_diku_org != is_diku_email: output_objects.append({'object_type': 'error_text', 'text' : '''Illegal email and organization combination: Please read and follow the instructions in red on the request page! If you are a DIKU student with only a @*.ku.dk address please just use KU as organization. As long as you state that you want the certificate for DIKU purposes in the comment field, you will be given access to the necessary resources anyway. '''}) return (output_objects, returnvalues.CLIENT_ERROR) try: distinguished_name_to_user(cert_id) except: output_objects.append({'object_type': 'error_text', 'text' : '''Illegal Distinguished name: Please note that the distinguished name must be a valid certificate DN with multiple "key=val" fields separated by "/". '''}) return (output_objects, returnvalues.CLIENT_ERROR) user_dict = { 'distinguished_name': cert_id, 'full_name': cert_name, 'organization': org, 'state': state, 'country': country, 'email': email, 'password': '', 'comment': '%s: %s' % ('Existing certificate', comment), 'expire': int(time.time() + cert_valid_days * 24 * 60 * 60), 'openid_names': [], } fill_distinguished_name(user_dict) user_id = user_dict['distinguished_name'] if configuration.user_openid_providers and configuration.user_openid_alias: user_dict['openid_names'] += \ [user_dict[configuration.user_openid_alias]] logger.info('got extcert request: %s' % user_dict) # If server allows automatic addition of users with a CA validated cert # we create the user immediately and skip mail if configuration.auto_add_cert_user: fill_user(user_dict) # Now all user fields are set and we can begin adding the user db_path = os.path.join(configuration.mig_server_home, user_db_filename) try: create_user(user_dict, configuration.config_file, db_path, ask_renew=False) except Exception, err: logger.error('Failed to create user with existing cert %s: %s' % (cert_id, err)) output_objects.append( {'object_type': 'error_text', 'text' : '''Could not create the user account for you: Please report this problem to the grid administrators (%s).''' % \ admin_email}) return (output_objects, returnvalues.SYSTEM_ERROR) output_objects.append({'object_type': 'text', 'text' : '''Created the user account for you: Please use the navigation menu to the left to proceed using it. '''}) return (output_objects, returnvalues.OK)