def _create_searchtemplate(self, name, user): """Create a search template in the database. Args: name: Name of the view (string) user: A user (instance of timesketch.models.user.User) Returns: A search template (timesketch.models.sketch.SearchTemplate) """ searchtemplate = SearchTemplate( name=name, query_string=name, query_filter=json.dumps(dict()), user=user ) self._commit_to_database(searchtemplate) return searchtemplate
def create_view_from_form(sketch, form): """Creates a view from form data. Args: sketch: Instance of timesketch.models.sketch.Sketch form: Instance of timesketch.lib.forms.SaveViewForm Returns: A view (Instance of timesketch.models.sketch.View) """ # Default to user supplied data view_name = form.name.data query_string = form.query.data query_filter = json.dumps(form.filter.data, ensure_ascii=False), query_dsl = json.dumps(form.dsl.data, ensure_ascii=False) # WTF forms turns the filter into a tuple for some reason. # pylint: disable=redefined-variable-type if isinstance(query_filter, tuple): query_filter = query_filter[0] # No search template by default (before we know if the user want to # create a template or use an existing template when creating the view) searchtemplate = None # Create view from a search template if form.from_searchtemplate_id.data: # Get the template from the datastore template_id = form.from_searchtemplate_id.data searchtemplate = SearchTemplate.query.get(template_id) # Copy values from the template view_name = searchtemplate.name query_string = searchtemplate.query_string query_filter = searchtemplate.query_filter, query_dsl = searchtemplate.query_dsl # WTF form returns a tuple for the filter. This is not # compatible with SQLAlchemy. if isinstance(query_filter, tuple): query_filter = query_filter[0] # Create a new search template based on this view (only if requested by # the user). if form.new_searchtemplate.data: query_filter_dict = json.loads(query_filter) if query_filter_dict.get(u'indices', None): query_filter_dict[u'indices'] = u'_all' # pylint: disable=redefined-variable-type query_filter = json.dumps(query_filter_dict, ensure_ascii=False) searchtemplate = SearchTemplate(name=view_name, user=current_user, query_string=query_string, query_filter=query_filter, query_dsl=query_dsl) db_session.add(searchtemplate) db_session.commit() # Create the view in the database view = View(name=view_name, sketch=sketch, user=current_user, query_string=query_string, query_filter=query_filter, query_dsl=query_dsl, searchtemplate=searchtemplate) db_session.add(view) db_session.commit() return view
def run(self, import_location, export_location): """Export/Import search templates to/from file. Args: import_location: Path to the yaml file to import templates. export_location: Path to the yaml file to export templates. """ if export_location: search_templates = [] for search_template in SearchTemplate.query.all(): labels = [] for label in search_template.labels: if label.label.startswith('supported_os:'): labels.append(label.label.replace('supported_os:', '')) search_templates.append({ 'name': search_template.name, 'query_string': search_template.query_string, 'query_dsl': search_template.query_dsl, 'supported_os': labels }) with open(export_location, 'w') as fh: yaml.safe_dump(search_templates, stream=fh) if import_location: try: with open(import_location, 'rb') as fh: search_templates = yaml.safe_load(fh) except IOError as e: sys.stdout.write('Unable to open file: {0!s}\n'.format(e)) sys.exit(1) for search_template in search_templates: name = search_template['name'] query_string = search_template['query_string'] query_dsl = search_template['query_dsl'] # Skip search template if already exits. if SearchTemplate.query.filter_by(name=name).first(): continue imported_template = SearchTemplate(name=name, user=User(None), query_string=query_string, query_dsl=query_dsl) # Add supported_os labels. for supported_os in search_template['supported_os']: label_name = 'supported_os:{0:s}'.format(supported_os) label = SearchTemplate.Label.get_or_create( label=label_name, user=None) imported_template.labels.append(label) # Set flag to identify local vs import templates. remote_flag = SearchTemplate.Label.get_or_create( label='remote_template', user=None) imported_template.labels.append(remote_flag) db_session.add(imported_template) db_session.commit()
def post(self): """Handles POST request to the resource. Returns: View in JSON (instance of flask.wrappers.Response) """ form = request.json if not form: form = request.data search_id = form.get('search_id') if not search_id: abort( HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to save the searchtemplate, the saved search ID is ' 'missing.') search_obj = View.query.get(search_id) if not search_obj: abort(HTTP_STATUS_CODE_NOT_FOUND, 'No search found with this ID.') templates = SearchTemplate.query.filter_by( name=search_obj.name, description=search_obj.description).all() if templates: abort(HTTP_STATUS_CODE_BAD_REQUEST, 'This search has already been saved as a template.') sketch = Sketch.query.get_with_acl(search_obj.sketch.id) if not sketch: abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.') if not sketch.has_permission(current_user, 'read'): abort(HTTP_STATUS_CODE_FORBIDDEN, 'User does not have read access controls on sketch.') if sketch.get_status.status == 'archived': abort(HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to query on an archived sketch.') # Remove date filter chips from the saved search. query_filter_dict = json.loads(search_obj.query_filter) chips = [] for chip in query_filter_dict.get('chips', []): chip_type = chip.get('type', '') if not chip_type.startswith('datetime'): chips.append(chip) query_filter_dict['chips'] = chips query_filter = json.dumps(query_filter_dict, ensure_ascii=False) searchtemplate = SearchTemplate(name=search_obj.name, description=search_obj.description, user=current_user, query_string=search_obj.query_string, query_filter=query_filter, query_dsl=search_obj.query_dsl) db_session.add(searchtemplate) db_session.commit() search_obj.searchtemplate = searchtemplate db_session.add(search_obj) db_session.commit() return self.to_json(searchtemplate)
def create_view_from_form(sketch, form): """Creates a view from form data. Args: sketch: Instance of timesketch.models.sketch.Sketch form: Instance of timesketch.lib.forms.SaveViewForm Returns: A view (Instance of timesketch.models.sketch.View) """ # Default to user supplied data view_name = form.name.data query_string = form.query.data query_filter_dict = form.filter.data # Stripping potential pagination from views before saving it. if 'from' in query_filter_dict: del query_filter_dict['from'] query_filter = json.dumps(query_filter_dict, ensure_ascii=False) query_dsl = json.dumps(form.dsl.data, ensure_ascii=False) if isinstance(query_filter, tuple): query_filter = query_filter[0] # No search template by default (before we know if the user want to # create a template or use an existing template when creating the view) searchtemplate = None # Create view from a search template if form.from_searchtemplate_id.data: # Get the template from the datastore template_id = form.from_searchtemplate_id.data searchtemplate = SearchTemplate.query.get(template_id) # Copy values from the template view_name = searchtemplate.name query_string = searchtemplate.query_string query_filter = searchtemplate.query_filter query_dsl = searchtemplate.query_dsl # WTF form returns a tuple for the filter. This is not # compatible with SQLAlchemy. if isinstance(query_filter, tuple): query_filter = query_filter[0] if not view_name: abort(HTTP_STATUS_CODE_BAD_REQUEST, 'View name is missing.') # Create a new search template based on this view (only if requested by # the user). if form.new_searchtemplate.data: query_filter_dict = json.loads(query_filter) if query_filter_dict.get('indices', None): query_filter_dict['indices'] = '_all' query_filter = json.dumps(query_filter_dict, ensure_ascii=False) searchtemplate = SearchTemplate(name=view_name, user=current_user, query_string=query_string, query_filter=query_filter, query_dsl=query_dsl) db_session.add(searchtemplate) db_session.commit() # Create the view in the database view = View(name=view_name, sketch=sketch, user=current_user, query_string=query_string, query_filter=query_filter, query_dsl=query_dsl, searchtemplate=searchtemplate) db_session.add(view) db_session.commit() return view