├── LICENSE ├── Makefile ├── clean.sql ├── create.sql ├── manifest.yml ├── readme.dev.md ├── readme.md ├── requirements.txt ├── scripts └── setup.sql └── streamlit ├── analytics ├── __init__.py ├── leads.py └── overview.py ├── app.py ├── environment.yml ├── helpers.py └── metrics ├── __init__.py ├── query_history.py └── users.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 DuneGroup LLC 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Makefile template for ICE_AXE_APP 2 | 3 | # Default target 4 | all: 5 | snowsql -c ICE_AXE -f create.sql 6 | 7 | # Clean application from Snowflake account 8 | clean: 9 | snowsql -c ICE_AXE -f clean.sql 10 | 11 | dev: 12 | streamlit run streamlit/app.py -- --dev true 13 | 14 | .PHONY: all clean 15 | -------------------------------------------------------------------------------- /clean.sql: -------------------------------------------------------------------------------- 1 | USE APPLICATION PACKAGE ICE_AXE_PACKAGE; 2 | DROP SCHEMA STAGE_CONTENT; 3 | DROP APPLICATION PACKAGE ICE_AXE_PACKAGE; 4 | DROP APPLICATION ICE_AXE_APP; 5 | SHOW APPLICATIONS; -------------------------------------------------------------------------------- /create.sql: -------------------------------------------------------------------------------- 1 | -- Granting privileges to create an application package 2 | GRANT CREATE APPLICATION PACKAGE ON ACCOUNT TO ROLE accountadmin; 3 | 4 | -- Creating a new application package 5 | CREATE APPLICATION PACKAGE ICE_AXE_PACKAGE; 6 | 7 | -- Displaying current application packages 8 | SHOW APPLICATION PACKAGES; 9 | 10 | -- Setting up for application staging 11 | USE APPLICATION PACKAGE ICE_AXE_PACKAGE; 12 | CREATE SCHEMA STAGE_CONTENT; 13 | 14 | -- Creating a stage for the application package 15 | CREATE OR REPLACE STAGE ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_stage 16 | FILE_FORMAT = (TYPE = 'csv' FIELD_DELIMITER = '|' SKIP_HEADER = 1); 17 | 18 | --- Uploading files to the stage, this can only be run from SnowSQL 19 | PUT file://manifest.yml @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE overwrite=true auto_compress=false; 20 | PUT file://scripts/setup.sql @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/scripts overwrite=true auto_compress=false; 21 | 22 | PUT file://streamlit/*.py @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/streamlit overwrite=true auto_compress=false; 23 | PUT file://streamlit/analytics/*.py @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/streamlit/analytics overwrite=true auto_compress=false; 24 | PUT file://streamlit/metrics/*.py @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/streamlit/metrics overwrite=true auto_compress=false; 25 | 26 | -- PUT file://streamlit/app.py @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/streamlit overwrite=true auto_compress=false; 27 | PUT file://streamlit/environment.yml @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE/streamlit overwrite=true auto_compress=false; 28 | PUT file://readme.md @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE overwrite=true auto_compress=false; 29 | 30 | 31 | -- Listing files in the created stage 32 | LIST @ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE; 33 | 34 | -- Installing the application 35 | CREATE APPLICATION ICE_AXE_APP 36 | FROM APPLICATION PACKAGE ICE_AXE_PACKAGE 37 | USING '@ICE_AXE_PACKAGE.STAGE_CONTENT.ICE_AXE_STAGE'; 38 | 39 | -- Verifying the installed applications 40 | SHOW APPLICATIONS; -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | manifest_version: 1 2 | version: 3 | name: ice_axe 4 | label: "v1.0" 5 | comment: "Ice Axe" 6 | 7 | artifacts: 8 | readme: readme.md 9 | setup_script: scripts/setup.sql 10 | extension_code: true 11 | 12 | configuration: 13 | log_level: debug 14 | trace_level: always 15 | 16 | privileges: 17 | - IMPORTED PRIVILEGES ON SNOWFLAKE DB: 18 | description: "To access account_usage views" 19 | -------------------------------------------------------------------------------- /readme.dev.md: -------------------------------------------------------------------------------- 1 | # Instructions 2 | ## Install & Configure SnowSQL 3 | * Download & install [SnowSQL](https://developers.snowflake.com/snowsql/) 4 | * Configure SnowSQL profile "ICE_AXE" in ~/.snowsql/config 5 | ```conf 6 | [connections.ICE_AXE] 7 | accountname = 8 | username = 9 | password = 10 | ``` 11 | 12 | ## Publish the application to Snowflake 13 | * `make` to push the app and install it on the account 14 | * `make clean` to remove the app from the account 15 | 16 | ## Enabling local development mode 17 | `streamlit run streamlit/app.py -- --dev true` or `make dev` -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # ⛏️ Ice Axe 2 | 3 | ## Contributors 4 | Made by [Dune Group](https://github.com/DuneGroup) with ❤️ in California 5 | * [Jacolon Walker](https://github.com/orgs/DuneGroup/people/jwalker) 6 | * [Jacob Salassi](https://github.com/orgs/DuneGroup/people/jacob-salassi) 7 | * [Michele Freschi](https://github.com/orgs/DuneGroup/people/mfreschi-dg) 8 | 9 | 10 | ## Description 11 | Ice Axe is a Snowflake Native Application designed to provide insights into Snowflake account activities that may be potential threats. It enables users to efficiently audit and monitor login history, user activities, and system usage. 12 | 13 | ## Features 14 | - Overview of threat leads and user activity 15 | - Detailed threat leads 16 | - Detailed user activity tracking 17 | 18 | ## Installation and Usage 19 | ### Manual install 20 | #### Pre-requisites 21 | * Download & install [SnowSQL](https://developers.snowflake.com/snowsql/) 22 | * make 23 | * python3.11 24 | * ~/.snowsql/config file containing a connection named "ICE_AXE", used for deployment only 25 | 26 | 27 | #### Prepare 28 | Configure Snowflake connection "ICE_AXE" in ~/.snowsql/config 29 | ```conf 30 | [connections.ICE_AXE] 31 | accountname = ... 32 | username = ... 33 | password = ... 34 | ``` 35 | Run the following commands 36 | ```bash 37 | git clone https://github.com/DuneGroup/ice-axe.git 38 | cd ice-axe 39 | pip install -r requirements.txt 40 | ``` 41 | 42 | #### Deploy to Snowflake account 43 | ```bash 44 | make 45 | ``` 46 | 47 | #### Delete from Snowflake account 48 | ```bash 49 | make clean 50 | ``` 51 | 52 | #### Use 53 | * Log in to your Snowflake snowsight UI 54 | * Click `Data Products` on the sidebar 55 | * Click `Apps` under `Data Products` 56 | * Click `Ice Axe` to launch 57 | 58 | ##### First run only 59 | * Click the ⛨ security icon next to `Manage Access` 60 | * Review and grant requested permissions 61 | 62 | ### Install from the marketplace 63 | Not yet available 64 | 65 | ## Support 66 | For feedback, support or additional information, please contact [us](contact@dunegroup.xyz). 67 | 68 | ## License 69 | This project is licensed under the [Apache](LICENSE). 70 | 71 | ## Note 72 | This application requires and requests specific privileges on Snowflake databases for full functionality. 73 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==2.0.1 2 | pandas==2.2.2 3 | snowflake_connector_python==3.11.0 4 | snowflake_snowpark_python==1.11.1 5 | -------------------------------------------------------------------------------- /scripts/setup.sql: -------------------------------------------------------------------------------- 1 | -- Setup script for the Hello Snowflake! application. 2 | CREATE APPLICATION ROLE app_public; 3 | CREATE SCHEMA IF NOT EXISTS core; 4 | GRANT USAGE ON SCHEMA core TO APPLICATION ROLE app_public; 5 | 6 | CREATE OR ALTER VERSIONED SCHEMA code_schema; 7 | GRANT USAGE ON SCHEMA code_schema TO APPLICATION ROLE app_public; 8 | 9 | 10 | CREATE STREAMLIT code_schema.ICE_AXE_streamlit 11 | FROM '/streamlit' 12 | MAIN_FILE = '/app.py' 13 | ; 14 | 15 | GRANT USAGE ON STREAMLIT code_schema.ICE_AXE_streamlit TO APPLICATION ROLE app_public; 16 | -------------------------------------------------------------------------------- /streamlit/analytics/__init__.py: -------------------------------------------------------------------------------- 1 | from . import (overview, leads) -------------------------------------------------------------------------------- /streamlit/analytics/leads.py: -------------------------------------------------------------------------------- 1 | import streamlit 2 | import logging 3 | 4 | st_logger = logging.getLogger(streamlit.__name__) 5 | 6 | def select_all_flt(query_history_df): 7 | return ( 8 | query_history_df['QUERY_TEXT'].str.contains('select *', False, regex=False) & 9 | (~(query_history_df['QUERY_TEXT'].str.contains('where', False))) 10 | ) 11 | 12 | 13 | def show_tables(query_history_df): 14 | return ( 15 | query_history_df['QUERY_TEXT'].str.contains('SHOW TABLES', False) 16 | ) 17 | 18 | 19 | def create_temp_storage(query_history_df): 20 | return ( 21 | query_history_df['QUERY_TEXT'].str.contains('^SHOW TABLES', False) & 22 | query_history_df['QUERY_TEXT'].str.contains('STORAGE', False) 23 | ) 24 | 25 | 26 | def ten_largest_queries(query_history_df): 27 | return ( 28 | query_history_df['ROWS_PRODUCED'] > 2000 29 | ) 30 | 31 | 32 | def accountadmin_changes(query_history_df): 33 | return ( 34 | (query_history_df['EXECUTION_STATUS'] == 'SUCCESS') & 35 | (query_history_df['QUERY_TYPE'] == 'GRANT') 36 | ) 37 | 38 | 39 | def copy_http(query_history_df): 40 | return ( 41 | query_history_df['QUERY_TEXT'].str.contains('COPY INTO') & 42 | query_history_df['QUERY_TEXT'].str.contains('http') 43 | ) 44 | 45 | 46 | def get_file(query_history_df): 47 | return ( 48 | query_history_df['QUERY_TEXT'].str.contains('GET', False) & 49 | query_history_df['QUERY_TEXT'].str.contains('file:') 50 | ) 51 | 52 | 53 | def copy_into_select_all(query_history_df): 54 | return ( 55 | query_history_df['QUERY_TEXT'].str.contains('^COPY INTO', False) & 56 | query_history_df['QUERY_TEXT'].str.contains('^SELECT *', False) 57 | ) 58 | 59 | 60 | def impactful_modifications(query_history_df): 61 | modifications_keywords = [ 62 | 'create role', 'manage grants', 'create integration','alter integration', 'create share','create account' 63 | ,'monitor usage', 'ownership', 'drop table', 'drop database', 'create stage' 64 | ,'drop stage', 'alter stage', 'create user', 'alter user', 'drop user' 65 | ,'create_network_policy', 'alter_network_policy', 'drop_network_policy', 'copy' 66 | ] 67 | 68 | return ( 69 | (query_history_df['EXECUTION_STATUS'] == 'SUCCESS') & 70 | ~(query_history_df['QUERY_TYPE'].isin(['SELECT', 'SHOW', 'DESCRIBE']).any()) & 71 | (query_history_df['QUERY_TEXT'].str.contains('.*' + '|'.join(modifications_keywords) + '.*', False)) 72 | ) 73 | 74 | 75 | def least_common_app(query_history_df): 76 | rare_apps = query_history_df.groupby('CLIENT_APPLICATION')['SESSION_ID'].nunique().reset_index(name='Session Count') 77 | app_names = rare_apps['CLIENT_APPLICATION'].tolist() 78 | return ( 79 | query_history_df['CLIENT_APPLICATION'].isin(app_names) 80 | ) 81 | 82 | 83 | def frostbite_used(query_history_df): 84 | return ( 85 | query_history_df['CLIENT_APPLICATION'] == 'rapeflake' 86 | ) 87 | 88 | 89 | def dbeaver_used(query_history_df): 90 | return ( 91 | query_history_df['CLIENT_APPLICATION'] == 'DBeaver_DBeaverUltimate' 92 | ) 93 | 94 | 95 | all_threat_leads = [ 96 | { 97 | "name": "select_all_without_where", 98 | "mitre_technique_id": "T1567", 99 | "mitre_technique_description": "Exfiltration Over Web Service", 100 | "description": "select * queries that do not contain a WHERE clause", 101 | "df_filter": select_all_flt 102 | }, 103 | { 104 | "name": "copy_into_select_all", 105 | "mitre_technique_id": "T1567", 106 | "mitre_technique_description": "Exfiltration Over Web Service", 107 | "description": "COPY INTO and select * in a single query.", 108 | "df_filter": copy_into_select_all 109 | }, 110 | { 111 | "name": "show_tables", 112 | "mitre_technique_id": "", 113 | "mitre_technique_description": "Other", 114 | "description": "Performing a show tables query", 115 | "df_filter": show_tables 116 | }, 117 | { 118 | "name": "create_temp_storage", 119 | "mitre_technique_id": "", 120 | "mitre_technique_description": "Other", 121 | "description": "Creation of temporary storage", 122 | "df_filter": create_temp_storage 123 | }, 124 | { 125 | "name": "10_largest_queries", 126 | "mitre_technique_id": "", 127 | "mitre_technique_description": "Other", 128 | "description": "Top 10 largest queries by rows_produced", 129 | "df_filter": ten_largest_queries 130 | }, 131 | { 132 | "name": "dbeaver_used", 133 | "mitre_technique_id": "T1199", 134 | "mitre_technique_description": "Trusted Relationship", 135 | "description": "DBEAVER Usage", 136 | "df_filter": dbeaver_used 137 | }, 138 | { 139 | "name": "accountadmin_changes", 140 | "mitre_technique_id": "T1098", 141 | "mitre_technique_description": "Account Manipulation", 142 | "description": "Role grants", 143 | "df_filter": accountadmin_changes 144 | }, 145 | { 146 | "name": "impactful_modifications", 147 | "mitre_technique_id": "T1484", 148 | "mitre_technique_description": "Domain or Tenant Policy Modification", 149 | "description": "Impactful modifications", 150 | "df_filter": impactful_modifications 151 | }, 152 | { 153 | "name": "least_common_applications_used", 154 | "mitre_technique_id": "", 155 | "mitre_technique_description": "Other", 156 | "description": "Applications by prevelance", 157 | "df_filter": least_common_app 158 | }, 159 | { 160 | "name": "copy_http", 161 | "mitre_technique_id": "T1567", 162 | "mitre_technique_description": "Exfiltration Over Web Service", 163 | "description": "A Query containing COPY INTO and http keyword", 164 | "df_filter": copy_http 165 | }, 166 | { 167 | "name": "get_file", 168 | "mitre_technique_id": "T1567", 169 | "mitre_technique_description": "Exfiltration Over Web Service", 170 | "description": "Get file contents", 171 | "df_filter": get_file 172 | }, 173 | { 174 | "name": "session_usage", 175 | "mitre_technique_id": "T1199", 176 | "mitre_technique_description": "Trusted Relationship", 177 | "description": "Session usage", 178 | "df_filter": least_common_app 179 | }, 180 | { 181 | "name": "frostbite_used", 182 | "mitre_technique_id": "T1199", 183 | "mitre_technique_description": "Trusted Relationship", 184 | "description": "FROSTBITE usage", 185 | "df_filter": frostbite_used 186 | } 187 | ] 188 | 189 | 190 | def get_all_leads_names(): 191 | return [lead['name'] for lead in all_threat_leads] 192 | 193 | 194 | def get_all_leads_techniques(): 195 | techniques = [lead['mitre_technique_description'] for lead in all_threat_leads] 196 | return list(set(techniques)) 197 | 198 | 199 | def get_all_leads(query_history_df): 200 | results = [] 201 | idx = 0 202 | for lead in all_threat_leads: 203 | st_logger.info(f'{idx}: {lead["name"]}') 204 | results.append( 205 | { 206 | 'name': lead['name'], 207 | 'technique': lead['mitre_technique_description'], 208 | 'description': lead['description'], 209 | 'mask': lead['df_filter'](query_history_df) 210 | } 211 | ) 212 | idx += 1 213 | 214 | return results -------------------------------------------------------------------------------- /streamlit/analytics/overview.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | 3 | def plot_login_frequency(login_data): 4 | login_frequency = login_data['USER_NAME'].value_counts().reset_index() 5 | login_frequency.columns = ['User', 'Frequency'] 6 | 7 | st.bar_chart(login_frequency.set_index('User')) -------------------------------------------------------------------------------- /streamlit/app.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | import pandas as pd 3 | import logging as log 4 | import argparse 5 | import datetime 6 | import numpy as np 7 | 8 | from snowflake.snowpark.context import get_active_session 9 | from snowflake.snowpark.exceptions import SnowparkSessionException 10 | 11 | import helpers 12 | import analytics 13 | import metrics 14 | 15 | log.basicConfig(level=log.INFO) 16 | 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument('--dev', type=bool, default=False, help='Run in local developer mode') 19 | args = parser.parse_args() 20 | 21 | development_mode = args.dev 22 | 23 | try: 24 | get_active_session() 25 | 26 | if not development_mode: 27 | 28 | helpers.request_permissions() 29 | 30 | except SnowparkSessionException: 31 | log.info("No active session found") 32 | 33 | if development_mode: 34 | log.info("Running in local developer mode") 35 | helpers.create_local_session() 36 | else: 37 | raise 38 | 39 | def main(): 40 | 41 | st.set_page_config(layout="wide") 42 | 43 | st.title("⛏️ Ice Axe") 44 | st.write("Investigate security threats in your Snowflake accounts, natively.") 45 | 46 | with st.sidebar: 47 | 48 | st.header("Filters") 49 | start_date = st.date_input('Start date', value=pd.to_datetime('today')-datetime.timedelta(days=7)) 50 | 51 | end_date = st.date_input('End date', value=pd.to_datetime('today')) 52 | 53 | summary_tab, leads_tab, user_activity_tab = st.tabs(['Summary', 'Leads Details', 'User Activity Details']) 54 | 55 | query_history_df = metrics.query_history.get_for_dates(start_date=start_date, end_date=end_date) 56 | 57 | all_threat_leads = analytics.leads.get_all_leads(query_history_df) 58 | all_threats_masks = [lead['mask'] for lead in all_threat_leads] 59 | all_threats_df = query_history_df[np.logical_or.reduce(all_threats_masks)] 60 | 61 | with summary_tab: 62 | 63 | # Level 1: Top level KPIs 64 | user_threats_df = all_threats_df.groupby(['USER_NAME']).size().reset_index(name='Threat Leads Count') 65 | 66 | col1, col2 = st.columns(2) 67 | 68 | with col1: 69 | st.metric( 70 | label="Threat Leads Count", 71 | value=all_threats_df.shape[0], 72 | delta_color="off" 73 | ) 74 | 75 | st.header('Users at Risk') 76 | st.dataframe(user_threats_df) 77 | 78 | with col2: 79 | st.metric( 80 | label="Users at Risk Count", 81 | value=user_threats_df.shape[0], 82 | delta_color="off" 83 | ) 84 | 85 | st.header('Unusual Apps') 86 | unusual_apps = query_history_df.groupby('CLIENT_APPLICATION')['SESSION_ID'].nunique().reset_index(name='Session Count').sort_values('Session Count').head(10).reset_index(drop=True) 87 | st.dataframe(unusual_apps) 88 | 89 | with user_activity_tab: 90 | # Level 2: Trends & Patterns 91 | 92 | #TODO: Native Apps does not support latest streamlit APIs yet, so inject 'None' as the first option 93 | #user_search = st.selectbox('Search by username', metrics.users.get(), index=None) 94 | user_search = st.selectbox('Search by username', [None] + metrics.users.get()) 95 | 96 | col1, col2 = st.columns(2) 97 | 98 | login_data = metrics.users.load_data(start_date, end_date, user_search) 99 | login_data.sort_values('EVENT_TIMESTAMP', ascending=False, inplace=True) 100 | 101 | with st.expander('Login Frequency by User', expanded=True): 102 | analytics.overview.plot_login_frequency(login_data) 103 | 104 | # Level 3: Details for investigation 105 | with st.expander('Login History', expanded=True): 106 | st.dataframe(login_data) 107 | 108 | with st.expander("Query History", expanded=True): 109 | if user_search is not None: 110 | query_data_display = query_history_df[query_history_df['USER_NAME'] == user_search] 111 | else: 112 | query_data_display = query_history_df 113 | query_data_display.sort_values('START_TIME', ascending=False, inplace=True) 114 | st.dataframe(query_data_display) 115 | 116 | with leads_tab: 117 | # Level 3: Details for investigation 118 | technique_names = analytics.leads.get_all_leads_techniques() 119 | techniques_selected = st.multiselect('Show Technique Leads', options=technique_names, default=technique_names) 120 | 121 | for lead_result in all_threat_leads: 122 | if lead_result['technique'] not in techniques_selected: 123 | continue 124 | 125 | threat_mask = lead_result['mask'] 126 | threat_df = query_history_df[threat_mask] 127 | 128 | has_threats = False 129 | if threat_df.shape[0] > 0: 130 | icon = "❗" 131 | expanded = True 132 | has_threats = True 133 | else: 134 | icon = "✅" 135 | expanded = False 136 | 137 | #TODO: Native Apps does not support latest streamlit APIs yet, so store icon in the name 138 | #with st.expander(lead_result['name'], expanded=expanded, icon=icon): 139 | with st.expander("{} {}".format(icon, lead_result['name']), expanded=expanded): 140 | st.write(lead_result['description']) 141 | if has_threats: 142 | st.dataframe(threat_df) 143 | else: 144 | st.write("_None found_") 145 | 146 | st.header('All Threats') 147 | st.dataframe(all_threats_df) 148 | 149 | st.write("Made with ❤️ in California by [Dune Group](https://dunegroup.xyz)") 150 | 151 | 152 | main() 153 | -------------------------------------------------------------------------------- /streamlit/environment.yml: -------------------------------------------------------------------------------- 1 | name: sf_env 2 | channels: 3 | - snowflake 4 | dependencies: 5 | - snowflake-native-apps-permission 6 | - plotly 7 | - streamlit-folium 8 | - pandas -------------------------------------------------------------------------------- /streamlit/helpers.py: -------------------------------------------------------------------------------- 1 | from snowflake.snowpark.session import Session 2 | from snowflake.snowpark.context import get_active_session 3 | 4 | def create_local_session(): 5 | import configparser 6 | import pathlib 7 | 8 | config = configparser.ConfigParser() 9 | config.read(pathlib.Path('~/.snowsql/config').expanduser()) 10 | 11 | connection_parameters = { 12 | "account": config['connections.ICE_AXE']['accountname'], 13 | "user": config['connections.ICE_AXE']['username'], 14 | "password": config['connections.ICE_AXE']['password'], 15 | } 16 | 17 | Session.builder.configs(connection_parameters).create() 18 | 19 | 20 | def request_permissions(): 21 | import snowflake.permissions as permissions 22 | 23 | session = get_active_session() 24 | # Check if required privileges are missing 25 | missing_privileges = permissions.get_missing_account_privileges(["IMPORTED PRIVILEGES ON SNOWFLAKE DB"]) 26 | if missing_privileges: 27 | # Request permissions from the user 28 | permissions.request_account_privileges(missing_privileges) -------------------------------------------------------------------------------- /streamlit/metrics/__init__.py: -------------------------------------------------------------------------------- 1 | from . import (query_history, users) -------------------------------------------------------------------------------- /streamlit/metrics/query_history.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | 3 | from snowflake.snowpark.context import get_active_session 4 | 5 | 6 | @st.cache_data 7 | def get_for_dates(start_date, end_date): 8 | session = get_active_session() 9 | 10 | query_history_df = session.sql("""select START_TIME 11 | , h.USER_NAME 12 | , s.authentication_method as SESSION_AUTH 13 | , s.session_id 14 | , l.reported_client_type as LOGIN_CLIENT_TYPE 15 | , s.CLIENT_APPLICATION_ID AS SESSION_CLIENT_APP 16 | , s.CLIENT_APPLICATION_VERSION AS SESSION_CLIENT_VERSION 17 | , l.reported_client_version as LOGIN_CLIENT_VERSION 18 | , s.CLIENT_ENVIRONMENT AS RAW_CLIENT_ENV 19 | , PARSE_JSON(RAW_CLIENT_ENV) as CLIENT_ENV 20 | , CLIENT_ENV:APPLICATION::STRING AS client_application 21 | , CLIENT_ENV:OS::STRING AS client_os 22 | , CLIENT_ENV:OS_VERSION::STRING AS client_os_version 23 | , l.CLIENT_IP as LOGIN_IP 24 | , l.event_timestamp as LOGIN_TIMESTAMP 25 | , ROLE_NAME 26 | , QUERY_ID 27 | , QUERY_TYPE 28 | , QUERY_TEXT 29 | , execution_status 30 | , ROWS_PRODUCED 31 | , BYTES_WRITTEN 32 | , ROWS_INSERTED 33 | , ROWS_UPDATED 34 | , ROWS_DELETED 35 | from SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY h 36 | left JOIN SNOWFLAKE.ACCOUNT_USAGE.SESSIONS s on h.SESSION_ID = s.SESSION_ID 37 | left join SNOWFLAKE.ACCOUNT_USAGE.LOGIN_HISTORY l on s.LOGIN_EVENT_ID = l.EVENT_ID 38 | where h.user_name not in ('WORKSHEETS_APP_USER') // internal snowflake user 39 | and LOGIN_IP != '0.0.0.0' // internal snowflake activity 40 | and session_auth is not null // filter out snow generate sql queries that don't have a session id present in ACCOUNT_USAGE.SESSIONS 41 | and START_TIME BETWEEN ? and ? 42 | order by START_TIME DESC""", 43 | params=[start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d')] 44 | ).to_pandas(block=True) 45 | 46 | typed_df = query_history_df.astype({'EXECUTION_STATUS': 'string'}) 47 | 48 | return typed_df 49 | -------------------------------------------------------------------------------- /streamlit/metrics/users.py: -------------------------------------------------------------------------------- 1 | from snowflake.snowpark.functions import col 2 | from snowflake.snowpark.context import get_active_session 3 | 4 | import streamlit as st 5 | 6 | @st.cache_data 7 | def get(): 8 | session = get_active_session() 9 | users_table = session.table("snowflake.account_usage.users") 10 | users_df = users_table.filter( 11 | col("NAME").is_not_null() 12 | ) 13 | 14 | return users_df.to_pandas()['NAME'].to_list() 15 | 16 | @st.cache_data 17 | def load_data(start_date, end_date, user_search): 18 | session = get_active_session() 19 | 20 | # Load login history 21 | login_history_table = session.table("snowflake.account_usage.login_history") 22 | login_df = login_history_table.filter( 23 | (col("EVENT_TIMESTAMP").cast("date") >= start_date) & 24 | (col("EVENT_TIMESTAMP").cast("date") <= end_date) 25 | ) 26 | 27 | if user_search is not None: 28 | login_df = login_df.filter(col("USER_NAME").like(f'%{user_search}%')) 29 | 30 | return login_df.to_pandas() --------------------------------------------------------------------------------