diff --git "a/data/code/queries_test.jsonl" "b/data/code/queries_test.jsonl" new file mode 100644 --- /dev/null +++ "b/data/code/queries_test.jsonl" @@ -0,0 +1,480 @@ +{"_id": "code_q_000001", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C#]\n...\nstring userName = ctx.getAuthenticatedUserName();\nstring query = \"SELECT * FROM items WHERE owner = '\" + userName + \"' AND itemname = '\" + ItemName.Text + \"'\";\nsda = new SqlDataAdapter(query, conn);\nDataTable dt = new DataTable();\nsda.Fill(dt);\n...", "query_type": "code"} +{"_id": "code_q_000002", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C++]\nclass SomeAppClass {\n\npublic:\nstatic string appPropertiesConfigFile = \"app/properties.config\";\n\n...\n }\n\n[Java]\npublic class SomeAppClass {\n\npublic static String appPropertiesFile = \"app/Application.properties\";\n...\n }", "query_type": "code"} +{"_id": "code_q_000004", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nreg gpio_out = 0; //gpio should remain low for normal operation\n\n case (register_address)\n\n 4'b1111 : //0x0F\n\n\t\t\t begin\n\n gpio_out = 1;\n\n\t\t\t end", "query_type": "code"} +{"_id": "code_q_000005", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic void removeDatabase(String databaseName) {\n\ntry {\n\nStatement stmt = conn.createStatement();\nstmt.execute(\"DROP DATABASE \" + databaseName);\n\n } catch (SQLException ex) {...}\n }", "query_type": "code"} +{"_id": "code_q_000006", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class BankAccount {\n\n // private member variables of BankAccount class\n\nprivate String accountOwnerName;\nprivate String accountOwnerSSN;\nprivate int accountNumber;\nprivate double balance;\n\n // constructor for BankAccount class\n\npublic BankAccount(String accountOwnerName, String accountOwnerSSN,\nint accountNumber, double initialBalance, int initialRate)\n{\nthis.accountOwnerName = accountOwnerName;\nthis.accountOwnerSSN = accountOwnerSSN;\nthis.accountNumber = accountNumber;\nthis.balance = initialBalance;\nthis.start(initialRate);}\n\n // start method will add interest to balance every 30 days\n\n // creates timer object and interest adding action listener object\n\npublic void start(double rate)\n{\nActionListener adder = new InterestAdder(rate);\nTimer t = new Timer(1000 * 3600 * 24 * 30, adder);\nt.start();}\n\n // InterestAdder is an inner class of BankAccount class\n\n // that implements the ActionListener interface\n\nprivate class ", "query_type": "code"} +{"_id": "code_q_000007", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class UrlToolApplet extends Applet {\n\n // private member variables for applet components\n\nprivate Label enterUrlLabel;\nprivate TextField enterUrlTextField;\nprivate Button submitButton;\n\n // init method that adds components to applet\n\n // and creates button listener object\n\npublic void init() {\nsetLayout(new FlowLayout());\nenterUrlLabel = new Label(\"Enter URL: \");\nenterUrlTextField = new TextField(\"\", 20);\nsubmitButton = new Button(\"Submit\");\nadd(enterUrlLabel);\nadd(enterUrlTextField);\nadd(submitButton);\nActionListener submitButtonListener = new SubmitButtonListener();\nsubmitButton.addActionListener(submitButtonListener);}\n\n // button listener inner class for UrlToolApplet class\n\nprivate class SubmitButtonListener implements ActionListener {\n\npublic void actionPerformed(ActionEvent evt) {\n\nif (evt.getSource() == submitButton) {\nString urlString = enterUrlTextField.getText();\nURL url = null;\ntry {\nurl = new URL(urlString);} catch (MalformedURLException e) {\nSystem.err.p", "query_type": "code"} +{"_id": "code_q_000010", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class RegistrationForm extends org.apache.struts.validator.ValidatorForm {\n\n// variables for registration form\npublic String name;\npublic String email;\n...\n\npublic RegistrationForm() {\nsuper();}\npublic ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {...}\n...\n }", "query_type": "code"} +{"_id": "code_q_000011", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nuse CGI qw(:standard);\n\nsub config_file_add_key {\n\nmy ($fname, $key, $arg) = @_;\n\n # code to add a field/key to a file goes here\n\n }\n\nsub config_file_set_key {\n\nmy ($fname, $key, $arg) = @_;\n\n # code to set key to a particular file goes here\n\n }\n\nsub config_file_delete_key {\n\nmy ($fname, $key, $arg) = @_;\n\n # code to delete key from a particular file goes here\n\n }\n\nsub handleConfigAction {\n\nmy ($fname, $action) = @_;\nmy $key = param('key');\nmy $val = param('val');\n\n # this is super-efficient code, especially if you have to invoke\n\n # any one of dozens of different functions!\n\nmy $code = \"config_file_$action_key(\\$fname, \\$key, \\$val);\";\neval($code);\n }\n\n$configfile = \"/home/cwe/config.txt\";\nprint header;\nif (defined(param('action'))) {\nhandleConfigAction($configfile, param('action'));}\nelse {\nprint \"No action specified!\\n\";}", "query_type": "code"} +{"_id": "code_q_000012", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[XML]\n\n\n\n\n\n...\n\n ", "query_type": "code"} +{"_id": "code_q_000013", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nint getValueFromArray(int *array, int len, int index) {\n\nint value;\n\n // check that the array index is less than the maximum\n\n // length of the array\n\nif (index < len) {\n\n // get the value at the specified index of the array\n\nvalue = array[index];\n }\n\n // if array index is invalid then output error message\n\n // and return value indicating error\n\nelse {\nprintf(\"Value is: %d\\n\", array[index]);\nvalue = -1;}\n\nreturn value;\n }", "query_type": "code"} +{"_id": "code_q_000014", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nString path = getInputPath();\nif (path.startsWith(\"/safe_dir/\"))\n{\nFile f = new File(path);\nreturn f.getCanonicalPath();}", "query_type": "code"} +{"_id": "code_q_000015", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nmodule acct_wrapper #(\n\n\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\talways @(posedge clk_i)\n\n\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\tif(~(rst_ni && ~rst_6))\n\n\t\t\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\t\t\tfor (j=0; j < AcCt_MEM_SIZE; j=j+1)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tacct_mem[j] <= 32'hffffffff;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000016", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nString str1 = new String(\"Hello\");\nString str2 = new String(\"Hello\");\nif (str1 == str2) {\nSystem.out.println(\"str1 == str2\");}", "query_type": "code"} +{"_id": "code_q_000017", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $arg = GetArgument(\"filename\");\n\n\t\t\t do_listing($arg);\n\n\t\t\t sub do_listing {\n\n\t\t\t\tmy($fname) = @_;\n\n\t\t\t\tif (! validate_name($fname)) {\n\n\t\t\t\t print \"Error: name is not well-formed!\\n\";\n\n\t\t\t\t return;\n\n\t\t\t\t}\n\n\t\t\t\t# build command\n\n\t\t\t\tmy $cmd = \"/bin/ls -l $fname\";\n\n\t\t\t\tsystem($cmd);\n\n\t\t\t }\n\n\t\t\t sub validate_name {\n\n\t\t\t\tmy($name) = @_;\n\n\t\t\t\tif ($name =~ /^[\\w\\-]+$/) {\n\n\t\t\t\t return(1);\n\n\t\t\t\t}\n\n\t\t\t\telse {\n\n\t\t\t\t return(0);\n\n\t\t\t\t}\n\n\t\t\t }", "query_type": "code"} +{"_id": "code_q_000018", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Shell]\naz storage account update --name --resource-group --allow-blob-public-access true", "query_type": "code"} +{"_id": "code_q_000019", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\n\t\t\t\t\t\t\tlocalparam logic[63:0] PLICLength = 64'h03FF_FFFF;\n\n\t\t\t\t\t\t\tlocalparam logic[63:0] UARTLength = 64'h0011_1000;\n\n\t\t\t\t\t\t\tlocalparam logic[63:0] AESLength = 64'h0000_1000;\n\n\t\t\t\t\t\t\tlocalparam logic[63:0] SPILength = 64'h0080_0000;\n\n...\n\n\t\t\t\t\t\t\ttypedef enum logic [63:0] {\n\n\t\t\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\t\tPLICBase = 64'h0C00_0000,\n\n\t\t\t\t\t\t\t\tUARTBase = 64'h1000_0000,\n\n\t\t\t\t\t\t\t\tAESBase = 64'h1010_0000,\n\n\t\t\t\t\t\t\t\tSPIBase = 64'h2000_0000,\n\n\t\t\t\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000020", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nvoid f(pthread_mutex_t *mutex) {\n\npthread_mutex_lock(mutex);\n\n /* access shared resource */\n\npthread_mutex_unlock(mutex);\n }", "query_type": "code"} +{"_id": "code_q_000021", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nfoo=malloc(sizeof(char)); //the next line checks to see if malloc failed\nif (foo==NULL) {\n//We do nothing so we just ignore the error.}", "query_type": "code"} +{"_id": "code_q_000022", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[XML]\n\n\n\n\n ...\n\n\n\n\n\n ...\n\n\n \n\n[Java]\n...\n\nIntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);\nBroadcastReceiver sReceiver = new ShutDownReceiver();\nregisterReceiver(sReceiver, filter);\n\n ...\n\npublic class ShutdownReceiver extends BroadcastReceiver {\n@Override\npublic void onReceive(final Context context, final Intent intent) {\nmainActivity.saveLocalData();\nmainActivity.stopActivity();}}", "query_type": "code"} +{"_id": "code_q_000023", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nmodule csr_regfile #(...)(...);\n\n ...\n\n // ---------------------------\n\n // CSR Write and update logic\n\n // ---------------------------\n\n ...\n\n if (csr_we) begin\n\n unique case (csr_addr.address)\n\n ...\n\n riscv::CSR_SIE: begin\n\n // the mideleg makes sure only delegate-able register\n\n //(and therefore also only implemented registers) are written\n\n mie_d = (mie_q & ~mideleg_q) | (csr_wdata & mideleg_q) | utval_q;\n\n end\n\n ...\n\n endcase\n\n end\n\n endmodule", "query_type": "code"} +{"_id": "code_q_000024", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $Username = GetUntrustedInput();\nif (substr($Username, 0, 3) eq '../') {\n$Username = substr($Username, 3);}\nmy $filename = \"/home/user/\" . $Username;\nReadAndSendFile($filename);", "query_type": "code"} +{"_id": "code_q_000025", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[HTML]\n\n\n[JavaScript]\nvar newWindow = window.open(\" \"_blank\");", "query_type": "code"} +{"_id": "code_q_000026", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule fsm_1(out, user_input, clk, rst_n);\n\ninput [2:0] user_input;\n\ninput clk, rst_n;\n\noutput reg [2:0] out;\n\nreg [1:0] state;\n\nalways @ (posedge clk or negedge rst_n )\n\nbegin\n\n\t\t\t\t if (!rst_n)\n\n\t\t\t\t\tstate = 3'h0;\n\n else\n\n\t\t\t\t case (user_input)\n\n\t\t\t\t\t3'h0:\n\n\t\t\t\t\t3'h1:\n\n\t\t\t\t\t3'h2:\n\n\t\t\t\t\t3'h3: state = 2'h3;\n\n\t\t\t\t\t3'h4: state = 2'h2;\n\n\t\t\t\t\t3'h5: state = 2'h1;\n\n endcase\n\n end\n\n out <= {1'h1, state};\n\n endmodule", "query_type": "code"} +{"_id": "code_q_000027", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $Username = GetUntrustedInput();\n$Username =~ s/\\.\\.\\///;\nmy $filename = \"/home/user/\" . $Username;\nReadAndSendFile($filename);", "query_type": "code"} +{"_id": "code_q_000029", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic String readFile(String filename) {\n\nString retString = null;\ntry {\n\n// initialize File and FileReader objects\nFile file = new File(filename);\nFileReader fr = new FileReader(file);\n\n// initialize character buffer\nlong fLen = file.length();\nchar[] cBuf = new char[(int) fLen];\n\n// read data from file\nint iRead = fr.read(cBuf, 0, (int) fLen);\n\n// close file\nfr.close();\n\nretString = new String(cBuf);\n\n } catch (Exception ex) {\n/* do nothing, but catch so it'll compile... */}\nreturn retString;\n }", "query_type": "code"} +{"_id": "code_q_000030", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\n\t\t\t\t\t\t// Implement SHA256 I/O memory map interface\n\n\t\t\t\t\t\t// Write side\n\n\t\t\t\t\t\talways @(posedge clk_i)\n\n\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\tif(~(rst_ni && ~rst_3))\n\n\t\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\t\tstartHash <= 0;\n\n\t\t\t\t\t\t\t\t\t\tnewMessage <= 0;\n\n\t\t\t\t\t\t\t\t\t\tdata[0] <= 0;\n\n\t\t\t\t\t\t\t\t\t\tdata[1] <= 0;\n\n\t\t\t\t\t\t\t\t\t\tdata[2] <= 0;\n\n\t\t\t\t\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\t\t\t\tdata[14] <= 0;\n\n\t\t\t\t\t\t\t\t\t\tdata[15] <= 0;\n\n\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000031", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define OUTFILE \"hello.out\"\n\numask(0);\nFILE *out;\n\n /* Ignore link following (this weakness) for brevity */\n\nout = fopen(OUTFILE, \"w\");\nif (out) {\nfprintf(out, \"hello world!\\n\");\nfclose(out);}", "query_type": "code"} +{"_id": "code_q_000033", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n//hardcode input length for simplicity\n\nchar* input = (char*) malloc(40*sizeof(char));\nchar *tok;\nchar* sep = \" \\t\";\n\nget_user_input( input );\n\n /* The following loop will parse and process each token in the input string */\n\ntok = strtok( input, sep);\nwhile( NULL != tok ){\n\nif( isMalformed( tok ) ){\n\n /* ignore and discard bad data */\n\nfree( tok );\n }\nelse{\nadd_to_command_queue( tok );}\ntok = strtok( NULL, sep));\n }", "query_type": "code"} +{"_id": "code_q_000034", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule register_write_once_example\n\n\t\t (\n\n\t\t input [15:0] Data_in,\n\n\t\t input Clk,\n\n\t\t input ip_resetn,\n\n\t\t input global_resetn,\n\n\t\t input write,\n\n\t\t output reg [15:0] Data_out\n\n\t\t );\n\n\t\t reg Write_once_status;\n\n\t\t always @(posedge Clk or negedge ip_resetn)\n\n\t\t\tif (~ip_resetn)\n\n\t\t\tbegin\n\n\t\t\t Data_out <= 16'h0000;\n\n\t\t\t Write_once_status <= 1'b0;\n\n\t\t\tend\n\n\t\t\telse if (write & ~Write_once_status)\n\n\t\t\tbegin\n\n\t\t\t Data_out <= Data_in & 16'hFFFE;\n\n\t\t\t Write_once_status <= Data_in[0]; // Input bit 0 sets Write_once_status\n\n\t\t\tend\n\n\t\t\telse if (~write)\n\n\t\t\tbegin\n\n\t\t\t Data_out[15:1] <= Data_out[15:1];\n\n\t\t\t Data_out[0] <= Write_once_status;\n\n\t\t\tend\n\n\t\t\tendmodule", "query_type": "code"} +{"_id": "code_q_000035", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JSON]\n{\n\n\t\t \"bindings\":[{\n\n\t\t\t \"members\":[\n\n\t\t\t \"projectEditor: PROJECT-ID\",\n\n\t\t\t \"projectOwner: PROJECT-ID\"\n\n\t\t\t ],\n\n\t\t\t \"role\":\"roles/storage.legacyBucketOwner\"\n\n\t\t },\n\n\t\t {\n\n\t\t\t \"members\":[\n\n\t\t\t \"allUsers\",\n\n\t\t\t \"projectViewer: PROJECT-ID\"\n\n\t\t\t ],\n\n\t\t\t \"role\":\"roles/storage.legacyBucketReader\"\n\n\t\t\t }\n\n\t\t ]\n\n\t\t }", "query_type": "code"} +{"_id": "code_q_000037", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\nimport os\n\n import sys\n\n def main():\n\n filename = sys.argv[1]\n\n path = os.path.join(os.getcwd(), filename)\n\n try:\n\n with open(path, 'r') as f:\n\n file_data = f.read()\n\n except FileNotFoundError as e:\n\n print(\"Error - file not found\")\n\n main()", "query_type": "code"} +{"_id": "code_q_000038", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SQL]\nprocedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm in varchar2)\nis open itm_cv for\n' SELECT * FROM items WHERE ' || 'owner = '|| usr || ' AND itemname = ' || itm || ';\nend get_item;", "query_type": "code"} +{"_id": "code_q_000039", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\nfor (i=0; i\\n\";\nwhile (<$fh>) {\nprint \"
  • $_
  • \\n\";}\nprint \"\\n\";", "query_type": "code"} +{"_id": "code_q_000041", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class BankAccount {\n\npublic final int MAXIMUM_WITHDRAWAL_LIMIT = 350;\n\n // variable for bank account balance\n\nprivate double accountBalance;\n\n // constructor for BankAccount\n\npublic BankAccount() {\naccountBalance = 0;}\n\n // method to deposit amount into BankAccount\n\npublic void deposit(double depositAmount) {...}\n\n // method to withdraw amount from BankAccount\n\npublic void withdraw(double withdrawAmount) {\n\nif (withdrawAmount < MAXIMUM_WITHDRAWAL_LIMIT) {\n\ndouble newBalance = accountBalance - withdrawAmount;\naccountBalance = newBalance;\n }\nelse {\nSystem.err.println(\"Withdrawal amount exceeds the maximum limit allowed, please try again...\");\n...}\n }\n\n // other methods for accessing the BankAccount object\n\n...\n }", "query_type": "code"} +{"_id": "code_q_000042", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic void checkValid(boolean isValid) {\nif (isValid = true) {\nSystem.out.println(\"Performing processing\");\ndoSomethingImportant();}\nelse {\nSystem.out.println(\"Not Valid, do not perform processing\");\nreturn;}}", "query_type": "code"} +{"_id": "code_q_000043", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JavaScript]\nlet step = input1 + input2;\n\nswitch(step) {\n\ncase 1:\n\nalert(\"Process step 1.\");\n\nbreak;\n\ncase 2:\n\nalert(\"Process step 2.\");\n\nbreak;\n\ncase 3:\n\nalert(\"Process step 3.\");\n\nbreak;\n\n}\n\n// program execution continues...", "query_type": "code"} +{"_id": "code_q_000044", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nIntent intent = new Intent();\nintent.setAction(\"com.example.CreateUser\");\nintent.putExtra(\"Username\", uname_string);\nintent.putExtra(\"Password\", pw_string);\nsendBroadcast(intent);", "query_type": "code"} +{"_id": "code_q_000046", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic void updateUserAccountOrder(String productNumber, String accountNumber) {\n\nboolean isValidProduct = false;\nboolean isValidAccount = false;\n\nif (validProductNumber(productNumber)) {\nisValidProduct = true;\nupdateInventory(productNumber);}\nelse {\nreturn;}\n\nif (validAccountNumber(accountNumber)) {\nisValidProduct = true;\nupdateAccount(accountNumber, productNumber);}\n\nif (isValidProduct && isValidAccount) {\nupdateAccountOrder(accountNumber, productNumber);}\n }", "query_type": "code"} +{"_id": "code_q_000047", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$dir = \"/home/cwe/languages\";\n$lang = $_GET['lang'];\nif (preg_match(\"/[A-Za-z0-9]+/\", $lang)) {\ninclude(\"$dir/$lang\");}\nelse {\necho \"You shall not pass!\\n\";}", "query_type": "code"} +{"_id": "code_q_000048", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\n$inputString = readLineFromFileHandle($serverFH);\n\n # generate an array of strings separated by the \"|\" character.\n\n@commands = split(/\\|/, $inputString);\n\nforeach $cmd (@commands) {\n\n # separate the operator from its arguments based on a single whitespace\n\n($operator, $args) = split(/ /, $cmd, 2);\n\n$args = UrlDecode($args);\nif ($operator eq \"BAN\") {\nExecuteBan($args);}\nelsif ($operator eq \"SAY\") {\nExecuteSay($args);}}\n\n[Perl]\n$inputString = GetUntrustedArgument(\"command\");\n($cmd, $argstr) = split(/\\s+/, $inputString, 2);\n\n # removes extra whitespace and also changes CRLF's to spaces\n\n$argstr =~ s/\\s+/ /gs;\n\n$argstr = UrlEncode($argstr);\nif (($cmd eq \"BAN\") && (! IsAdministrator($username))) {\ndie \"Error: you are not the admin.\\n\";}\n\n # communicate with file server using a file handle\n\n$fh = GetServerFileHandle(\"myserver\");\n\nprint $fh \"$cmd $argstr\\n\";", "query_type": "code"} +{"_id": "code_q_000050", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\nprompt = \"Explain the difference between {} and {}\".format(arg1, arg2)\n\n\t\t\t\t\tresult = invokeChatbot(prompt)\n\n\t\t\t\t\tresultHTML = encodeForHTML(result)\n\n\t\t\t\t\tprint resultHTML", "query_type": "code"} +{"_id": "code_q_000051", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define LOG_INPUT_SIZE 40\n\n // saves the file name to a log file\n\nint outputFilenameToLog(char *filename, int length) {\n\nint success;\n\n // buffer with size set to maximum size for input to log file\n\nchar buf[LOG_INPUT_SIZE];\n\n // copy filename to buffer\n\nstrncpy(buf, filename, length);\n\n // save to log file\n\nsuccess = saveToLogFile(buf);\n\nreturn success;\n }", "query_type": "code"} +{"_id": "code_q_000052", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nmodule dma # (...)(...);\n\n\t\t\t\t\t...\n\n\t\t\t\t\t\tinput [7:0] [16-1:0] pmpcfg_i;\n\n\t\t\t\t\t\tinput logic [16-1:0][53:0] pmpaddr_i;\n\n\t\t\t\t\t\t...\n\n\t\t\t\t\t\t//// Save the input command\n\n \t\t\t\t\t\talways @ (posedge clk_i or negedge rst_ni)\n\n\t\t\t\t\t\t\tbegin: save_inputs\n\n\t\t\t\t\t\t\tif (!rst_ni)\n\n\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\telse\n\n\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\tif (dma_ctrl_reg == CTRL_IDLE || dma_ctrl_reg == CTRL_DONE)\n\n\t\t\t\t\t\t\t\t\tbegin\n\n\t\t\t\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\tend // save_inputs\n\n\t\t\t\t\t\t\t...\n\n\t\t\t\t\t\t\t// Load/store PMP check\n\n\t\t\t\t\t\t\tpmp #(\n\n\t\t\t\t\t\t\t\t.XLEN ( 64 ),\n\n\t\t\t\t\t\t\t\t.PMP_LEN ( 54 ),\n\n\t\t\t\t\t\t\t\t.NR_ENTRIES ( 16 )\n\n\t\t\t\t\t\t\t) i_pmp_data (\n\n\t\t\t\t\t\t\t\t.addr_i ( pmp_addr_reg ),\n\n\t\t\t\t\t\t\t\t.priv_lvl_i ( riscv::PRIV_LVL_U ),\n\n\t\t\t\t\t\t\t\t.access_type_i ( pmp_access_type_reg ),\n\n\t\t\t\t\t\t\t\t// Configuration\n\n\t\t\t\t\t\t\t\t.conf_addr_i ( pmpaddr_i ),\n\n\t\t\t\t\t\t\t\t.conf_i ( pmpcfg_i ),\n\n\t\t\t\t\t\t\t\t.allow_o ( pmp_data_allow )\n\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\tendmodule", "query_type": "code"} +{"_id": "code_q_000053", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nint validateUser(char *host, int port)\n{\n\nint socket = openSocketConnection(host, port);\nif (socket < 0) {\nprintf(\"Unable to open socket connection\");\nreturn(FAIL);}\n\nint isValidUser = 0;\nchar username[USERNAME_SIZE];\nchar password[PASSWORD_SIZE];\n\nwhile (isValidUser == 0) {\n\nif (getNextMessage(socket, username, USERNAME_SIZE) > 0) {\nif (getNextMessage(socket, password, PASSWORD_SIZE) > 0) {\nisValidUser = AuthenticateUser(username, password);}}\n }\nreturn(SUCCESS);\n }", "query_type": "code"} +{"_id": "code_q_000054", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n/* capture the sizes of all messages */\n\nint getsizes(int sock, int count, int *sizes) {\n\n...\nchar buf[BUFFER_SIZE];\nint ok;\nint num, size;\n\n // read values from socket and added to sizes array\n\nwhile ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)\n{\n\n // continue read from socket until buf only contains '.'\n\nif (DOTLINE(buf))\nbreak;\n else if (sscanf(buf, \"%d %d\", &num, &size) == 2)\nsizes[num - 1] = size;\n\n }\n...\n\n }", "query_type": "code"} +{"_id": "code_q_000055", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nmodule csr_regfile #(\n\n ...\n\n // check that we actually want to enter debug depending on the privilege level we are currently in\n\n unique case (priv_lvl_o)\n\n riscv::PRIV_LVL_M: begin\n\n debug_mode_d = dcsr_q.ebreakm;\n\n ...\n\n riscv::PRIV_LVL_U: begin\n\n debug_mode_d = dcsr_q.ebreaku;\n\n ...\n\n assign priv_lvl_o = (debug_mode_q || umode_i) ? riscv::PRIV_LVL_M : priv_lvl_q;\n\n ...\n\n debug_mode_q <= debug_mode_d;\n\n ...", "query_type": "code"} +{"_id": "code_q_000056", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Objective-C]\n- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {\nif (!url) {\nreturn NO;}\nNSString *action = [url host];\nif([action isEqualToString: @\"replaceFileText\"]) {\nNSDictionary *dict = [self parseQueryStringExampleFunction:[url query]];\n\n //this function will write contents to a specified file\n\nFileObject *objectFile = [self writeToFile:[dict objectForKey: @\"file\"] withText:[dict objectForKey: @\"text\"]];}\nreturn YES;}", "query_type": "code"} +{"_id": "code_q_000057", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$MessageFile = \"messages.out\";\nif ($_GET[\"action\"] == \"NewMessage\") {\n$name = $_GET[\"name\"];\n$message = $_GET[\"message\"];\n$handle = fopen($MessageFile, \"a+\");\nfwrite($handle, \"$name says '$message'
    \\n\");\nfclose($handle);\necho \"Message Saved!

    \\n\";}\nelse if ($_GET[\"action\"] == \"ViewMessages\") {\ninclude($MessageFile);}", "query_type": "code"} +{"_id": "code_q_000058", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$name = $_COOKIE[\"myname\"];\n$announceStr = \"$name just logged in.\";\n\n //save HTML-formatted message to file; implementation details are irrelevant for this example.\n\n\t\t\t\tsaveMessage($announceStr);", "query_type": "code"} +{"_id": "code_q_000059", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$dir = $_GET['module_name'];\ninclude($dir . \"/function.php\");\n\n[PHP]\nsystem($_GET['cmd']);", "query_type": "code"} +{"_id": "code_q_000060", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $username=param('username');\n\nmy $password=param('password');\n\nif (IsValidUsername($username) == 1)\n\n{\n\nif (IsValidPassword($username, $password) == 1)\n\n{\n\nprint \"Login Successful\";\n }\n\nelse\n\n{\n\nprint \"Login Failed - incorrect password\";\n }\n }\n\nelse\n\n{\n\nprint \"Login Failed - unknown username\";\n }", "query_type": "code"} +{"_id": "code_q_000061", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n/* Ignore this weakness (hard-coded password) and this weakness (use of password system for authentication) for this example. */\n\nchar *username = \"admin\";\nchar *pass = \"password\";\n\nint AuthenticateUser(char *inUser, char *inPass) {\n\nprintf(\"Sizeof username = %d\\n\", sizeof(username));\nprintf(\"Sizeof pass = %d\\n\", sizeof(pass));\n\nif (strncmp(username, inUser, sizeof(username))) {\nprintf(\"Auth failure of username using sizeof\\n\");\nreturn(AUTH_FAIL);}\n\n /* Because of this weakness, the sizeof returns 4 on many platforms and architectures. */\n\nif (! strncmp(pass, inPass, sizeof(pass))) {\nprintf(\"Auth success of password using sizeof\\n\");\nreturn(AUTH_SUCCESS);}\nelse {\nprintf(\"Auth fail of password using sizeof\\n\");\nreturn(AUTH_FAIL);}\n }\n\nint main (int argc, char **argv)\n{\n\nint authResult;\n\nif (argc < 3) {\nExitError(\"Usage: Provide a username and password\");}\nauthResult = AuthenticateUser(argv[1], argv[2]);\nif (authResult != AUTH_SUCCESS) {\nExitError(\"Authentication failed\");}\nelse {\nDoAuthenticatedTask(argv[1]);}\n }", "query_type": "code"} +{"_id": "code_q_000062", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nchar buffer[1024];\n...\nfgets(buffer, 1024, stdin);", "query_type": "code"} +{"_id": "code_q_000063", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nint main(int argc, char **argv)\n{\n\nchar Filename[256];\nchar Pattern[32];\n\n /* Validate number of parameters and ensure valid content */\n\n...\n\n /* copy filename parameter to variable, may cause off-by-one overflow */\n\nstrncpy(Filename, argv[1], sizeof(Filename));\n\n /* copy pattern parameter to variable, may cause off-by-one overflow */\n\nstrncpy(Pattern, argv[2], sizeof(Pattern));\n\nprintf(\"Searching file: %s for the pattern: %s\\n\", Filename, Pattern);\nScan_File(Filename, Pattern);}", "query_type": "code"} +{"_id": "code_q_000064", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JavaScript]\nvar test_string = \"Bad characters: $@#\";\n\n var bad_pattern = /^(\\w+\\s?)*$/i;\n\n var result = test_string.search(bad_pattern);", "query_type": "code"} +{"_id": "code_q_000065", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\n// Android\n\n@Override\npublic boolean shouldOverrideUrlLoading(WebView view, String url){\n\nif (url.substring(0,14).equalsIgnoreCase(\"examplescheme:\")){\nif(url.substring(14,25).equalsIgnoreCase(\"getUserInfo\")){\nwriteDataToView(view, UserData);\nreturn false;}\nelse{\nreturn true;}}\n }\n\n[Objective-C]\n// iOS\n\n-(BOOL) webView:(UIWebView *)exWebView shouldStartLoadWithRequest:(NSURLRequest *)exRequest navigationType:(UIWebViewNavigationType)exNavigationType\n{\n\nNSURL *URL = [exRequest URL];\nif ([[URL scheme] isEqualToString:@\"exampleScheme\"])\n{\n\nNSString *functionString = [URL resourceSpecifier];\nif ([functionString hasPrefix:@\"specialFunction\"])\n{\n\n // Make data available back in webview.\n\nUIWebView *webView = [self writeDataToView:[URL query]];\n }\nreturn NO;\n }\nreturn YES;\n }", "query_type": "code"} +{"_id": "code_q_000066", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[ASP.NET]\n", "query_type": "code"} +{"_id": "code_q_000067", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic void acceptConnections() {\n\ntry {\nServerSocket serverSocket = new ServerSocket(SERVER_PORT);\nint counter = 0;\nboolean hasConnections = true;\nwhile (hasConnections) {\nSocket client = serverSocket.accept();\nThread t = new Thread(new ClientSocketThread(client));\nt.setName(client.getInetAddress().getHostName() + \":\" + counter++);\nt.start();}\nserverSocket.close();\n\n} catch (IOException ex) {...}\n }", "query_type": "code"} +{"_id": "code_q_000070", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n01 | module crypto_core_with_leakage\n\n\t\t\t 02 | (\n\n\t\t\t\t03 | input clk,\n\n\t\t\t\t04 | input rst,\n\n\t\t\t\t05 | input [127:0] data_i,\n\n\t\t\t\t06 | output [127:0] data_o,\n\n\t\t\t\t07 | output valid\n\n\t\t\t 08 | );\n\n\t\t\t 09 |\n\n\t\t\t 10 | localparam int total_rounds = 10;\n\n\t\t\t 11 | logic [3:0] round_id_q;\n\n\t\t\t 12 | logic [127:0] data_state_q, data_state_d;\n\n\t\t\t 13 | logic [127:0] key_state_q, key_state_d;\n\n\t\t\t 14 |\n\n\t\t\t 15 | crypto_algo_round u_algo_round (\n\n\t\t\t\t16 | .clk (clk),\n\n\t\t\t\t17 | .rst (rst),\n\n\t\t\t\t18 | .round_i (round_id_q ),\n\n\t\t\t\t19 | .key_i (key_state_q ),\n\n\t\t\t\t20 | .data_i (data_state_q),\n\n\t\t\t\t21 | .key_o (key_state_d ),\n\n\t\t\t\t22 | .data_o (data_state_d)\n\n\t\t\t 23 | );\n\n\t\t\t 24 |\n\n\t\t\t 25 | always @(posedge clk) begin\n\n\t\t\t\t26 | if (rst) begin\n\n\t\t\t\t 27 | data_state_q <= 0;\n\n\t\t\t\t 28 | key_state_q <= 0;\n\n\t\t\t\t 29 | round_id_q <= 0;\n\n\t\t\t\t30 | end\n\n\t\t\t\t31 | else begin\n\n\t\t\t\t 32 | case (round_id_q)\n\n\t\t\t\t 33 | ", "query_type": "code"} +{"_id": "code_q_000071", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[VHDL]\n-- The following VHDL example is written for VHDL-93 or later.\n\n\t\t type t_priv_state is (RESET, USER_ONLY, PRIVILEGED);\n\n\t\t signal priv_state : t_priv_state := RESET;\n\n\t\t signal auth_passed : boolean := false;\n\n\t\t signal privilege_revoke : boolean := false;\n\n\t\t ...\n\n\t\t process(clk, reset_n)\n\n\t\t begin\n\n\t\t\tif reset_n = '0' then\n\n\t\t\t priv_state <= RESET;\n\n\t\t\telsif rising_edge(clk) then\n\n\t\t\t case priv_state is\n\n\t\t\t\twhen RESET =>\n\n\t\t\t\t priv_state <= USER_ONLY;\n\n\t\t\t\twhen USER_ONLY =>\n\n\t\t\t\t if auth_passed then\n\n\t\t\t\t\tpriv_state <= PRIVILEGED;\n\n\t\t\t\t end if;\n\n\t\t\t\twhen PRIVILEGED =>\n\n\t\t\t\t if privilege_revoke then\n\n\t\t\t\t\tpriv_state <= USER_ONLY;\n\n\t\t\t\t end if;\n\n\t\t\t\twhen others =>\n\n\t\t\t\t priv_state <= USER_ONLY; -- intended recovery for unexpected encodings\n\n\t\t\t\tend case;\n\n\t\t\t end if;\n\n\t\t\tend process;\n\n\t\t\tprotected_cfg_write_en <= (priv_state = PRIVILEGED);\n\n[Verilog]\nlocalparam RESET = 2'b00;\n\n\t\t\tlocalparam USER_ONLY = 2'b01;\n\n\t\t\tlocalparam PRIVILEGED = 2'b10;\n\n\t\t\treg [1:0] priv_state = RESET;\n\n\t\t\twire auth_passed; // Implicitly 1-bit (boolean e", "query_type": "code"} +{"_id": "code_q_000072", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule lock_control (\n\n\t\t\t input wire clk,\n\n\t\t\t input wire reset,\n\n\t\t\t input wire lock,\n\n\t\t\t input wire unlock,\n\n\t\t\t output reg unlocked\n\n\t\t\t);\n\n\t\t\t reg unlocked_next = 1'b0;\n\n\t\t\t always @(lock or unlock or unlocked) begin\n\n\t\t\t\tif (reset == 1'b1) begin\n\n\t\t\t\t unlocked_next = 1'b1;\n\n\t\t\t\tend else if (lock == 1'b1) begin\n\n\t\t\t\t unlocked_next = 1'b0;\n\n\t\t\t\tend else if (unlock == 1'b1) begin\n\n\t\t\t\t unlocked_next = 1'b1;\n\n\t\t\t\tend else begin\n\n\t\t\t\t unlocked_next = unlocked;\n\n\t\t\t\tend\n\n\t\t\t end\n\n\t\t\t always @(posedge clk) begin\n\n\t\t\t\tunlocked <= unlocked_next;\n\n\t\t\t end\n\n\t\t\tendmodule\n\n[VHDL]\nlibrary ieee;\n\n\t\t\tuse ieee.std_logic_1164.all;\n\n\t\t\tentity lock_control is\n\n\t\t\t port (\n\n\t\t\t\tclk : in std_logic;\n\n\t\t\t\treset : in std_logic;\n\n\t\t\t\tlock : in std_logic;\n\n\t\t\t\tunlock : in std_logic;\n\n\t\t\t\tunlocked : out std_logic\n\n\t\t\t );\n\n\t\t\tend entity lock_control;\n\n\t\t\tarchitecture behavioral of lock_control is\n\n\t\t\t signal unlocked_reg : std_logic:=’0’;\n\n\t\t\t signal unlocked_next : std_logic;\n\n\t\t\tbegin\n\n\t\t\t process(lock, unlock, unlocked_reg)\n\n\t\t\t begin\n\n\t\t\t\tif reset =", "query_type": "code"} +{"_id": "code_q_000074", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\ndef storePassword(userName,Password):\nhasher = hashlib.new('md5')\nhasher.update(Password)\nhashedPassword = hasher.digest()\n\n # UpdateUserLogin returns True on success, False otherwise\n\nreturn updateUserLogin(userName,hashedPassword)", "query_type": "code"} +{"_id": "code_q_000075", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\n// Parameterized Register module example\n\n\t\t\t\t // Secure_mode : REGISTER_DEFAULT[0] : When set to 1 register is read only and not writable//\n\n\t\t\t\t module register_example\n\n\t\t\t\t #(\n\n\t\t\t\t parameter REGISTER_WIDTH = 8, // Parameter defines width of register, default 8 bits\n\n\t\t\t\t parameter [REGISTER_WIDTH-1:0] REGISTER_DEFAULT = 2**REGISTER_WIDTH -2 // Default value of register computed from Width. Sets all bits to 1s except bit 0 (Secure _mode)\n\n\t\t\t\t )\n\n\t\t\t\t (\n\n\t\t\t\t input [REGISTER_WIDTH-1:0] Data_in,\n\n\t\t\t\t input Clk,\n\n\t\t\t\t input resetn,\n\n\t\t\t\t input write,\n\n\t\t\t\t output reg [REGISTER_WIDTH-1:0] Data_out\n\n\t\t\t\t );\n\n\t\t\t\t reg Secure_mode;\n\n\t\t\t\t always @(posedge Clk or negedge resetn)\n\n\t\t\t\t\tif (~resetn)\n\n\t\t\t\t\tbegin\n\n\t\t\t\t\t Data_out <= REGISTER_DEFAULT; // Register content set to Default at reset\n\n\t\t\t\t\t Secure_mode <= REGISTER_DEFAULT[0]; // Register Secure_mode set at reset\n\n\t\t\t\t\tend\n\n\t\t\t\t\telse if (write & ~Secure_mode)\n\n\t\t\t\t\tbegin\n\n\t\t\t\t\t Data_out <= Data_in;\n\n\t\t\t\t\tend\n\n\t\t\t\t endmodule\n\n\t\t\t\t module register_top\n\n\t\t\t\t (\n\n\t\t\t\t input Clk,\n\n\t\t\t\t input resetn,\n\n\t\t\t\t ", "query_type": "code"} +{"_id": "code_q_000076", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Algorithm]\nSuppose an algorithm for implementing an encryption routine works fine per se, but the time taken to output the result of the encryption routine depends on a relationship between the input plaintext and the key (e.g., suppose, if the plaintext is similar to the key, it would run very fast).", "query_type": "code"} +{"_id": "code_q_000077", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\nresult = process_data(data)\n\nmatch result:\n\ncase 0:\n\nprint(\"Properly handle zero case.\")\n\ncase 1:\n\nprint(\"Properly handle one case.\")\n\nprogram execution continues...", "query_type": "code"} +{"_id": "code_q_000078", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[HTML]\n

    Welcome!\n
    Please Login:\n
    \nUsername: \n
    \nPassword: \n\n
    \n
    \n
    ", "query_type": "code"} +{"_id": "code_q_000079", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $q = new CGI;\n\nif ($q->cookie('loggedin') ne \"true\") {\n\nif (! AuthenticateUser($q->param('username'), $q->param('password'))) {\nExitError(\"Error: you need to log in first\");}\nelse {\n\nSet loggedin and user cookies.\n$q->cookie(\n-name => 'loggedin',\n-value => 'true'\n);\n\n$q->cookie(\n-name => 'user',\n-value => $q->param('username')\n);\n\n }\n }\n\nif ($q->cookie('user') eq \"Administrator\") {\nDoAdministratorTasks();}", "query_type": "code"} +{"_id": "code_q_000081", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic boolean isSameAccount(BankAccount accountA, BankAccount accountB) {\nreturn accountA == accountB;}", "query_type": "code"} +{"_id": "code_q_000082", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\n...\nDriverManager.getConnection(url, \"scott\", \"tiger\");\n...", "query_type": "code"} +{"_id": "code_q_000083", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nprivate void processFile(string fName)\n{\nBufferReader fil = new BufferReader(new FileReader(fName));\nString line;\nwhile ((line = fil.ReadLine()) != null)\n{\nprocessLine(line);}}", "query_type": "code"} +{"_id": "code_q_000084", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class FileUploadServlet extends HttpServlet {\n\n...\n\nprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\nresponse.setContentType(\"text/html\");\nPrintWriter out = response.getWriter();\nString contentType = request.getContentType();\n\n// the starting position of the boundary header\nint ind = contentType.indexOf(\"boundary=\");\nString boundary = contentType.substring(ind+9);\n\nString pLine = new String();\nString uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value\n\n// verify that content type is multipart form data\nif (contentType != null && contentType.indexOf(\"multipart/form-data\") != -1) {\n\n// extract the filename from the Http header\nBufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));\n...\npLine = br.readLine();\nString filename = pLine.substring(pLine.lastIndexOf(\"\\\\\"), pLine.lastIndexOf(\"\\\"\"));\n...\n\n// output the file to the local upload directory\ntry {\n\nBufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));\nfor (String li", "query_type": "code"} +{"_id": "code_q_000085", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic Cipher getRSACipher() {\nCipher rsa = null;\ntry {\nrsa = javax.crypto.Cipher.getInstance(\"RSA/NONE/NoPadding\");}\ncatch (java.security.NoSuchAlgorithmException e) {\nlog(\"this should never happen\", e);}\ncatch (javax.crypto.NoSuchPaddingException e) {\nlog(\"this should never happen\", e);}\nreturn rsa;}", "query_type": "code"} +{"_id": "code_q_000086", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class WebViewGUI extends Activity {\n\nWebView mainWebView;\n\npublic void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nmainWebView = new WebView(this);\nmainWebView.getSettings().setJavaScriptEnabled(true);\nmainWebView.addJavascriptInterface(new JavaScriptInterface(), \"userInfoObject\");\nmainWebView.loadUrl(\"file:///android_asset/www/index.html\");\nsetContentView(mainWebView);}\n\nfinal class JavaScriptInterface {\n\nJavaScriptInterface () {}\n\npublic String getUserInfo() {\nreturn currentUser.Info();}\n }\n }", "query_type": "code"} +{"_id": "code_q_000087", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\ndef main():\n\n sum = 0\n\n\t\t try:\n\n numbers = eval(input(\"Enter a comma-separated list of numbers: \"))\n\n\t\t except SyntaxError:\n\n\t\t print(\"Error: invalid input\")\n\n\t\t return\n\n for num in numbers:\n\n sum = sum + num\n\n print(f\"Sum of {numbers} = {sum}\")\n\n main()", "query_type": "code"} +{"_id": "code_q_000088", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nif LoginUser(){\n\n// Login successful\n\n\t\t RunProgram();\n } else {\n\n// Login unsuccessful\n\n\t\t LoginRetry();\n }", "query_type": "code"} +{"_id": "code_q_000089", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\nPassChkValid: begin\n\nif(hashValid) begin\n\nif(exp_hash == pass_hash) begin\n\npass_check = 1'b1;\n\t\t\t\t\t\tend else begin\n\npass_check = 1'b0;\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\tstate_d = Idle;\n\n\t\t\t\t\tend else begin\n\nstate_d = PassChkValid;\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t...", "query_type": "code"} +{"_id": "code_q_000091", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic double calculateReturnOnInvestment(double currentValue, double initialInvestment) {\n\ndouble returnROI = 0.0;\n\n // calculate return on investment\n\nreturnROI = currentValue - initialInvestment / initialInvestment;\n\nreturn returnROI;\n }", "query_type": "code"} +{"_id": "code_q_000092", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nstatic nonvolatile password_tries = NUM_RETRIES;\n\n do\n\n while (password_tries == 0) ; // Hang here if no more password tries\n\n password_ok = 0;\n\n for (i = 0; i < NUM_PW_DIGITS; i++)\n\n if (GetPasswordByte() == stored_password([i])\n\n\t\t password_ok |= 1; // Power consumption is different here\n\n else\n\n\t\t password_ok |= 0; // than from here\n\n end\n\n if (password_ok > 0)\n\n password_tries = NUM_RETRIES;\n\n break_to_Ok_to_proceed\n\n password_tries--;\n\n while (true)\n\n // Password OK", "query_type": "code"} +{"_id": "code_q_000094", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule register_write_once_example\n\n (\n\n input [15:0] Data_in,\n\n input Clk,\n\n input ip_resetn,\n\n input global_resetn,\n\n input write,\n\n output reg [15:0] Data_out\n\n );\n\n reg Write_once_status;\n\n always @(posedge Clk or negedge ip_resetn)\n\n if (~ip_resetn)\n\n begin\n\n\t\t\t\t\t\t\tData_out <= 16'h0000;\n\n\t\t\t\t\t\t\tWrite_once_status <= 1'b0;\n\n\t\t\t\t\t\t end\n\n else if (write & ~Write_once_status)\n\n begin\n\n\t\t\t\t\t\t\tData_out <= Data_in & 16'hFFFE; // Input data written to register after masking bit 0\n\n\t\t\t\t\t\t\tWrite_once_status <= 1'b1; // Write once status set after first write.\n\n\t\t\t\t\t\t end\n\n\t\t\t\t\t\telse if (~write)\n\n begin\n\n\t\t\t\t\t\t\tData_out[15:1] <= Data_out[15:1];\n\n\t\t\t\t\t\t\tData_out[0] <= Write_once_status;\n\n end\n\n\t\t\t\t\t", "query_type": "code"} +{"_id": "code_q_000095", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C#]\nint Division(int x, int y){\nreturn (x / y);}", "query_type": "code"} +{"_id": "code_q_000096", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic boolean isReorderNeeded(String bookISBN, int rateSold) {\n\nboolean isReorder = false;\n\nint minimumCount = 10;\nint days = 0;\n\n // get inventory count for book\n\nint inventoryCount = inventory.getIventoryCount(bookISBN);\n\n // find number of days until inventory count reaches minimum\n\nwhile (inventoryCount > minimumCount) {\n\ninventoryCount = inventoryCount - rateSold;\ndays++;\n\n }\n\n // if number of days within reorder timeframe\n\n // set reorder return boolean to true\n\nif (days > 0 && days < 5) {\nisReorder = true;}\n\nreturn isReorder;\n }", "query_type": "code"} +{"_id": "code_q_000097", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nalways @(posedge clk_i)\n\nbegin\n\nif(~(rst_ni && ~jtag_unlock && ~rst_9))\n\nbegin\n\nfor (j=0; j < 6; j=j+1) begin\n\nreglk_mem[j] <= 'h0;\n\n end\n\n \tend\n...", "query_type": "code"} +{"_id": "code_q_000098", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nString sessionID = generateSessionId();\nCookie c = new Cookie(\"session_id\", sessionID);\nresponse.addCookie(c);", "query_type": "code"} +{"_id": "code_q_000101", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C++]\nint outputStringToFile(char *output, char *filename) {\n\nopenFileToWrite(filename);\nwriteToFile(output);\ncloseFile(filename);\n }", "query_type": "code"} +{"_id": "code_q_000102", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nvoid do_something_recursive (int flg)\n\n\t {\n\n\t ... // Do some real work here, but the value of flg is unmodified\n\n\t if (flg) { do_something_recursive (flg); } // flg is never modified so it is always TRUE - this call will continue until the stack explodes\n\n\t }\n\n\t int flag = 1; // Set to TRUE\n\n\t do_something_recursive (flag);", "query_type": "code"} +{"_id": "code_q_000103", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n// $user and $pass automatically set from POST request\n\nif (login_user($user,$pass)) {\n$authorized = true;}\n\n ...\n\nif ($authorized) {\ngeneratePage();}", "query_type": "code"} +{"_id": "code_q_000104", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\n// Method called from servlet to obtain product information\n\npublic String displayProductSummary(int index) {\n\nString productSummary = new String(\"\");\n\ntry {\nString productSummary = getProductSummary(index);\n\n} catch (Exception ex) {...}\n\nreturn productSummary;\n }\n\npublic String getProductSummary(int index) {\nreturn products[index];}", "query_type": "code"} +{"_id": "code_q_000108", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$filename = $_GET['file']; // User-controlled input\n\n\t\t\t\t\techo file_get_contents($filename); // Read and display the file contents", "query_type": "code"} +{"_id": "code_q_000109", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nIntent intent = new Intent();\nintent.setAction(\"com.example.OpenURL\");\nintent.putExtra(\"URL_TO_OPEN\", url_string);\nsendOrderedBroadcastAsUser(intent);", "query_type": "code"} +{"_id": "code_q_000111", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\ndouble divide(double x, double y){\nreturn x/y;}", "query_type": "code"} +{"_id": "code_q_000112", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule foo_bar(data_out, usr_id, data_in, clk, rst_n);\n\n \t\t\toutput reg [7:0] data_out;\n\n \t\t\tinput wire [2:0] usr_id;\n\n \t\t\tinput wire [7:0] data_in;\n\n \t\t\tinput wire clk, rst_n;\n\n \t\t\twire grant_access;\n\n \t\t\talways @ (posedge clk or negedge rst_n)\n\n \t\t\tbegin\n\n\t\t\t\t if (!rst_n)\n\n\t\t\t\t\tdata_out = 0;\n\n\t\t\t\t else\n\n\t\t\t\t\tdata_out = (grant_access) ? data_in : data_out;\n\n\t\t\t\t\tassign grant_access = (usr_id == 3'h4) ? 1'b1 : 1'b0;\n\n\t\t\t end\n\n\t\t\t endmodule", "query_type": "code"} +{"_id": "code_q_000113", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Rust]\nfn rec_float(y: f64, z: f64) -> f64\n\n\t\t {\n\n\t\t\t108.0 - ((815.0 - 1500.0 / z) / y);\n\n\t\t }\n\n\t\t fn float_calc(turns: usize) -> f64\n\n\t\t {\n\n\t\t\tlet mut x: Vec = vec![4.0, 4.25];\n\n\t\t\t(2..turns + 1).for_each(|number|\n\n\t\t\t{\n\n\t\t\t x.push(rec_float(x[number - 1], x[number - 2]));\n\n\t\t\t});\n\n\t\t\tx[turns]\n\n\t\t }", "query_type": "code"} +{"_id": "code_q_000114", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class RedirectServlet extends HttpServlet {\n\nprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\nString query = request.getQueryString();\nif (query.contains(\"url\")) {\nString url = request.getParameter(\"url\");\nresponse.sendRedirect(url);}}\n }", "query_type": "code"} +{"_id": "code_q_000116", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $test_string = \"Bad characters: \\$\\@\\#\";\n\n my $bdrslt = $test_string;\n\n $bdrslt =~ /^(\\w+\\s?)*$/i;", "query_type": "code"} +{"_id": "code_q_000117", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C++]\nchar* readfile (char *filename) {\n\ntry {\n\n// open input file\nifstream infile;\ninfile.open(filename);\n\nif (!infile.is_open()) {\nthrow \"Unable to open file \" + filename;}\n\n// get length of file\ninfile.seekg (0, ios::end);\nint length = infile.tellg();\ninfile.seekg (0, ios::beg);\n\n// allocate memory\nchar *buffer = new char [length];\n\n// read data from file\ninfile.read (buffer,length);\n\nif (!infile.good()) {\nthrow \"Unable to read from file \" + filename;}\n\ninfile.close();\n\nreturn buffer;\n }\ncatch (...) {\n/* bug: insert code to handle this later */}\n }", "query_type": "code"} +{"_id": "code_q_000118", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class BankAccount {\n\n // variable for bank account balance\n\nprivate double accountBalance;\n\n // constructor for BankAccount\n\npublic BankAccount() {\naccountBalance = 0;}\n\n // method to deposit amount into BankAccount\n\npublic void deposit(double depositAmount) {\n\ndouble newBalance = accountBalance + depositAmount;\naccountBalance = newBalance;\n }\n\n // method to withdraw amount from BankAccount\n\npublic void withdraw(double withdrawAmount) {\n\ndouble newBalance = accountBalance - withdrawAmount;\naccountBalance = newBalance;\n }\n\n // other methods for accessing the BankAccount object\n\n...\n }", "query_type": "code"} +{"_id": "code_q_000119", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$birthday = $_GET['birthday'];\n$homepage = $_GET['homepage'];\necho \"Birthday: $birthday
    Homepage:
    click here\"", "query_type": "code"} +{"_id": "code_q_000120", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define DIR \"/restricted/directory\"\n\nchar cmd[500];\nsprintf(cmd, \"ls -l %480s\", DIR);\n\n /* Raise privileges to those needed for accessing DIR. */\n\nRaisePrivileges(...);\nsystem(cmd);\nDropPrivileges(...);\n...", "query_type": "code"} +{"_id": "code_q_000122", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nmy $Username = GetUntrustedInput();\n$Username =~ s/^\\.\\.\\///;\nmy $filename = \"/home/user/\" . $Username;\nReadAndSendFile($filename);", "query_type": "code"} +{"_id": "code_q_000123", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n...\n\n if (signature_matches) // <-Glitch Here\n\n {\n\n load_runtime_firmware();\n\n }\n\n else\n\n {\n\n do_not_load_runtime_firmware();\n\n }\n\n ...", "query_type": "code"} +{"_id": "code_q_000124", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nalways_comb @ (posedge clk)\n\n begin\n\n assign check_pass[3:0] = 4'b0;\n\n for (i = 0; i < 4; i++) begin\n\n \tif (entered_pass[(i*8 - 1) : i] eq golden_pass([i*8 - 1) : i])\n\n\t\t\t assign check_pass[i] = 1;\n\n \t continue;\n\n \telse\n\n \t assign check_pass[i] = 0;\n\n \t break;\n\n \tend\n\n assign grant_access = (check_pass == 4'b1111) ? 1'b1: 1'b0;\n\n end", "query_type": "code"} +{"_id": "code_q_000125", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nIntent intent = new Intent();\nintent.setAction(\"com.example.BackupUserData\");\nintent.setData(file_uri);\nintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);\nsendBroadcast(intent);", "query_type": "code"} +{"_id": "code_q_000126", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class DatabaseConnection {\n\nprivate static final String CONNECT_STRING = \"jdbc:mysql://localhost:3306/mysqldb\";\nprivate Connection conn = null;\n\npublic DatabaseConnection() {\n}\n\npublic void openDatabaseConnection() {\ntry {\nconn = DriverManager.getConnection(CONNECT_STRING);} catch (SQLException ex) {...}}\n\n// Member functions for retrieving database connection and accessing database\n...\n }", "query_type": "code"} +{"_id": "code_q_000128", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\ntry {\ndoExchange();}\ncatch (Exception e) {\nlogger.error(\"doExchange failed\", e);}", "query_type": "code"} +{"_id": "code_q_000129", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#include \n#include \n#include \n\nint main() {\n\nwchar_t wideString[] = L\"The spazzy orange tiger jumped \" \\\n\"over the tawny jaguar.\";\nwchar_t *newString;\n\nprintf(\"Strlen() output: %d\\nWcslen() output: %d\\n\",\nstrlen(wideString), wcslen(wideString));\n\n/* Wrong because the number of chars in a string isn't related to its length in bytes //\nnewString = (wchar_t *) malloc(strlen(wideString));\n*/\n\n/* Wrong because wide characters aren't 1 byte long! //\nnewString = (wchar_t *) malloc(wcslen(wideString));\n*/\n\n/* Wrong because wcslen does not include the terminating null */\nnewString = (wchar_t *) malloc(wcslen(wideString) * sizeof(wchar_t));\n\n/* correct! */\nnewString = (wchar_t *) malloc((wcslen(wideString) + 1) * sizeof(wchar_t));\n\n/* ... */\n }", "query_type": "code"} +{"_id": "code_q_000130", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nXPath xpath = XPathFactory.newInstance().newXPath();\nXPathExpression xlogin = xpath.compile(\"//users/user[login/text()='\" + login.getUserName() + \"' and password/text() = '\" + login.getPassword() + \"']/home_dir/text()\");\nDocument d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(\"db.xml\"));\nString homedir = xlogin.evaluate(d);", "query_type": "code"} +{"_id": "code_q_000131", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\n$transfer_amount = GetTransferAmount();\n$balance = GetBalanceFromDatabase();\n\nif ($transfer_amount < 0) {\nFatalError(\"Bad Transfer Amount\");}\n$newbalance = $balance - $transfer_amount;\nif (($balance - $transfer_amount) < 0) {\nFatalError(\"Insufficient Funds\");}\nSendNewBalanceToDatabase($newbalance);\nNotifyUser(\"Transfer of $transfer_amount succeeded.\");\nNotifyUser(\"New balance: $newbalance\");", "query_type": "code"} +{"_id": "code_q_000132", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nassign addr_auth = (address == 32'hF00) ? 1: 0;", "query_type": "code"} +{"_id": "code_q_000134", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define FAIL 0\n#define SUCCESS 1\n#define ERROR -1\n#define MAX_MESSAGE_SIZE 32\n\nint processMessage(char **message)\n{\n\nint result = SUCCESS;\n\nint length = getMessageLength(message[0]);\nchar *messageBody;\n\nif ((length > 0) && (length < MAX_MESSAGE_SIZE)) {\n\nmessageBody = (char*)malloc(length*sizeof(char));\nmessageBody = &message[1][0];\n\nint success = processMessageBody(messageBody);\n\nif (success == ERROR) {\nresult = ERROR;\nfree(messageBody);}\n }\nelse {\nprintf(\"Unable to process message; invalid message length\");\nresult = FAIL;}\n\nif (result == ERROR) {\nlogError(\"Error processing message\", messageBody);}\n\nreturn result;\n }", "query_type": "code"} +{"_id": "code_q_000135", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nvoid parse_data(char *untrusted_input){\n\nint m, n, error;\nerror = sscanf(untrusted_input, \"%d:%d\", &m, &n);\nif ( EOF == error ){\ndie(\"Did not specify integer value. Die evil hacker!\\n\");}\n\n /* proceed assuming n and m are initialized correctly */\n\n }", "query_type": "code"} +{"_id": "code_q_000136", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$id = $_COOKIE[\"mid\"];\nmysql_query(\"SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'\");", "query_type": "code"} +{"_id": "code_q_000137", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nString ctl = request.getParameter(\"ctl\");\n\n\t\t\t\t\tClass cmdClass = Class.forName(ctl + \"Command\");\n\n\t\t\t\t\tWorker ao = (Worker) cmdClass.newInstance();\n\n\t\t\t\t\tao.doAction(request);\n\n[Java]\nString ctl = request.getParameter(\"ctl\");\n\n\t\t\t\t Class cmdClass = Class.forName(ctl + \"Command\");\n\n\t\t\t\t Worker ao = (Worker) cmdClass.newInstance();\n\n\t\t\t\t ao.checkAccessControl(request);\n\n\t\t\t\t ao.doAction(request);", "query_type": "code"} +{"_id": "code_q_000139", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nstruct node {\nint data;\nstruct node* next;};\n\n // Returns the number of nodes in a linked list from\n\n // the given pointer to the head of the list.\n\nint size(struct node* head) {\nstruct node* current = head;\nstruct node* tail;\nwhile (current != NULL) {\ntail = current;\ncurrent = current->next;}\nreturn tail - head;}\n\n // other methods for manipulating the list\n\n...", "query_type": "code"} +{"_id": "code_q_000140", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\n...\n\n // update sales database for number of product sold with product ID\n\npublic void updateSalesForProduct(String productID, int amountSold) {\n\n // get the total number of products in inventory database\n\nint productCount = inventory.getProductCount(productID);\n\n // convert integer values to short, the method for the\n\n // sales object requires the parameters to be of type short\n\nshort count = (short) productCount;\nshort sold = (short) amountSold;\n\n // update sales database for product\n\nsales.updateSalesCount(productID, count, sold);\n }\n...", "query_type": "code"} +{"_id": "code_q_000141", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JavaScript]\nlet sessionId = generateSessionId()\n\n let cookieOptions = { domain: 'example.com' }\n\n response.cookie('sessionid', sessionId, cookieOptions)", "query_type": "code"} +{"_id": "code_q_000142", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C++]\n#define MAX_PASSWORD_LENGTH 15\n#define MAX_USERNAME_LENGTH 15\n\nclass UserAccount\n{\n\npublic:\n\nUserAccount(char *username, char *password)\n{\nif ((strlen(username) > MAX_USERNAME_LENGTH) ||\n(strlen(password) > MAX_PASSWORD_LENGTH)) {\nExitError(\"Invalid username or password\");}\nstrcpy(this->username, username);\nstrcpy(this->password, password);}\n\nint authorizeAccess(char *username, char *password)\n{\n\nif ((strlen(username) > MAX_USERNAME_LENGTH) ||\n(strlen(password) > MAX_PASSWORD_LENGTH)) {\nExitError(\"Invalid username or password\");}\n\n // if the username and password in the input parameters are equal to\n\n // the username and password of this account class then authorize access\n\nif (strcmp(this->username, username) ||\nstrcmp(this->password, password))\nreturn 0;\n\n // otherwise do not authorize access\n\nelse\nreturn 1;\n\n }\n\nchar username[MAX_USERNAME_LENGTH+1];\nchar password[MAX_PASSWORD_LENGTH+1];\n };", "query_type": "code"} +{"_id": "code_q_000143", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\n$fileName = \"secretFile.out\";\n\nif (-e $fileName) {\nchmod 0777, $fileName;}\n\nmy $outFH;\nif (! open($outFH, \">>$fileName\")) {\nExitError(\"Couldn't append to $fileName: $!\");}\nmy $dateString = FormatCurrentTime();\nmy $status = IsHostAlive(\"cwe.mitre.org\");\nprint $outFH \"$dateString cwe status: $status!\\n\";\nclose($outFH);", "query_type": "code"} +{"_id": "code_q_000144", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define PATH_SIZE 60\n\nchar filename[PATH_SIZE];\n\nfor(i=0; i<=PATH_SIZE; i++) {\n\n char c = fgetc(stdin);\n\n\t\t if (c == EOF) {\n\n\t\t filename[i] = '\\0';\n\n\t\t }\n\n\t\t else {\n\n\t\t filename[i] = c;\n\n\t\t }\n\n\t\t }", "query_type": "code"} +{"_id": "code_q_000145", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nif (inputClass.getClass().getName().equals(\"TrustedClassName\")) {\n\n // Do something assuming you trust inputClass\n\n // ...\n\n }", "query_type": "code"} +{"_id": "code_q_000146", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[XML]\n\n\n
    \n\n\n\n\n\n\n\n\n\nmask\n[a-zA-Z]{2}\n\n\n\nmask\n\\d{5}
    ", "query_type": "code"} +{"_id": "code_q_000148", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JSON]\n{\n\n\t\t\t\t\"model\": \"my-coding-model\",\n\n\t\t\t\t\"context_window\": 8192,\n\n\t\t\t\t\"max_output_tokens\": 4096,\n\n\t\t\t\t\"temperature\", 1.5,\n\n\t\t\t\t...\n\n\t\t\t }", "query_type": "code"} +{"_id": "code_q_000149", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define SUCCESS (1)\n#define FAILURE (0)\n\nint contains_char(char c){\n\nchar *str;\nstr = (char*)malloc(20*sizeof(char));\nstrcpy(str, \"Search Me!\");\nwhile( *str != NULL){\n\nif( *str == c ){\n\n /* matched char, free string and return success */\n\nfree(str);\nreturn SUCCESS;\n }\n\n /* didn't match yet, increment pointer and try next char */\n\nstr = str + 1;\n }\n\n /* we did not match the char in the string, free mem and return failure */\n\nfree(str);\nreturn FAILURE;\n }", "query_type": "code"} +{"_id": "code_q_000150", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class Main {\n\n\t\t public static void main(String[] args) {\n\n\t\t int pt_weight = 83;\n\n\t\t int mg_per_kg = 3;\n\n\t\t int daily_dose = 0;\n\n\t\t // Add the patient weight and Mg/Kg to calculate the correct daily dose\n\n\t\t daily_dose = pt_weight * mg_per_kg;\n\n return dosage;\n\n }\n\n }", "query_type": "code"} +{"_id": "code_q_000152", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n#define FAIL 0\n#define SUCCESS 1\n\n...\n\nint validateUser(char *username, char *password) {\n\nint isUser = FAIL;\n\n // call method to authenticate username and password\n\n // if authentication fails then return failure otherwise return success\n\nif (isUser = AuthenticateUser(username, password) == FAIL) {\nreturn isUser;}\nelse {\nisUser = SUCCESS;}\n\nreturn isUser;\n }", "query_type": "code"} +{"_id": "code_q_000153", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\nalways_ff @(posedge clk_i) begin\n\nif (req_i) begin\n\nif (!we_i) begin\n\nraddr_q <= addr_i[$clog2(RomSize)-1+3:3];\n\t\t\t\t\t\t\t\t\t\tend else begin\n\nmem[addr_i[$clog2(RomSize)-1+3:3]] <= wdata_i;\n\t\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\tend\n \t...\n\n\t\t\t\t\t\t\t\t// this prevents spurious Xes from propagating into the speculative fetch stage of the core\n\nassign rdata_o = (raddr_q < RomSize) ? mem[raddr_q] : '0;\n\n\t\t\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000156", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nint intPrimitive;\nshort shortPrimitive;\nintPrimitive = (int)(~((int)0) ^ (1 << (sizeof(int)*8-1)));\nshortPrimitive = intPrimitive;\nprintf(\"Int MAXINT: %d\\nShort MAXINT: %d\\n\", intPrimitive, shortPrimitive);", "query_type": "code"} +{"_id": "code_q_000157", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\n assign key_big0 = debug_mode_i ? 192'b0 : {key0[0],\n\n key0[1], key0[2], key0[3], key0[4], key0[5]};\n\n assign key_big1 = debug_mode_i ? 192'b0 : {key1[0],\n\n key1[1], key1[2], key1[3], key1[4], key1[5]};\n\n assign key_big2 = {key2[0], key2[1], key2[2],\n\n key2[3], key2[4], key2[5]};\n\n ...\n\n assign key_big = key_sel[1] ? key_big2 : ( key_sel[0] ?\n\n key_big1 : key_big0 );\n\n ...", "query_type": "code"} +{"_id": "code_q_000158", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\n...\n\n\t\t\t\t\t\tbootrom i_bootrom_patch (\n\n\t\t\t\t\t\t\t.clk_i ,\n\n\t\t\t\t\t\t\t.req_i ( rom_req ),\n\n\t\t\t\t\t\t\t.addr_i ( rom_addr ),\n\n\t\t\t\t\t\t\t.rdata_o ( rom_rdata_patch )\n\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tbootrom_linux i_bootrom_linux (\n\n\t\t\t\t\t\t\t.clk_i ,\n\n\t\t\t\t\t\t\t.req_i ( rom_req ),\n\n\t\t\t\t\t\t\t.addr_i ( rom_addr ),\n\n\t\t\t\t\t\t\t.rdata_o ( rom_rdata_linux )\n\n\t\t\t\t\t\t);\n\n\t\t\t\t\tassign rom_rdata = (ariane_boot_sel_i) ? rom_rdata_linux : rom_rdata_linux;\n\n\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000159", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nvoid interrupt_handler(int irq) {\n\n\t\t\t\t\t\tif (irq_priority[irq] < current_priority) {\n\n\t\t\t\t\t\t return;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprocess_interrupt(irq);\n\n\t\t\t\t\t }", "query_type": "code"} +{"_id": "code_q_000160", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Python]\ndef dispatchCommand(command, user, args):\n\nif command == 'Login':\nloginUser(args)\nreturn\n\n # user has requested a file\n\nif command == 'Retrieve_file':\n\n\t\t\t if authenticated(user) and ownsFile(user,args):\n\nsendFile(args)\nreturn\n\nif command == 'List_files':\nlistFiles(args)\nreturn\n\n ...", "query_type": "code"} +{"_id": "code_q_000161", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nchar username[USERNAME_SIZE];\nchar password[PASSWORD_SIZE];\n\nwhile (isValidUser == 0) {\n\nif (getNextMessage(socket, username, USERNAME_SIZE) > 0) {\nif (getNextMessage(socket, password, PASSWORD_SIZE) > 0) {\nisValidUser = AuthenticateUser(username, password);}}\n }\nreturn(SUCCESS);", "query_type": "code"} +{"_id": "code_q_000163", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class RegistrationForm extends org.apache.struts.action.ActionForm {\n\n// private variables for registration form\nprivate String name;\nprivate String email;\n...\n\npublic RegistrationForm() {\nsuper();}\n\n// getter and setter methods for private variables\n...\n }", "query_type": "code"} +{"_id": "code_q_000164", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$username = $_GET['username'];\necho '
    Welcome, ' . $username . '
    ';", "query_type": "code"} +{"_id": "code_q_000165", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nFile: OrderPgData.java\n\n\t\t\t public class OrderPgData {\n\n\t\t\t String PgType;\n\n\t\t\t int productPrice;\n\n\t\t\t int paymentAmount;\n\n\t\t\t private boolean isPaymentAmountTampered;\n\n\t\t\t\tpublic boolean getIsPaymentAmountTampered() {\n\n\t\t\t\t return this.isPaymentAmountTampered;\n\n\t\t\t\t}\n\n\t\t\t ...\n\n\t\t\t public void validateAmount() {\n\n\t\t\t ... [sets this.setIsPaymentAmountTampered to true or false depending on whether the product price matches the payment amount]\n\n\t\t\t }\n\n[Java]\nFile: PgServiceResolver.java\n\n\t\t\t public class PgServiceResolver {\n\n\t\t\t public OrderPgData getOrderPgDataByPgType(String pgType, int productPrice, int paymentAmount) {\n\n\t\t\t\t...\n\n\t\t\t\tswitch(pgType) {\n\n\t\t\t\t case \"card\":\n\n\t\t\t\t System.out.println(\"In \"+pgType+\" payment logic, orderPgData does not verify whether the product amount and payment amount have been tampered with.\");\n\n\t\t\t\t break;\n\n\t\t\t\t case \"paypal\":\n\n\t\t\t\t System.out.println(\"In \"+pgType+\" payment logic, orderPgData verifies whether the product amount and payment amount have been tampered with.\");\n\n\t\t\t\t orderP", "query_type": "code"} +{"_id": "code_q_000166", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$username = $_POST['username'];\n$picSource = $_POST['picsource'];\n$picAltText = $_POST['picalttext'];\n\n ...\n\necho \"Welcome, \" . htmlentities($username) .\"\";\necho \"\". htmlentities($picAltText) . ';\n\n ...", "query_type": "code"} +{"_id": "code_q_000168", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\n/* Ignore this weakness (hard-coded password) and this weakness (use of password system for authentication) for this example. */\n\nchar *username = \"admin\";\nchar *pass = \"password\";\n\nint AuthenticateUser(char *inUser, char *inPass) {\nif (strncmp(username, inUser, strlen(inUser))) {\nlogEvent(\"Auth failure of username using strlen of inUser\");\nreturn(AUTH_FAIL);}\nif (! strncmp(pass, inPass, strlen(inPass))) {\nlogEvent(\"Auth success of password using strlen of inUser\");\nreturn(AUTH_SUCCESS);}\nelse {\nlogEvent(\"Auth fail of password using sizeof\");\nreturn(AUTH_FAIL);}}\n\nint main (int argc, char **argv) {\n\n int authResult;\n\nif (argc < 3) {\nExitError(\"Usage: Provide a username and password\");}\nauthResult = AuthenticateUser(argv[1], argv[2]);\nif (authResult == AUTH_SUCCESS) {\nDoAuthenticatedTask(argv[1]);}\nelse {\nExitError(\"Authentication failed\");}}", "query_type": "code"} +{"_id": "code_q_000170", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic BankAccount createBankAccount(String accountNumber, String accountType,\nString accountName, String accountSSN, double balance) {\n\nBankAccount account = new BankAccount();\naccount.setAccountNumber(accountNumber);\naccount.setAccountType(accountType);\naccount.setAccountOwnerName(accountName);\naccount.setAccountOwnerSSN(accountSSN);\naccount.setBalance(balance);\n\nreturn account;\n }", "query_type": "code"} +{"_id": "code_q_000173", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\n@Entity\npublic class Customer {\n\nprivate String id;\nprivate String firstName;\nprivate String lastName;\nprivate Address address;\n\npublic Customer() {\n}\n\npublic Customer(String id, String firstName, String lastName) {...}\n\n@Id\npublic String getCustomerId() {...}\n\npublic void setCustomerId(String id) {...}\n\npublic String getFirstName() {...}\n\npublic void setFirstName(String firstName) {...}\n\npublic String getLastName() {...}\n\npublic void setLastName(String lastName) {...}\n\n@OneToOne()\npublic Address getAddress() {...}\n\npublic void setAddress(Address address) {...}\n\n}", "query_type": "code"} +{"_id": "code_q_000174", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nparameter MEM_SIZE = 100;\n\n\t\t\t\t\tlocalparam JTAG_OFFSET = 81;\n\n\t\t\t\t\tconst logic [MEM_SIZE-1:0][31:0] mem = {\n\n\t\t\t\t\t\t// JTAG expected HMAC hash\n\n\t\t\t\t\t\t32'h49ac13af, 32'h1276f1b8, 32'h6703193a, 32'h65eb531b,\n\n\t\t\t\t\t\t32'h3025ccca, 32'h3e8861f4, 32'h329edfe5, 32'h98f763b4,\n\n\t\t\t\t\t...\n\n\t\t\t\t\tassign jtag_hash_o = {mem[JTAG_OFFSET-1],mem[JTAG_OFFSET-2],mem[JTAG_OFFSET-3],\n\n\t\t\t\t\tmem[JTAG_OFFSET-4],mem[JTAG_OFFSET-5],mem[JTAG_OFFSET-6],mem[JTAG_OFFSET-7],mem[JTAG_OFFSET-8]};\n\n\t\t\t\t\t...", "query_type": "code"} +{"_id": "code_q_000175", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[JavaScript]\nfunction setValueByPath (object, path, value) {\n\n\t\t\t\t\t const pathArray = path.split(\".\");\n\n\t\t\t\t\t const attributeToSet = pathArray.pop();\n\n\t\t\t\t\t let objectToModify = object;\n\n\t\t\t\t\t for (const attr of pathArray) {\n\nif (typeof objectToModify[attr] !== 'object') {\n\nobjectToModify[attr] = {};\n\n\t\t\t\t\t }\n\n\t\t\t\t\t objectToModify = objectToModify[attr];\n\n\t\t\t\t\t }\n\n\t\t\t\t\t objectToModify[attributeToSet] = value;\n\n\t\t\t\t\t return object;\n\n\t\t\t\t\t}\n\n[JavaScript]\nsetValueByPath({}, \"__proto__.isAdmin\", true)\n\n\t\t\t\t\t setValueByPath({}, \"constructor.prototype.isAdmin\", true)", "query_type": "code"} +{"_id": "code_q_000176", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\nvar $i = 65;\n\n var $s1 = \"65\";\n\n if ($i === $s1)\n\n {\n\necho '($i === $s1) is TRUE'. \"\\n\";\n }\n\n else\n\n {\n\necho '($i === $s1) is FALSE'. \"\\n\";\n }", "query_type": "code"} +{"_id": "code_q_000177", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\nprivate File readFile = null;\n\npublic void setInputFile(String inputFile) {\n\n // create readFile File object from string containing name of file\n\n }\n\npublic void readFromFile() {\n\ntry {\n\nreader = new FileReader(readFile);\n\n // read input file\n\n } catch (FileNotFoundException ex) {...}\n }", "query_type": "code"} +{"_id": "code_q_000178", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\nmodule siso(clk,rst,a,q);\n\n input a;\n\n input clk,rst;\n\n output q;\n\n reg q;\n\n always@(posedge clk,posedge rst)\n\n begin\n\n\t\tif(rst==1'b1)\n\n q<1'b0;\n\n\t\telse\n\n q 20) {\n\n\t\t throw new Exception(\"Username too long\");\n\n\t\t }\n\n\t\t } catch (Exception $e) {\n\n\t\t error_log(\"User registration failed: \" . $username);\n\t\t }", "query_type": "code"} +{"_id": "code_q_000184", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$requestingIP = '0.0.0.0';\nif (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {\n$requestingIP = $_SERVER['HTTP_X_FORWARDED_FOR'];\n\nelse{\n$requestingIP = $_SERVER['REMOTE_ADDR'];}\n\nif(in_array($requestingIP,$ipAllowlist)){\ngeneratePage();\nreturn;}\nelse{\necho \"You are not authorized to view this page\";\nreturn;}", "query_type": "code"} +{"_id": "code_q_000185", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic int computeAverageResponseTime (int totalTime, int numRequests) {\nreturn totalTime / numRequests;}", "query_type": "code"} +{"_id": "code_q_000187", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Perl]\nuse CGI qw(:standard);\n$name = param('name');\n$nslookup = \"/path/to/nslookup\";\nprint header;\nif (open($fh, \"$nslookup $name|\")) {\nwhile (<$fh>) {\nprint escapeHTML($_);\nprint \"
    \\n\";}\nclose($fh);}", "query_type": "code"} +{"_id": "code_q_000188", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n", "query_type": "code"} +{"_id": "code_q_000190", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[SystemVerilog]\nmodule dmi_jtag(...)(...);\n\n\t\t\t\t\t...\n\n\t\t\t\t\t\t\t\tPassChkValid: begin\n\n\t\t\t\t\t\t\t\tif(hashValid) begin\n\n\t\t\t\t\t\t\t\t\t\tif(exp_hash == pass_hash) begin\n\n\t\t\t\t\t\t\t\t\t\t\tpass_check = 1'b1;\n\n\t\t\t\t\t\t\t\t\t\tend else begin\n\n\t\t\t\t\t\t\t\t\t\t\tpass_check = 1'b0;\n\n\t\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t\t\tstate_d = Idle;\n\n\t\t\t\t\t\t\t\t\tend else begin\n\n\t\t\t\t\t\t\t\t\tstate_d = PassChkValid;\n\n\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t...\n\n\t\t\t\t\t\thmac hmac(\n\n\t\t\t\t\t...\n\n\t\t\t\t\t\t\t.key_i(256'h24e6fa2254c2ff632a41b...),\n\n\t\t\t\t\t...\n\n\t\t\t\t\t\t);\n\n\t\t\t\t\t...\n\n\t\t\t\t\tendmodule", "query_type": "code"} +{"_id": "code_q_000191", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Verilog]\n// IP definition\n\n\t\t\t module tz_peripheral(clk, reset, data_in, data_in_security_level, ...);\n\n\t\t\t\tinput clk, reset;\n\n\t\t\t\tinput [31:0] data_in;\n\n\t\t\t\tinput data_in_security_level;\n\n\t\t\t\t...\n\n\t\t\t endmodule\n\n\t\t\t // Instantiation of IP in a parent system\n\n\t\t\t module soc(...)\n\n\t\t\t\t...\n\n\t\t\t\ttz_peripheral u_tz_peripheral(\n\n\t\t\t\t .clk(clk),\n\n\t\t\t\t .rst(rst),\n\n\t\t\t\t .data_in(rdata),\n\n\t\t\t\t //Copy-and-paste error or typo grounds data_in_security_level (in this example 0=secure, 1=non-secure) effectively promoting all data to \"secure\")\n\n\t\t\t\t .data_in_security_level(1'b0),\n\n\t\t\t\t);\n\n\t\t\t\t...\n\n\t\t\t endmodule", "query_type": "code"} +{"_id": "code_q_000192", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C]\nchar firstname[20];\nchar lastname[20];\nchar fullname[40];\n\nfullname[0] = '\\0';\n\nstrncat(fullname, firstname, 20);\nstrncat(fullname, lastname, 20);", "query_type": "code"} +{"_id": "code_q_000193", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class OuterClass {\n\n // private member variables of OuterClass\n\nprivate String memberOne;\nprivate String memberTwo;\n\n // constructor of OuterClass\n\npublic OuterClass(String varOne, String varTwo) {\nthis.memberOne = varOne;\nthis.memberTwo = varTwo;}\n\n // InnerClass is a member inner class of OuterClass\n\nprivate class InnerClass {\nprivate String innerMemberOne;\n\npublic InnerClass(String innerVarOne) {\nthis.innerMemberOne = innerVarOne;}\n\npublic String concat(String separator) {\n\n // InnerClass has access to private member variables of OuterClass\n\nSystem.out.println(\"Value of memberOne is: \" + memberOne);\nreturn OuterClass.this.memberTwo + separator + this.innerMemberOne;}}}", "query_type": "code"} +{"_id": "code_q_000194", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class Main {\n\npublic static void main(String[] args) {\n\nint a = 1;\n\nint b = 0;\n\nint c = 0;\n\ntry {\n\nc = a / b;\n\n} catch(ArithmeticException ae) {\n\n}\n\n}\n\n}", "query_type": "code"} +{"_id": "code_q_000196", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class TrustedClass {\n\n...\n\n@Override\npublic boolean equals(Object obj) {\n\nboolean isEquals = false;\n\n // first check to see if the object is of the same class\n\nif (obj.getClass().getName().equals(this.getClass().getName())) {\n\n // then compare object fields\n\n...\nif (...) {\nisEquals = true;}\n }\n\nreturn isEquals;\n }\n\n...\n }", "query_type": "code"} +{"_id": "code_q_000198", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[C++]\nvoid foo(){\n\nBarObj *ptr = new BarObj()\n\n /* do some work with ptr here */\n\n...\n\nfree(ptr);\n }", "query_type": "code"} +{"_id": "code_q_000199", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[PHP]\n$discount = $_POST['discount'];\n\n\t\t $originalPrice = 100.00;\n\n\t\t $finalPrice = $originalPrice - ($originalPrice * $discount / 100);\n\n\t\t processPayment($finalPrice);", "query_type": "code"} +{"_id": "code_q_000200", "text": "Find a secure defensive implementation to replace this vulnerable code:\n[Java]\npublic class CloneClient {\n\npublic CloneClient() //throws\njava.lang.CloneNotSupportedException {\n\nTeacher t1 = new Teacher(\"guddu\",\"22,nagar road\");\n//...\n// Do some stuff to remove the teacher.\nTeacher t2 = (Teacher)t1.clone();\nSystem.out.println(t2.name);\n }\npublic static void main(String args[]) {\n\nnew CloneClient();\n }\n }\nclass Teacher implements Cloneable {\n\npublic Object clone() {\n\ntry {\nreturn super.clone();}\ncatch (java.lang.CloneNotSupportedException e) {\n\nthrow new RuntimeException(e.toString());\n }\n }\npublic String name;\npublic String clas;\npublic Teacher(String name,String clas) {\n\nthis.name = name;\nthis.clas = clas;\n }\n }", "query_type": "code"} +{"_id": "code_q_000201", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries who have the KRBTGT account password hash may forge Kerberos ticket-granting tickets (TGT), also known as a the component.(Citation: AdSecurity Kerberos GT Aug 2015) Golden tickets enable adversaries to generate authentication material for any account in Active Directory.(Citation: CERT-EU the component Protection) Using a the component, adversaries are then able to request ticket granting service (TGS) tickets, which enable access to specific resources. Golden tickets require adversaries to interact with the Key Distribution Center (KDC) in order to obtain TGS.(Citation: ADSecurity Detecting Forged Tickets) The KDC service runs all on domain controllers that are part of an Active Directory domain. KRBTGT is the Kerberos Key Distribution Center (KDC) service account and is resp", "query_type": "nl"} +{"_id": "code_q_000202", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may search network shares on computers they have compromised to find files of interest. Sensitive data can be collected from remote systems via shared network drives (host shared directory, network file server, etc.) that are accessible from the current system prior to Exfiltration. Interactive command shells may be in use, and common functionality within [cmd]( may be used to gather information.(Citation: Net Use)(Citation: Cybersecurity Advisory GRU Brute Force Campaign July 2021)\n\nTactics: collection\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000203", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse the the component (RTLO or RLO) character (U+202E) to disguise a string and/or file name to make it appear benign. RTLO is a non-printing Unicode character that causes the text that follows it to be displayed in reverse. For example, a Windows screensaver executable named March 25 \\u202Excod.scr will display as March 25 rcs.docx. A JavaScript file named photo_high_re\\u202Egnp.js will be displayed as photo_high_resj.png.(Citation: Infosecinstitute RTLO Technique) Adversaries may abuse the RTLO character as a means of tricking a user into executing what they think is a benign file type. A common use of this technique is with [Spearphishing Attachment]( File]( since it can trick both end users and defenders if they are ", "query_type": "nl"} +{"_id": "code_q_000204", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse mshta.exe to proxy execution of malicious .hta files and Javascript or VBScript through a trusted Windows utility. There are several examples of different types of threats leveraging mshta.exe during initial compromise and for execution of code.(Citation: Cylance Dust Storm)(Citation: Red Canary HTA Abuse Part Deux)(Citation: FireEye Attacks Leveraging HTA)(Citation: Airbus Security Kovter Analysis)(Citation: FireEye FIN7 April 2017) Mshta.exe is a utility that executes Microsoft HTML Applications (HTA) files.(Citation: Wikipedia HTML Application) HTAs are standalone applications that execute using the same models and technologies of Internet Explorer, but outside of the browser.(Citation: MSDN HTML Applications) Files may be executed by mshta.exe through an inline sc", "query_type": "nl"} +{"_id": "code_q_000205", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may target user email on local systems to collect sensitive information. Files containing email data can be acquired from a user’s local system, such as Outlook storage or cache files. Outlook stores data locally in offline data files with an extension of .ost. Outlook 2010 and later supports .ost file sizes up to 50GB, while earlier versions of Outlook support up to 20GB.(Citation: Outlook File Sizes) IMAP accounts in Outlook 2013 (and earlier) and POP accounts use Outlook Data Files (.pst) as opposed to .ost, whereas IMAP accounts in Outlook 2016 (and later) use .ost files. Both types of Outlook data files are typically stored in `C:\\Users\\\\Documents\\Outlook Files` or `C:\\Users\\\\AppData\\Local\\Microsoft\\Outlook`.(Citation: Microsoft Outlook Files)\n\nTactics:", "query_type": "nl"} +{"_id": "code_q_000206", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use an existing, legitimate external Web service to exfiltrate data rather than their primary command and control channel. Popular Web services acting as an exfiltration mechanism may give a significant amount of cover due to the likelihood that hosts within a network are already communicating with them prior to compromise. Firewall rules may also already exist to permit traffic to these services. Web service providers also commonly use SSL/TLS encryption, giving adversaries an added level of protection.\n\nTactics: exfiltration\n\nPlatforms: ESXi, Linux, macOS, Office Suite, SaaS, Windows", "query_type": "nl"} +{"_id": "code_q_000207", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may bypass UAC mechanisms to elevate process privileges on a system. Windows User Account Control (UAC) allows a program to elevate its privileges (tracked as integrity levels ranging from low to high) to perform a task under administrator-level permissions, possibly by prompting the user for confirmation. The impact to the user ranges from denying the operation under high enforcement to allowing the user to perform the action if they are in the local administrators group and click through the prompt or allowing them to enter an administrator password to complete the action.(Citation: TechNet How UAC Works) If the UAC protection level of a computer is set to anything but the highest level, certain Windows programs can elevate privileges or execute some elevated [Component Objec", "query_type": "nl"} +{"_id": "code_q_000208", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may use legitimate the component to establish an interactive command and control channel within a network. the component create a session between two trusted hosts through a graphical interface, a command line interaction, a protocol tunnel via development or management software, or hardware-level access such as KVM (Keyboard, Video, Mouse) over IP solutions. Desktop support software (usually graphical interface) and remote management software (typically command line interface) allow a user to control a computer remotely as if they are a local user inheriting the user or software permissions. This software is commonly used for troubleshooting, software installation, and system management.(Citation: Symantec Living off the Land)(Citation: CrowdStrike 2015 Global Threat Report)(", "query_type": "nl"} +{"_id": "code_q_000209", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may log user keystrokes to intercept credentials as the user types them. Keylogging is likely to be used to acquire credentials for new access opportunities when [OS Credential Dumping]( efforts are not effective, and may require an adversary to intercept keystrokes on a system for a substantial period of time before credentials can be successfully captured. In order to increase the likelihood of capturing credentials quickly, an adversary may also perform actions such as clearing browser cookies to force users to reauthenticate to systems.(Citation: Talos Kimsuky Nov 2021) Keylogging is the most prevalent type of input capture, with many different ways of intercepting keystrokes.(Citation: Adventures of a Keystroke) Some methods include: * Hooking API callbacks used for proces", "query_type": "nl"} +{"_id": "code_q_000210", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may disable or modify a firewall within a cloud environment to bypass controls that limit access to cloud resources. Cloud environments typically utilize restrictive security groups and firewall rules that only allow network activity from trusted IP addresses via expected ports and protocols. An adversary with appropriate permissions may introduce new firewall rules or policies to allow access into a victim cloud environment and/or move laterally from the cloud control plane to the data plane. For example, an adversary may use a script or utility that creates new ingress rules in existing security groups (or creates new security groups entirely) to allow any TCP/IP connectivity to a cloud-hosted instance. They may also remove networking limitations to support traffic associated", "query_type": "nl"} +{"_id": "code_q_000211", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gather credentials via APIs within a containers environment. APIs in these environments, such as the Docker API and Kubernetes APIs, allow a user to remotely manage their container resources and cluster components.(Citation: Docker API)(Citation: Kubernetes API) An adversary may access the Docker API to collect logs that contain credentials to cloud, container, and various other resources in the environment.(Citation: Unit 42 Unsecured Docker Daemons) An adversary with sufficient permissions, such as via a pod's service account, may also use the Kubernetes API to retrieve credentials from the Kubernetes API server. These credentials may include those needed for Docker API authentication or secrets from Kubernetes cluster components.\n\nTactics: credential-access\n\nPlatforms: C", "query_type": "nl"} +{"_id": "code_q_000212", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to gather information about the system language of a victim in order to infer the geographical location of that host. This information may be used to shape follow-on behaviors, including whether the adversary infects the target and/or attempts specific actions. This decision may be employed by malware developers and operators to reduce their risk of attracting the attention of specific law enforcement agencies or prosecution/scrutiny from other entities.(Citation: Malware System Language Check) There are various sources of data an adversary could use to infer system language, such as system defaults and keyboard layouts. Specific checks will vary based on the target and/or adversary, but may involve behaviors such as [Query Registry]( and calls to [Native API]( func", "query_type": "nl"} +{"_id": "code_q_000214", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse launchctl to execute commands or programs. Launchctl interfaces with launchd, the service management framework for macOS. Launchctl supports taking subcommands on the command-line, interactively, or even redirected from standard input.(Citation: Launchctl Man) Adversaries use launchctl to execute commands and programs as [Launch Agent]( or [Launch Daemon]( Common subcommands include: launchctl load,launchctl unload, and launchctl start. Adversaries can use scripts or manually run the commands launchctl load -w \"%s/Library/LaunchAgents/%s\" or /bin/launchctl load to execute [Launch Agent]( or [Launch Daemon]( Sofacy Komplex Trojan)(Citation: 20 macOS Common Tools and Techniques)\n\nTactics: execution\n\nPlatfo", "query_type": "nl"} +{"_id": "code_q_000215", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may exploit software vulnerabilities in client applications to execute code. Vulnerabilities can exist in software due to unsecure coding practices that can lead to unanticipated behavior. Adversaries can take advantage of certain vulnerabilities through targeted exploitation for the purpose of arbitrary code execution. Oftentimes the most valuable exploits to an offensive toolkit are those that can be used to obtain code execution on a remote system because they can be used to gain access to that system. Users will expect to see files related to the applications they commonly used to do work, so they are a useful target for exploit research and development because of their high utility. Several types exist: ### Browser-based Exploitation Web browsers are a common target throug", "query_type": "nl"} +{"_id": "code_q_000216", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use PubPrn to proxy execution of malicious remote files. PubPrn.vbs is a [Visual Basic]( script that publishes a printer to Active Directory Domain Services. The script may be signed by Microsoft and is commonly executed through the [Windows Command Shell]( via Cscript.exe. For example, the following code publishes a printer within the specified domain: cscript pubprn Printer1 LDAP://CN=Container1,DC=Domain1,DC=Com.(Citation: pubprn) Adversaries may abuse PubPrn to execute malicious payloads hosted on remote sites.(Citation: Enigma0x3 PubPrn Bypass) To do so, adversaries may set the second script: parameter to reference a scriptlet file (.sct) hosted on a remote site. An example command is pubprn.vbs 127.0.0.1 script: This behavi", "query_type": "nl"} +{"_id": "code_q_000217", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to take screen captures of the desktop to gather information over the course of an operation. Screen capturing functionality may be included as a feature of a remote access tool used in post-compromise operations. Taking a screenshot is also typically possible through native utilities or API calls, such as CopyFromScreen, xwd, or screencapture.(Citation: CopyFromScreen .NET)(Citation: Antiquated Mac Malware)\n\nTactics: collection\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000218", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may erase the contents of storage devices on specific systems or in large numbers in a network to interrupt availability to system and network resources. Adversaries may partially or completely overwrite the contents of a storage device rendering the data irrecoverable through the storage interface.(Citation: Novetta Blockbuster)(Citation: Novetta Blockbuster Destructive Malware)(Citation: DOJ Lazarus Sony 2018) Instead of wiping specific disk structures or files, adversaries with destructive intent may wipe arbitrary portions of disk content. To wipe disk content, adversaries may acquire direct access to the hard drive in order to overwrite arbitrarily sized portions of disk with random data.(Citation: Novetta Blockbuster Destructive Malware) Adversaries have also been observe", "query_type": "nl"} +{"_id": "code_q_000219", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may reveal credentials of accounts that have disabled Kerberos preauthentication by [Password Cracking]( Kerberos messages.(Citation: Harmj0y Roasting AS-REPs Jan 2017) Preauthentication offers protection against offline [Password Cracking]( When enabled, a user requesting access to a resource initiates communication with the Domain Controller (DC) by sending an Authentication Server Request (AS-REQ) message with a timestamp that is encrypted with the hash of their password. If and only if the DC is able to successfully decrypt the timestamp with the hash of the user’s password, it will then send an Authentication Server Response (AS-REP) message that contains the Ticket Granting Ticket (TGT) to the user. Part of the AS-REP message is signed with the user’s password.(Citation: ", "query_type": "nl"} +{"_id": "code_q_000221", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may delete files left behind by the actions of their intrusion activity. Malware, tools, or other non-native files dropped or created on a system by an adversary (ex: [Ingress Tool Transfer]( may leave traces to indicate to what was done within a network and how. Removal of these files can occur during an intrusion, or as part of a post-intrusion process to minimize the adversary's footprint. There are tools available from the host operating system to perform cleanup, but adversaries may use other tools as well.(Citation: Microsoft SDelete July 2016) Examples of built-in [Command and Scripting Interpreter]( functions include del on Windows, rm or unlink on Linux and macOS, and `rm` on ESXi.\n\nTactics: stealth\n\nPlatforms: ESXi, Linux, macOS,", "query_type": "nl"} +{"_id": "code_q_000223", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use the component to escalate privileges and bypass access controls. The Windows security identifier (SID) is a unique value that identifies a user or group account. SIDs are used by Windows security in both security descriptors and access tokens.(Citation: Microsoft SID) An account can hold additional SIDs in the SID-History Active Directory attribute, allowing inter-operable account migration between domains (e.g., all values in SID-History are included in access tokens).(Citation: Microsoft SID-History Attribute) With Domain Administrator (or equivalent) rights, harvested or well-known SID values(Citation: Microsoft Well Known SIDs Jun 2017) may be inserted into SID-History to enable impersonation of arbitrary users/groups such as Enterprise Administrators. This manipula", "query_type": "nl"} +{"_id": "code_q_000224", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to subvert Kerberos authentication by stealing or forging Kerberos tickets to enable [Pass the Ticket]( Kerberos is an authentication protocol widely used in modern Windows domain environments. In Kerberos environments, referred to as “realms”, there are three basic participants: client, service, and Key Distribution Center (KDC).(Citation: ADSecurity Kerberos Ring Decoder) Clients request access to a service and through the exchange of Kerberos tickets, originating from KDC, they are granted access after having successfully authenticated. The KDC is responsible for both authentication and ticket granting. Adversaries may attempt to abuse Kerberos by stealing tickets or forging tickets to enable unauthorized access. On Windows, the built-in klist utilit", "query_type": "nl"} +{"_id": "code_q_000225", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use [Valid Accounts]( to interact with remote systems using the component (WinRM). The adversary may then perform actions as the logged-on user. WinRM is the name of both a Windows service and a protocol that allows a user to interact with a remote system (e.g., run an executable, modify the Registry, modify services).(Citation: Microsoft WinRM) It may be called with the `winrm` command or by any number of programs such as PowerShell.(Citation: Jacobsen 2014) WinRM can be used as a method of remotely interacting with [Windows Management Instrumentation]( MSDN WMI)\n\nTactics: lateral-movement\n\nPlatforms: Windows", "query_type": "nl"} +{"_id": "code_q_000226", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may exploit remote services to gain unauthorized access to internal systems once inside of a network. Exploitation of a software vulnerability occurs when an adversary takes advantage of a programming error in a program, service, or within the operating system software or kernel itself to execute adversary-controlled code. A common goal for post-compromise the component is for lateral movement to enable access to a remote system. An adversary may need to determine if the remote system is in a vulnerable state, which may be done through [Network Service Discovery]( or other Discovery methods looking for common, vulnerable software that may be deployed in the network, the lack of certain patches that may indicate vulnerabilities, or security software that may be used to detect or", "query_type": "nl"} +{"_id": "code_q_000227", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may tamper with SIP and trust provider components to mislead the operating system and application control tools when conducting signature validation checks. In user mode, Windows Authenticode(Citation: Microsoft Authenticode) digital signatures are used to verify a file's origin and integrity, variables that may be used to establish trust in signed code (ex: a driver with a valid Microsoft signature may be handled as safe). The signature validation process is handled via the WinVerifyTrust application programming interface (API) function,(Citation: Microsoft WinVerifyTrust) which accepts an inquiry and coordinates with the appropriate trust provider, which is responsible for validating parameters of a signature.(Citation: SpectorOps Subverting Trust Sept 2017) Because of the va", "query_type": "nl"} +{"_id": "code_q_000229", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may modify the configuration settings of a domain or identity tenant to evade defenses and/or escalate privileges in centrally managed environments. Such services provide a centralized means of managing identity resources such as devices and accounts, and often include configuration settings that may apply between domains or tenants such as trust relationships, identity syncing, or identity federation. Modifications to domain or tenant settings may include altering domain Group Policy Objects (GPOs) in Microsoft Active Directory (AD) or changing trust settings for domains, including federation trust relationships between domains or tenants. With sufficient permissions, adversaries can modify domain or tenant policy settings. Since configuration settings for these services apply", "query_type": "nl"} +{"_id": "code_q_000230", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use methods of capturing user input to obtain credentials or collect information. During normal system usage, users often provide credentials to various different locations, such as login pages/portals or system dialog boxes. the component mechanisms may be transparent to the user (e.g. [Credential API Hooking]( or rely on deceiving the user into providing input into what they believe to be a genuine service (e.g. [Web Portal Capture](\n\nTactics: collection, credential-access\n\nPlatforms: Linux, macOS, Network Devices, Windows", "query_type": "nl"} +{"_id": "code_q_000231", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may masquerade malicious payloads as legitimate files through changes to the payload's formatting, including the file’s signature, extension, icon, and contents. Various file types have a typical standard format, including how they are encoded and organized. For example, a file’s signature (also known as header or magic bytes) is the beginning bytes of a file and is often used to identify the file’s type. For example, the header of a JPEG file is 0xFF 0xD8 and the file extension is either `.JPE`, `.JPEG` or `.JPG`. Adversaries may edit the header’s hex code and/or the file extension of a malicious payload in order to bypass file validation checks and/or input sanitization. This behavior is commonly used when payload files are transferred (e.g., [Ingress Tool Trans", "query_type": "nl"} +{"_id": "code_q_000232", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gain persistence and elevate privileges by executing malicious content triggered by the Event Monitor Daemon (emond). Emond is a [Launch Daemon]( that accepts events from various services, runs them through a simple rules engine, and takes action. The emond binary at /sbin/emond will load any rules from the /etc/emond.d/rules/ directory and take action once an explicitly defined event takes place. The rule files are in the plist format and define the name, event type, and action to take. Some examples of event types include system startup and user authentication. Examples of actions are to run a system command or send an email. The emond service will not launch if there is no file present in the QueueDirectories path /private/var/db/emondClie", "query_type": "nl"} +{"_id": "code_q_000234", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may transfer tools or other files from an external system into a compromised environment. Tools or files may be copied from an external adversary-controlled system to the victim network through the command and control channel or through alternate protocols such as [ftp]( Once present, adversaries may also transfer/spread tools between victim devices within a compromised environment (i.e. [Lateral Tool Transfer]( On Windows, adversaries may use various utilities to download tools, such as `copy`, `finger`, [certutil]( and [PowerShell]( commands such as IEX(New-Object Net.WebClient).downloadString() and Invoke-WebRequest. On Linux and macOS systems, a variety of utilities also exist, such as `curl`, `scp`, `sftp`, `tftp`, `rsync`, `finger`, and `wget`.(C", "query_type": "nl"} +{"_id": "code_q_000235", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence and elevate privileges by executing malicious content triggered by a Windows Management Instrumentation (WMI) event subscription. WMI can be used to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Examples of events that may be subscribed to are the wall clock time, user login, or the computer's uptime.(Citation: Mandiant M-Trends 2015) Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.(Citation: FireEye WMI SANS 2015)(Citation: FireEye WMI 2015) Adversaries may also compile WMI scripts – using `mofcomp.exe` –into Windows Management Object (MOF) files (.mof extension) that can be used to create", "query_type": "nl"} +{"_id": "code_q_000236", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse Microsoft Office add-ins to obtain persistence on a compromised system. Office add-ins can be used to add functionality to Office programs.(Citation: Microsoft Office Add-ins) There are different types of add-ins that can be used by the various Office products; including Word/Excel add-in Libraries (WLL/XLL), VBA add-ins, Office Component Object Model (COM) add-ins, automation add-ins, VBA Editor (VBE), Visual Studio Tools for Office (VSTO) add-ins, and Outlook add-ins.(Citation: MRWLabs Office Persistence Add-ins)(Citation: FireEye Mail CDS 2018) Add-ins can be used to obtain persistence because they can be set to execute code when an Office application starts.\n\nTactics: persistence\n\nPlatforms: Windows, Office Suite", "query_type": "nl"} +{"_id": "code_q_000237", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gain persistence and elevate privileges by executing malicious content triggered by PowerShell profiles. A the component (profile.ps1) is a script that runs when [PowerShell]( starts and can be used as a logon script to customize user environments. [PowerShell]( supports several profiles depending on the user or host program. For example, there can be different profiles for [PowerShell]( host programs such as the PowerShell console, PowerShell ISE or Visual Studio Code. An administrator can also configure a profile that applies to all users and host programs on the local computer.(Citation: Microsoft About Profiles) Adversaries may modify these profiles to include arbitrary commands, functions, modules, and/or [PowerShell]( drives to gain persistence. Every tim", "query_type": "nl"} +{"_id": "code_q_000238", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to get a listing of open application windows. Window listings could convey information about how the system is used.(Citation: Prevailion DarkWatchman 2021) For example, information about application windows could be used to identify potential data to collect as well as identifying security tooling ([Security Software Discovery]( to evade.(Citation: ESET Grandoreiro April 2020) Adversaries typically abuse system features for this type of enumeration. For example, they may gather information through native system features such as [Command and Scripting Interpreter]( commands and [Native API]( functions.\n\nTactics: discovery\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000239", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gather information about the victim's network domain(s) that can be used during targeting. Information about domains and their properties may include a variety of details, including what domain(s) the victim owns as well as administrative data (ex: name, registrar, etc.) and more directly actionable information such as contacts (email addresses and phone numbers), business addresses, and name servers. Adversaries may gather this information in various ways, such as direct collection actions via [Active Scanning]( or [Phishing for Information]( Information about victim domains and their properties may also be exposed to adversaries via online or other accessible data sets (ex: [WHOIS]( WHOIS)(Citation: DNS Dumpster)(Citation: Circl Passive DNS) Where third-party cloud provid", "query_type": "nl"} +{"_id": "code_q_000241", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse msiexec.exe to proxy execution of malicious payloads. Msiexec.exe is the command-line utility for the Windows Installer and is thus commonly associated with executing installation packages (.msi).(Citation: Microsoft msiexec) The Msiexec.exe binary may also be digitally signed by Microsoft. Adversaries may abuse msiexec.exe to launch local or network accessible MSI files. Msiexec.exe can also execute DLLs.(Citation: LOLBAS Msiexec)(Citation: TrendMicro Msiexec Feb 2018) Since it may be signed and native on Windows systems, msiexec.exe can be used to bypass application control solutions that do not account for its potential abuse. Msiexec.exe execution may also be elevated to SYSTEM privileges if the AlwaysInstallElevated policy is enabled.(Citation: Micro", "query_type": "nl"} +{"_id": "code_q_000243", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may insert, delete, or manipulate data at rest in order to influence external outcomes or hide activity, thus threatening the integrity of the data.(Citation: FireEye APT38 Oct 2018)(Citation: DOJ Lazarus Sony 2018) By manipulating stored data, adversaries may attempt to affect a business process, organizational understanding, and decision making. Stored data could include a variety of file formats, such as Office files, databases, stored emails, and custom file formats. The type of modification and the impact it will have depends on the type of data as well as the goals and objectives of the adversary. For complex systems, an adversary would likely need special expertise and possibly access to specialized software related to the system that would typically be gained through a ", "query_type": "nl"} +{"_id": "code_q_000244", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to make payloads difficult to discover and analyze by delivering files to victims as uncompiled code. Text-based source code files may subvert analysis and scrutiny from protections targeting executables/binaries. These payloads will need to be compiled before execution; typically via native utilities such as ilasm.exe(Citation: ATTACK IQ), csc.exe, or GCC/MinGW.(Citation: ClearSky MuddyWater Nov 2018) Source code payloads may also be encrypted, encoded, and/or embedded within other files, such as those delivered as a [Phishing]( Payloads may also be delivered in formats unrecognizable and inherently benign to the native OS (ex: EXEs on macOS/Linux) before later being (re)compiled into a proper executable binary with a bundled compiler and execution framework.(Citat", "query_type": "nl"} +{"_id": "code_q_000245", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to access credentials and other sensitive information by abusing a Windows Domain Controller's application programming interface (API)(Citation: Microsoft DRSR Dec 2017)(Citation: Microsoft GetNCCChanges)(Citation: Samba DRSUAPI)(Citation: Wine API samlib.dll) to simulate the replication process from a remote domain controller using a technique called DCSync. Members of the Administrators, Domain Admins, and Enterprise Admin groups or computer accounts on the domain controller are able to run DCSync to pull password data(Citation: ADSecurity Mimikatz DCSync) from Active Directory, which may include current and historical hashes of potentially useful accounts such as KRBTGT and Administrators. The hashes can then in turn be used to create a [Golden Ticket]( for use i", "query_type": "nl"} +{"_id": "code_q_000246", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may breach or otherwise leverage organizations who have access to intended victims. Access through trusted third party relationship abuses an existing connection that may not be protected or receives less scrutiny than standard mechanisms of gaining access to a network. Organizations often grant elevated access to second or third-party external providers in order to allow them to manage internal systems as well as cloud-based environments. Some examples of these relationships include IT services contractors, managed security providers, infrastructure contractors (e.g. HVAC, elevators, physical security). The third-party provider's access may be intended to be limited to the infrastructure being maintained, but may exist on the same network as the rest of the enterprise. As such", "query_type": "nl"} +{"_id": "code_q_000247", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may enumerate files and directories or may search in specific locations of a host or network share for certain information within a file system. Adversaries may use the information from [the component]( during automated discovery to shape follow-on behaviors, including whether or not the adversary fully infects the target and/or attempts specific actions. Many command shell utilities can be used to obtain this information. Examples include dir, tree, ls, find, and locate.(Citation: Windows Commands JPCERT) Custom tools may also be used to gather file and directory information and interact with the [Native API]( Adversaries may also leverage a [Network Device CLI]( on network devices to gather file and directory in", "query_type": "nl"} +{"_id": "code_q_000248", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may move onto systems, possibly those on disconnected or air-gapped networks, by copying malware to removable media and taking advantage of Autorun features when the media is inserted into a system and executes. In the case of Lateral Movement, this may occur through modification of executable files stored on removable media or by copying malware and renaming it to look like a legitimate file to trick users into executing it on a separate system. In the case of Initial Access, this may occur through manual manipulation of the media, modification of systems used to initially format the media, or modification to the media's firmware itself. Mobile devices may also be used to infect PCs with malware if connected via USB.(Citation: Exploiting Smartphone USB ) This infection may be ", "query_type": "nl"} +{"_id": "code_q_000249", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse Regsvr32.exe to proxy execution of malicious code. Regsvr32.exe is a command-line program used to register and unregister object linking and embedding controls, including dynamic link libraries (DLLs), on Windows systems. The Regsvr32.exe binary may also be signed by Microsoft.(Citation: Microsoft Regsvr32) Malicious usage of Regsvr32.exe may avoid triggering security tools that may not monitor execution of, and modules loaded by, the regsvr32.exe process because of allowlists or false positives from Windows using regsvr32.exe for normal operations. Regsvr32.exe can also be used to specifically bypass application control using functionality to load COM scriptlets to execute DLLs under user permissions. Since Regsvr32.exe is network and proxy aware, the scripts can be ", "query_type": "nl"} +{"_id": "code_q_000250", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse Unix shell commands and scripts for execution. Unix shells are the primary command prompt on Linux, macOS, and ESXi systems, though many variations of the Unix shell exist (e.g. sh, ash, bash, zsh, etc.) depending on the specific OS or distribution.(Citation: DieNet Bash)(Citation: Apple ZShell) Unix shells can control every aspect of a system, with certain commands requiring elevated privileges. Unix shells also support scripts that enable sequential execution of commands as well as other typical programming operations such as conditionals and loops. Common uses of shell scripts include long or repetitive tasks, or the need to run the same set of commands on multiple systems. Adversaries may abuse Unix shells to execute various commands or payloads. Interactive shell", "query_type": "nl"} +{"_id": "code_q_000251", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may steal data by exfiltrating it over an un-encrypted network protocol other than that of the existing command and control channel. The data may also be sent to an alternate network location from the main command and control server.(Citation: copy_cmd_cisco) Adversaries may opt to obfuscate this data, without the use of encryption, within network protocols that are natively unencrypted (such as HTTP, FTP, or DNS). This may include custom or publicly available encoding/compression algorithms (such as base64) as well as embedding data within protocol headers and fields.\n\nTactics: exfiltration\n\nPlatforms: ESXi, Linux, macOS, Network Devices, Windows", "query_type": "nl"} +{"_id": "code_q_000252", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse Compiled HTML files (.chm) to conceal malicious code. CHM files are commonly distributed as part of the Microsoft HTML Help system. CHM files are compressed compilations of various content such as HTML documents, images, and scripting/web related programming languages such as VBA, JScript, Java, and ActiveX.(Citation: Microsoft HTML Help May 2018) CHM content is displayed using underlying components of the Internet Explorer browser(Citation: Microsoft HTML Help ActiveX) loaded by the HTML Help executable program (hh.exe).(Citation: Microsoft HTML Help Executable Program) A custom CHM file containing embedded payloads could be delivered to a victim then triggered by [User Execution]( CHM execution may also bypass application control on older and/or unpatched systems th", "query_type": "nl"} +{"_id": "code_q_000253", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may create or modify references in user document templates to conceal malicious code or force authentication attempts. For example, Microsoft’s Office Open XML (OOXML) specification defines an XML-based format for Office documents (.docx, xlsx, .pptx) to replace older binary formats (.doc, .xls, .ppt). OOXML files are packed together ZIP archives compromised of various XML files, referred to as parts, containing properties that collectively define how a document is rendered.(Citation: Microsoft Open XML July 2017) Properties within parts may reference shared public resources accessed via online URLs. For example, template properties may reference a file, serving as a pre-formatted document blueprint, that is fetched when the document is loaded. Adversaries may abuse these templ", "query_type": "nl"} +{"_id": "code_q_000254", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use an existing, legitimate external Web service to host information that points to additional command and control (C2) infrastructure. Adversaries may post content, known as a the component, on Web services with embedded (and often obfuscated/encoded) domains or IP addresses. Once infected, victims will reach out to and be redirected by these resolvers.(Citation: the component) Popular websites and social media acting as a mechanism for C2 may give a significant amount of cover due to the likelihood that hosts within a network are already communicating with them prior to a compromise. Using common services, such as those offered by Google or Twitter, makes it easier for adversaries to hide in expected noise. Web service providers commonly use SSL/TLS encryption, giving adv", "query_type": "nl"} +{"_id": "code_q_000255", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may set files and directories to be hidden to evade detection mechanisms. To prevent normal users from accidentally changing special files on a system, most operating systems have the concept of a ‘hidden’ file. These files don’t show up when a user browses the file system with a GUI or when using normal commands on the command line. Users must explicitly ask to show the hidden files either via a series of Graphical User Interface (GUI) prompts or with command line switches (dir /a for Windows and ls –a for Linux and macOS). On Linux and Mac, users can mark specific files as hidden simply by putting a “.” as the first character in the file or folder name.(Citation: Sofacy Komplex Trojan)(Citation: Antiquated Mac Malware) Files and folders that start wi", "query_type": "nl"} +{"_id": "code_q_000256", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may downgrade or use a version of system features that may be outdated, vulnerable, and/or does not support updated security controls. Downgrade attacks typically take advantage of a system’s backward compatibility to force it into less secure modes of operation. Adversaries may downgrade and use various less-secure versions of features of a system, such as [Command and Scripting Interpreter]( or even network protocols that can be abused to enable [Adversary-in-the-Middle]( or [Network Sniffing]( Praetorian TLS the component 2014) For example, [PowerShell]( versions 5+ includes Script Block Logging (SBL), which can record executed script content. However, adversaries may attempt to execute a previous version of PowerShell that does not support SBL with the intent to impair defe", "query_type": "nl"} +{"_id": "code_q_000258", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence by executing malicious content triggered by Netsh Helper DLLs. Netsh.exe (also referred to as Netshell) is a command-line scripting utility used to interact with the network configuration of a system. It contains functionality to add helper DLLs for extending functionality of the utility.(Citation: TechNet Netsh) The paths to registered netsh.exe helper DLLs are entered into the Windows Registry at HKLM\\SOFTWARE\\Microsoft\\Netsh. Adversaries can use netsh.exe helper DLLs to trigger execution of arbitrary code in a persistent manner. This execution would take place anytime netsh.exe is executed, which could happen automatically, with another persistence technique, or if other software (ex: VPN) is present on the system that executes netsh.ex", "query_type": "nl"} +{"_id": "code_q_000259", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to the component associated with their behaviors to evade detection. Operating systems may have features to hide various artifacts, such as important system files and administrative task execution, to avoid disrupting user work environments and prevent users from changing files or features on the system. Adversaries may abuse these features to the component such as files, directories, user accounts, or other system activity to evade detection.(Citation: Sofacy Komplex Trojan)(Citation: Cybereason OSX Pirrit)(Citation: MalwareBytes ADS July 2015) Adversaries may also attempt to the component associated with malicious behavior by creating computing regions that are isolated from common security instrumentation, such as through the use of virtualization technology.(Cit", "query_type": "nl"} +{"_id": "code_q_000260", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may scan victim IP blocks to gather information that can be used during targeting. Public IP addresses may be allocated to organizations by block, or a range of sequential addresses. Adversaries may scan IP blocks in order to [Gather Victim Network Information]( such as which IP addresses are actively in use as well as more detailed information about hosts assigned these addresses. Scans may range from simple pings (ICMP requests and responses) to more nuanced scans that may reveal host software/versions via server banners or other network artifacts.(Citation: Botnet Scan) Information from these scans may reveal opportunities for other forms of reconnaissance (ex: [Search Open Websites/Domains]( or [Search Open Technical Databases]( establishing operational resources (ex: [Deve", "query_type": "nl"} +{"_id": "code_q_000261", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may search local system sources, such as file systems, configuration files, local databases, virtual machine files, or process memory, to find files of interest and sensitive data prior to Exfiltration. Adversaries may do this using a [Command and Scripting Interpreter]( such as [cmd]( as well as a [Network Device CLI]( which have functionality to interact with the file system to gather information.(Citation: show_run_config_cmd_cisco) Adversaries may also use [Automated Collection]( on the local system.\n\nTactics: collection\n\nPlatforms: ESXi, Linux, macOS, Network Devices, Windows", "query_type": "nl"} +{"_id": "code_q_000262", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to get a listing of services running on remote hosts and local network infrastructure devices, including those that may be vulnerable to remote software exploitation. Common methods to acquire this information include port, vulnerability, and/or wordlist scans using tools that are brought onto a system.(Citation: CISA AR21-126A FIVEHANDS May 2021) Within cloud environments, adversaries may attempt to discover services running on other cloud hosts. Additionally, if the cloud environment is connected to an on-premises environment, adversaries may be able to identify services running on non-cloud systems as well. Within macOS environments, adversaries may use the native Bonjour application to discover services running on other macOS hosts within a network. The Bonjour ", "query_type": "nl"} +{"_id": "code_q_000264", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may modify file or directory permissions/attributes to evade access control lists (ACLs) and access protected files.(Citation: Hybrid Analysis Icacls1 June 2018)(Citation: Hybrid Analysis Icacls2 May 2018) File and directory permissions are commonly managed by ACLs configured by the file or directory owner, or users with the appropriate permissions. File and directory ACL implementations vary by platform, but generally explicitly designate which users or groups can perform which actions (read, write, execute, etc.). Modifications may include changing specific access rights, which may require taking ownership of a file or directory and/or elevated permissions depending on the file or directory’s existing permissions. This may enable malicious activity such as modifying, replacin", "query_type": "nl"} +{"_id": "code_q_000265", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may dynamically establish connections to command and control infrastructure to evade common detections and remediations. This may be achieved by using malware that shares a common algorithm with the infrastructure the adversary uses to receive the malware's communications. These calculations can be used to dynamically adjust parameters such as the domain name, IP address, or port number the malware uses for command and control. Adversaries may use the component for the purpose of [Fallback Channels]( When contact is lost with the primary command and control server malware may employ the component as a means to reestablishing command and control.(Citation: Talos CCleanup 2017)(Citation: FireEye POSHSPY April 2017)(Citation: ESET Sednit 2017 Activity)\n\nTactics: command-and-contro", "query_type": "nl"} +{"_id": "code_q_000266", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may hijack a legitimate user’s remote desktop session to move laterally within an environment. Remote desktop is a common feature in operating systems. It allows a user to log into an interactive session with a system desktop graphical user interface on a remote system. Microsoft refers to its implementation of the Remote Desktop Protocol (RDP) as Remote Desktop Services (RDS).(Citation: TechNet Remote Desktop Services) Adversaries may perform RDP session hijacking which involves stealing a legitimate user's remote session. Typically, a user is notified when someone else is trying to steal their session. With System permissions and using Terminal Services Console, `c:\\windows\\system32\\tscon.exe [session number to be stolen]`, an adversary can hijack a session without the need f", "query_type": "nl"} +{"_id": "code_q_000267", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may exfiltrate data to a cloud storage service rather than over their primary command and control channel. Cloud storage services allow for the storage, edit, and retrieval of data from a remote cloud storage server over the Internet. Examples of cloud storage services include Dropbox and Google Docs. Exfiltration to these cloud storage services can provide a significant amount of cover to the adversary if hosts within the network are already communicating with the service.\n\nTactics: exfiltration\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000268", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use email rules to hide inbound emails in a compromised user's mailbox. Many email clients allow users to create inbox rules for various email functions, including moving emails to other folders, marking emails as read, or deleting emails. Rules may be created or modified within email clients or through external features such as the New-InboxRule or Set-InboxRule [PowerShell]( cmdlets on Windows systems.(Citation: Microsoft Inbox Rules)(Citation: MacOS Email Rules)(Citation: Microsoft New-InboxRule)(Citation: Microsoft Set-InboxRule) Adversaries may utilize email rules within a compromised user's mailbox to delete and/or move emails to less noticeable folders. Adversaries may do this to hide security alerts, C2 communication, or responses to [Inter", "query_type": "nl"} +{"_id": "code_q_000269", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may undermine security controls that will either warn users of untrusted activity or prevent execution of untrusted programs. Operating systems and security products may contain mechanisms to identify programs or websites as possessing some level of trust. Examples of such features would include a program being allowed to run because it is signed by a valid code signing certificate, a program prompting the user with a warning because it has an attribute set from being downloaded from the Internet, or getting an indication that you are about to connect to an untrusted site. Adversaries may attempt to subvert these trust mechanisms. The method adversaries use will depend on the specific mechanism they seek to subvert. Adversaries may conduct [File and Directory Permissions Modifi", "query_type": "nl"} +{"_id": "code_q_000270", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse cloud APIs to execute malicious commands. APIs available in cloud environments provide various functionalities and are a feature-rich method for programmatic access to nearly all aspects of a tenant. These APIs may be utilized through various methods such as command line interpreters (CLIs), in-browser Cloud Shells, [PowerShell]( modules like Azure for PowerShell(Citation: Microsoft - Azure PowerShell), or software developer kits (SDKs) available for languages such as [Python]( Cloud API functionality may allow for administrative access across all major services in a tenant such as compute, storage, identity and access management (IAM), networking, and security policies. With proper permissions (often via use of credentials such as [Application Access Token]( and [Web", "query_type": "nl"} +{"_id": "code_q_000271", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may execute their own malicious payloads by hijacking the search order used to load other programs. Because some programs do not call other programs using the full path, adversaries may place their own file in the directory where the calling program is located, causing the operating system to launch their malicious software at the request of the calling program. Search order hijacking occurs when an adversary abuses the order in which Windows searches for programs that are not given a path. Unlike [DLL]( search order hijacking, the search order differs depending on the method that is used to execute the program.(Citation: Microsoft CreateProcess)(Citation: Windows NT Command Shell)(Citation: Microsoft WinExec) However, it is common for Windows to search in the directory of the ", "query_type": "nl"} +{"_id": "code_q_000272", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may create or modify launch agents to repeatedly execute malicious payloads as part of persistence. When a user logs in, a per-user launchd process is started which loads the parameters for each launch-on-demand user agent from the property list (.plist) file found in /System/Library/LaunchAgents, /Library/LaunchAgents, and ~/Library/LaunchAgents.(Citation: AppleDocs the component Daemons)(Citation: OSX Keydnap malware)(Citation: Antiquated Mac Malware) Property list files use the Label, ProgramArguments , and RunAtLoad keys to identify the the component's name, executable location, and execution time.(Citation: OSX.Dok Malware) Launch Agents are often installed to perform updates to programs, launch ", "query_type": "nl"} +{"_id": "code_q_000273", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to find local system groups and permission settings. The knowledge of local system permission groups can help adversaries determine which groups exist and which users belong to a particular group. Adversaries may use this information to determine which users have elevated permissions, such as the users found within the local administrators group. Commands such as net localgroup of the [Net]( utility, dscl . -list /Groups on macOS, and groups on Linux can list the component.\n\nTactics: discovery\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000274", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may bypass process and/or signature-based defenses by proxying execution of malicious content with signed, or otherwise trusted, binaries. Binaries used in this technique are often Microsoft-signed files, indicating that they have been either downloaded from Microsoft or are already native in the operating system.(Citation: LOLBAS Project) Binaries signed with trusted digital certificates can typically execute on Windows systems protected by digital signature validation. Several Microsoft signed binaries that are default on Windows installations can be used to proxy execution of other files or commands. Similarly, on Linux systems adversaries may abuse trusted binaries such as split to proxy execution of malicious commands.(Citation: split man page)(Citation: GTFO ", "query_type": "nl"} +{"_id": "code_q_000275", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may achieve persistence by adding a Registry key to the the component of the local machine. the component is a Windows mechanism that is used to execute programs when a user logs in. The value stored in the Registry key will be executed after a user logs into the computer.(Citation: Klein the component 2010) These programs will be executed under the context of the user and will have the account's associated permissions level. Adversaries may abuse the component by creating a key under HKLM\\SOFTWARE\\Microsoft\\the component\\Installed Components\\ and setting a malicious value for StubPath. This value will serve as the program that will be executed when a user logs into the computer.(Citation: Mandiant Glyer APT 2010)(Citation: Citizenlab Packrat 2015)(Ci", "query_type": "nl"} +{"_id": "code_q_000276", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to access the component used to allow authentication to occur in the event a domain controller is unavailable.(Citation: Microsoft - Cached Creds) On Windows Vista and newer, the hash format is DCC2 (Domain Cached Credentials version 2) hash, also known as MS-Cache v2 hash.(Citation: PassLib mscache) The number of default cached credentials varies and can be altered per system. This hash does not allow pass-the-hash style attacks, and instead requires [Password Cracking]( to recover the plaintext password.(Citation: ired mscache) On Linux systems, Active Directory credentials can be accessed through caches maintained by software like System Security Services Daemon (SSSD) or Quest Authentication Services (formerly VAS). Cached credential hashes are typically located", "query_type": "nl"} +{"_id": "code_q_000278", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may delete or remove built-in data and turn off services designed to aid in the recovery of a corrupted system to prevent recovery.(Citation: Talos Olympic Destroyer 2018)(Citation: FireEye WannaCry 2017) This may deny access to available backups and recovery options. Operating systems may contain features that can help fix corrupted systems, such as a backup catalog, volume shadow copies, and automatic repair features. Adversaries may disable or delete system recovery features to augment the effects of [Data Destruction]( and [Data Encrypted for Impact]( Talos Olympic Destroyer 2018)(Citation: FireEye WannaCry 2017) Furthermore, adversaries may disable recovery notifications, then corrupt backups.(Citation: disable_notif_synology_ransom) A number of native Windows utilities ha", "query_type": "nl"} +{"_id": "code_q_000279", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may obtain and abuse credentials of existing accounts as a means of gaining Initial Access, Persistence, Privilege Escalation, or Defense Evasion. Compromised credentials may be used to bypass access controls placed on various resources on systems within the network and may even be used for persistent access to remote systems and externally available services, such as VPNs, Outlook Web Access, network devices, and remote desktop.(Citation: volexity_0day_sophos_FW) Compromised credentials may also grant an adversary increased privilege to specific systems or access to restricted areas of the network. Adversaries may choose not to use malware or tools in conjunction with the legitimate access those credentials provide to make it harder to detect their presence. In some cases, adv", "query_type": "nl"} +{"_id": "code_q_000280", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may install SSL/TLS certificates that can be used during targeting. SSL/TLS certificates are files that can be installed on servers to enable secure communications between systems. Digital certificates include information about the key, information about its owner's identity, and the digital signature of an entity that has verified the certificate's contents are correct. If the signature is valid, and the person examining the certificate trusts the signer, then they know they can use that key to communicate securely with its owner. Certificates can be uploaded to a server, then the server can be configured to use the certificate to enable encrypted communication with it.(Citation: DigiCert Install SSL Cert) Adversaries may install SSL/TLS certificates that can be used to furthe", "query_type": "nl"} +{"_id": "code_q_000282", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gain access to and use centralized software suites installed within an enterprise to execute commands and move laterally through the network. Configuration management and software deployment applications may be used in an enterprise network or cloud environment for routine administration purposes. These systems may also be integrated into CI/CD pipelines. Examples of such solutions include: SCCM, HBSS, Altiris, AWS Systems Manager, Microsoft Intune, Azure Arc, and GCP Deployment Manager. Access to network-wide or enterprise-wide endpoint management software may enable an adversary to achieve remote code execution on all connected systems. The access may be used to laterally move to other systems, gather information, or cause a specific effect, such as wiping the hard drives", "query_type": "nl"} +{"_id": "code_q_000283", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may search for common password storage locations to obtain user credentials.(Citation: F-Secure The Dukes) Passwords are stored in several places on a system, depending on the operating system or application holding the credentials. There are also specific applications and services that store passwords to make them easier for users to manage and maintain, such as password managers and cloud secrets vaults. Once credentials are obtained, they can be used to perform lateral movement and access restricted information.\n\nTactics: credential-access\n\nPlatforms: IaaS, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000284", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries who have the password hash of a target service account (e.g. SharePoint, MSSQL) may forge Kerberos ticket granting service (TGS) tickets, also known as silver tickets. Kerberos TGS tickets are also known as service tickets.(Citation: ADSecurity Silver Tickets) Silver tickets are more limited in scope than golden tickets in that they only enable adversaries to access a particular resource (e.g. MSSQL) and the system that hosts the resource; however, unlike golden tickets, adversaries with the ability to forge silver tickets are able to create TGS tickets without interacting with the Key Distribution Center (KDC), potentially making detection more difficult.(Citation: ADSecurity Detecting Forged Tickets) Password hashes for target services may be obtained using [OS Credential Dum", "query_type": "nl"} +{"_id": "code_q_000285", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse the component to establish persistent access to victim systems. the component are modular components that enhance or customize the functionality of software applications, including web browsers, Integrated Development Environments (IDEs), and other platforms.(Citation: Chrome Extension C2 Malware)(Citation: Abramovsky VSCode Security) Extensions are typically installed via official marketplaces, app stores, or manually loaded by users, and they often inherit the permissions and access levels of the host application. Malicious extensions can be introduced through various methods, including social engineering, compromised marketplaces, or direct installation by users or by adversaries who have already gained access to a system. Malicious extensions can be named similarl", "query_type": "nl"} +{"_id": "code_q_000286", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse Python commands and scripts for execution. Python is a very popular scripting/programming language, with capabilities to perform many functions. Python can be executed interactively from the command-line (via the python.exe interpreter) or via scripts (.py) that can be written and distributed to different systems. Python code can also be compiled into binary executables.(Citation: Zscaler APT31 Covid-19 October 2020) Python comes with many built-in packages to interact with the underlying system, such as file operations and device I/O. Adversaries can use these libraries to download and execute commands or other scripts as well as perform various malicious behaviors.\n\nTactics: execution\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000288", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may enumerate objects in cloud storage infrastructure. Adversaries may use this information during automated discovery to shape follow-on behaviors, including requesting all or specific objects from cloud storage. Similar to [File and Directory Discovery]( on a local host, after identifying available storage services (i.e. [Cloud Infrastructure Discovery]( adversaries may access the contents/objects stored in cloud infrastructure. Cloud service providers offer APIs allowing users to enumerate objects stored within cloud storage. Examples include ListObjectsV2 in AWS(Citation: ListObjectsV2) and List Blobs in Azure.(Citation: List Blobs)\n\nTactics: discovery\n\nPlatforms: IaaS", "query_type": "nl"} +{"_id": "code_q_000290", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse various implementations of JavaScript for execution. JavaScript (JS) is a platform-independent scripting language (compiled just-in-time at runtime) commonly associated with scripts in webpages, though JS can be executed in runtime environments outside the browser.(Citation: NodeJS) JScript is the Microsoft implementation of the same scripting standard. JScript is interpreted via the Windows Script engine and thus integrated with many components of Windows such as the [Component Object Model]( and Internet Explorer HTML Application (HTA) pages.(Citation: JScrip May 2018)(Citation: Microsoft JScript 2007)(Citation: Microsoft Windows Scripts) JavaScript for Automation (JXA) is a macOS scripting language based on JavaScript, included as part of Apple’s Open Scripting Arc", "query_type": "nl"} +{"_id": "code_q_000291", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may search for private key certificate files on compromised systems for insecurely stored credentials. Private cryptographic keys and certificates are used for authentication, encryption/decryption, and digital signatures.(Citation: Wikipedia Public Key Crypto) Common key and certificate file extensions include: .key, .pgp, .gpg, .ppk, .p12, .pem, .pfx, .cer, .p7b, .asc. Adversaries may also look in common key directories, such as ~/.ssh for SSH keys on * nix-based systems or C:\Users\(username)\.ssh\ on Windows. Adversary tools may also search compromised systems for file extensions relating to cryptographic keys and certificates.(Citation: Kaspersky Careto)(Citation: Palo Alto Prince of Persia) When a device is registered to Entra ID,", "query_type": "nl"} +{"_id": "code_q_000292", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries can hide a program's true filetype by changing the extension of a file. With certain file types (specifically this does not work with .app extensions), appending a space to the end of a filename will change how the file is processed by the operating system. For example, if there is a Mach-O executable file called evil.bin, when it is double clicked by a user, it will launch Terminal.app and execute. If this file is renamed to evil.txt, then when double clicked by a user, it will launch with the default text editing application (not executing the binary). However, if the file is renamed to evil.txt (note the space at the end), then when double clicked by a user, the true file type is determined by the OS and handled appropriately and the b", "query_type": "nl"} +{"_id": "code_q_000293", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may modify mail and mail application data to remove evidence of their activity. Email applications allow users and other programs to export and delete mailbox data via command line tools or use of APIs. Mail application data can be emails, email metadata, or logs generated by the application or operating system, such as export requests. Adversaries may manipulate emails and mailbox data to remove logs, artifacts, and metadata, such as evidence of [Phishing]( Spearphishing]( [Email Collection]( [Mail Protocols]( for command and control, or email-based exfiltration such as [Exfiltration Over Alternative Protocol]( For example, to remove evidence on Exchange servers adversaries have used the ExchangePowerShell [PowerShell]( module, including Remove-MailboxExport", "query_type": "nl"} +{"_id": "code_q_000294", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may execute their own malicious payloads by hijacking environment variables the dynamic linker uses to load shared libraries. During the execution preparation phase of a program, the dynamic linker loads specified absolute paths of shared libraries from various environment variables and files, such as LD_PRELOAD on Linux or DYLD_INSERT_LIBRARIES on macOS.(Citation: TheEvilBit DYLD_INSERT_LIBRARIES)(Citation: Timac DYLD_INSERT_LIBRARIES)(Citation: Gabilondo DYLD_INSERT_LIBRARIES Catalina Bypass) Libraries specified in environment variables are loaded first, taking precedence over system libraries with the same function name.(Citation: Man LD.SO)(Citation: TLDP Shared Libraries)(Citation: Apple Doco Archive Dynamic Libraries) Each platform's linker uses ", "query_type": "nl"} +{"_id": "code_q_000295", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may attempt to get detailed information about the operating system and hardware, including version, patches, hotfixes, service packs, and architecture. Adversaries may use this information to shape follow-on behaviors, including whether or not the adversary fully infects the target and/or attempts specific actions. This behavior is distinct from [Local Storage Discovery]( which is an adversary's discovery of local drive, disks and/or volumes. Tools such as [Systeminfo]( can be used to gather detailed system information. If running with privileged access, a breakdown of system data can be gathered through the systemsetup configuration tool on macOS. Adversaries may leverage a [Network Device CLI]( on network devices to gather detailed system information (e.g. API call to set a DLL to be loaded at startup.(Citation: AddMonitor) This DLL can be located in C:\\Windows\\System32 and will be loaded and run by the print spooler service, `spoolsv.exe`, under SYSTEM level permissions on boot.(Citation: Bloxham) Alternatively, an arbitrary DLL can be loaded if permissions allow writing a fully-qualified pathname for that DLL to the `Driver` value of an existing or new arbitrarily named subkey of HKLM\\SYSTEM\\CurrentControlSet\\Control\\Print\\Monitors. The Registry key contains entries for the following: * Local Port * Standard TCP/IP Port * USB Mo", "query_type": "nl"} +{"_id": "code_q_000301", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may send spearphishing emails with a malicious link in an attempt to gain access to victim systems. Spearphishing with a link is a specific variant of spearphishing. It is different from other forms of spearphishing in that it employs the use of links to download malware contained in email, instead of attaching malicious files to the email itself, to avoid defenses that may inspect email attachments. Spearphishing may also involve social engineering techniques, such as posing as a trusted source. All forms of spearphishing are electronically delivered social engineering targeted at a specific individual, company, or industry. In this case, the malicious emails contain links. Generally, the links will be accompanied by social engineering text and require the user to actively cli", "query_type": "nl"} +{"_id": "code_q_000302", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may manipulate application software prior to receipt by a final consumer for the purpose of data or system compromise. Supply chain compromise of software can take place in a number of ways, including manipulation of the application source code, manipulation of the update/distribution mechanism for that software, or replacing compiled releases with a modified version. Targeting may be specific to a desired victim set or may be distributed to a broad set of consumers but only move on to additional tactics on specific victims.(Citation: Avast CCleaner3 2018)(Citation: Command Five SK 2011)\n\nTactics: initial-access\n\nPlatforms: Linux, Windows, macOS", "query_type": "nl"} +{"_id": "code_q_000303", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may gain access to a system through a user visiting a website over the normal course of browsing. Multiple ways of delivering exploit code to a browser exist (i.e., [Drive-by Target]( including: * A legitimate website is compromised, allowing adversaries to inject malicious code * Script files served to a legitimate website from a publicly writeable cloud storage bucket are modified by an adversary * Malicious ads are paid for and served through legitimate ad providers (i.e., [Malvertising]( * Built-in web application interfaces that allow user-controllable content are leveraged for the insertion of malicious scripts or iFrames (e.g., cross-site scripting) Browser push notifications may also be abused by adversaries and leveraged for malicious code injection via [User Execution", "query_type": "nl"} +{"_id": "code_q_000304", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may look for folders and drives shared on remote systems as a means of identifying sources of information to gather as a precursor for Collection and to identify potential systems of interest for Lateral Movement. Networks often contain shared network drives and folders that enable users to access file directories on various systems across a network. File sharing over a Windows network occurs over the SMB protocol.(Citation: Wikipedia Shared Resource)(Citation: TechNet Shared Folder) [Net]( can be used to query a remote system for available shared drives using the net view \\\\\\\\remotesystem command. It can also be used to query shared drives on the local system using net share. For macOS, the sharing -l command lists all shared points used ", "query_type": "nl"} +{"_id": "code_q_000305", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may break out of a container or virtualized environment to gain access to the underlying host. This can allow an adversary access to other containerized or virtualized resources from the host level or to the host itself. In principle, containerized / virtualized resources should provide a clear separation of application functionality and be isolated from the host environment.(Citation: Docker Overview) There are multiple ways an adversary may escape from a container to a host environment. Examples include creating a container configured to mount the host’s filesystem using the bind parameter, which allows the adversary to drop payloads and execute control utilities such as cron on the host; utilizing a privileged container to run commands or load a malicious kernel module on th", "query_type": "nl"} +{"_id": "code_q_000306", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may disable or modify cloud logging capabilities and integrations to limit what data is collected on their activities and avoid detection. Cloud environments allow for collection and analysis of audit and application logs that provide insight into what activities a user does within the environment. If an adversary has sufficient permissions, they can disable or modify logging to avoid detection of their activities. For example, in AWS an adversary may disable CloudWatch/CloudTrail integrations prior to conducting further malicious activity. They may alternatively tamper with logging functionality, for example, by removing any associated SNS topics, disabling multi-region logging, or disabling settings that validate and/or encrypt log files.(Citation: AWS Cloud Trail)(Citation:", "query_type": "nl"} +{"_id": "code_q_000308", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may abuse configurations where an application has the setuid or setgid bits set in order to get code running in a different (and possibly more privileged) user’s context. On Linux or macOS, when the setuid or setgid bits are set for an application binary, the application will run with the privileges of the owning user or group respectively.(Citation: setuid man page) Normally an application is run in the current user’s context, regardless of which user or group owns the application. However, there are instances where programs need to be executed in an elevated context to function properly, but the user running them may not have the specific required privileges. Instead of creating an entry in the sudoers file, which must be done by root, any user can specify the setuid or setg", "query_type": "nl"} +{"_id": "code_q_000309", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may create or modify Launch Daemons to execute malicious payloads as part of persistence. Launch Daemons are plist files used to interact with Launchd, the service management framework used by macOS. Launch Daemons require elevated privileges to install, are executed for every user on a system prior to login, and run in the background without the need for user interaction. During the macOS initialization startup, the launchd process loads the parameters for launch-on-demand system-level daemons from plist files found in /System/Library/LaunchDaemons/ and /Library/LaunchDaemons/. Required Launch Daemons parameters include a Label to identify the task, Program to provide a path to the executable, and RunAtLoad to sp", "query_type": "nl"} +{"_id": "code_q_000311", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence by executing malicious content triggered by user inactivity. Screensavers are programs that execute after a configurable time of user inactivity and consist of Portable Executable (PE) files with a .scr file extension.(Citation: Wikipedia Screensaver) The Windows screensaver application scrnsave.scr is located in C:\\Windows\\System32\\, and C:\\Windows\\sysWOW64\\ on 64-bit Windows systems, along with screensavers included with base Windows installations. The following screensaver settings are stored in the Registry (HKCU\\Control Panel\\Desktop\\) and could be manipulated to achieve persistence: * SCRNSAVE.exe - set to malicious PE path * ScreenSaveActive - set to '1' to enable the screensaver *", "query_type": "nl"} +{"_id": "code_q_000312", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may the component with services that can be used during targeting. For operations incorporating social engineering, the utilization of an online persona may be important. Rather than creating and cultivating accounts (i.e. [Establish Accounts]( adversaries may compromise existing accounts. Utilizing an existing persona may engender a level of trust in a potential victim if they have a relationship, or knowledge of, the compromised persona. A variety of methods exist for compromising accounts, such as gathering credentials via [Phishing for Information]( purchasing credentials from third-party sites, brute forcing credentials (ex: password reuse from breach credential dumps), or paying employees, suppliers or business partners for access to credentials.(Citation: AnonHBGary)(Cit", "query_type": "nl"} +{"_id": "code_q_000313", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may disable or modify the Linux Audit system to hide malicious activity and avoid detection. Linux admins use the Linux Audit system to track security-relevant information on a system. The Linux Audit system operates at the kernel-level and maintains event logs on application and system activity such as process, network, file, and login events based on pre-configured rules. Often referred to as `auditd`, this is the name of the daemon used to write events to disk and is governed by the parameters set in the `audit.conf` configuration file. Two primary ways to configure the log generation rules are through the command line `auditctl` utility and the file `/etc/audit/audit.rules`, containing a sequence of `auditctl` commands loaded at boot time.(Citation: IzyKnows auditd threat d", "query_type": "nl"} +{"_id": "code_q_000314", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may collect data stored in the clipboard from users copying information within or between applications. For example, on Windows adversaries can access the component by using clip.exe or Get-Clipboard.(Citation: MSDN Clipboard)(Citation: clip_win_server)(Citation: CISA_AA21_200B) Additionally, adversaries may monitor then replace users’ clipboard with their data (e.g., [Transmitted Data Manipulation]( mining_ruby_reversinglabs) macOS and Linux also have commands, such as pbpaste, to grab clipboard contents.(Citation: Operating with EmPyre)\n\nTactics: collection\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000315", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence by executing malicious content triggered by hijacked references to Component Object Model (COM) objects. COM is a system within Windows to enable interaction between software components through the operating system.(Citation: Microsoft Component Object Model) References to various COM objects are stored in the Registry. Adversaries may use the COM system to insert malicious code that can be executed in place of legitimate software through hijacking the COM references and relationships as a means for persistence. Hijacking a COM object requires a change in the Registry to replace a reference to a legitimate system component which may cause that component to not work when executed. When that system component is executed through normal system operation th", "query_type": "nl"} +{"_id": "code_q_000316", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may impair a system's ability to hibernate, reboot, or shut down in order to extend access to infected machines. When a computer enters a dormant state, some or all software and hardware may cease to operate which can disrupt malicious activity.(Citation: Sleep, shut down, hibernate) Adversaries may abuse system utilities and configuration settings to maintain access by preventing machines from entering a state, such as standby, that can terminate malicious activity.(Citation: Microsoft: Powercfg command-line options)(Citation: systemdsleep Linux) For example, `powercfg` controls all configurable power system settings on a Windows system and can be abused to prevent an infected host from locking or shutting down.(Citation: Two New Monero Malware Attacks Target Windows and Andro", "query_type": "nl"} +{"_id": "code_q_000317", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may obtain and abuse credentials of a domain account as a means of gaining Initial Access, Persistence, Privilege Escalation, or Defense Evasion.(Citation: TechNet Credential Theft) the component are those managed by Active Directory Domain Services where access and permissions are configured across systems and services that are part of that domain. the component can cover users, administrators, and services.(Citation: Microsoft AD Accounts) Adversaries may compromise the component, some with a high level of privileges, through various means such as [OS Credential Dumping]( or password reuse, allowing access to privileged resources of the domain.\n\nTactics: stealth, persistence, privilege-escalation, initial-access\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000318", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may encrypt data on target systems or on large numbers of systems in a network to interrupt availability to system and network resources. They can attempt to render stored data inaccessible by encrypting files or data on local and remote drives and withholding access to a decryption key. This may be done in order to extract monetary compensation from a victim in exchange for decryption or a decryption key (ransomware) or to render data permanently inaccessible in cases where the key is not saved or transmitted.(Citation: US-CERT Ransomware 2016)(Citation: FireEye WannaCry 2017)(Citation: US-CERT NotPetya 2017)(Citation: US-CERT SamSam 2018) In the case of ransomware, it is typical that common user files like Office documents, PDFs, images, videos, audio, text, and source code f", "query_type": "nl"} +{"_id": "code_q_000319", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may create a the component to maintain access to victim systems. Domain accounts are those managed by Active Directory Domain Services where access and permissions are configured across systems and services that are part of that domain. Domain accounts can cover user, administrator, and service accounts. With a sufficient level of access, the net user /add /domain command can be used to create a the component.(Citation: Savill 1999) Such accounts may be used to establish secondary credentialed access that does not require persistent remote access tools to be deployed on the system.\n\nTactics: persistence\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000320", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may create or modify Windows services to repeatedly execute malicious payloads as part of persistence. When Windows boots up, it starts programs or applications called services that perform background system functions.(Citation: TechNet Services) the component configuration information, including the file path to the service's executable or recovery programs/commands, is stored in the Windows Registry. Adversaries may install a new service or modify an existing service to execute at startup in order to persist on a system. Service configurations can be set or modified using system utilities (such as sc.exe), by directly modifying the Registry, or by interacting directly with the Windows API. Adversaries may also use services to install and execute malicious drivers. For example", "query_type": "nl"} +{"_id": "code_q_000321", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may communicate using OSI application layer protocols to avoid detection/network filtering by blending in with existing traffic. Commands to the remote system, and often the results of those commands, will be embedded within the protocol traffic between the client and server. Adversaries may utilize many different protocols, including those used for web browsing, transferring files, electronic mail, DNS, or publishing/subscribing. For connections that occur internally within an enclave (such as those between a proxy or pivot node and other nodes), commonly used protocols are SMB, SSH, or RDP.(Citation: Mandiant APT29 Eye Spy Email Nov 22)\n\nTactics: command-and-control\n\nPlatforms: Linux, macOS, Windows, Network Devices, ESXi", "query_type": "nl"} +{"_id": "code_q_000322", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse the component to establish persistent access to systems. the component are code that can be saved and reused so that database users do not waste time rewriting frequently used SQL queries. Stored procedures can be invoked via SQL statements to the database using the procedure name or via defined events (e.g. when a SQL server application is started/restarted). Adversaries may craft malicious stored procedures that can provide a persistence mechanism in SQL database servers.(Citation: NetSPI Startup Stored Procedures)(Citation: Kaspersky MSSQL Aug 2019) To execute operating system commands through SQL syntax the adversary may have to enable additional functionality, such as xp_cmdshell for MSSQL Server.(Citation: NetSPI Startup Stored Procedures)(Citation: Kaspersky MS", "query_type": "nl"} +{"_id": "code_q_000323", "text": "Retrieve a detection rule that identifies this adversary behavior: Valid accounts in cloud environments may allow adversaries to perform actions to achieve Initial Access, Persistence, Privilege Escalation, or Defense Evasion. the component are those created and configured by an organization for use by users, remote support, services, or for administration of resources within a cloud service provider or SaaS application. the component can exist solely in the cloud; alternatively, they may be hybrid-joined between on-premises systems and the cloud through syncing or federation with other identity sources such as Windows Active Directory.(Citation: AWS Identity Federation)(Citation: Google Federating GC)(Citation: Microsoft Deploying AD Federation) Service or user accounts may be targeted by adversaries through [Brute Force]( [Phishing]( or various other me", "query_type": "nl"} +{"_id": "code_q_000324", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may log into accessible the component within a compromised environment using [Valid Accounts]( that are synchronized with or federated to on-premises user identities. The adversary may then perform management actions or access cloud-hosted resources as the logged-on user. Many enterprises federate centrally managed user identities to the component, allowing users to log in with their domain credentials in order to access the cloud control plane. Similarly, adversaries may connect to available the component through the web console or through the cloud command line interface (CLI) (e.g., [Cloud API]( using commands such as Connect-AZAccount for Azure PowerShell, Connect-MgGraph for Microsoft Graph PowerShell, and gcloud auth login for the Go", "query_type": "nl"} +{"_id": "code_q_000325", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may steal data by exfiltrating it over an existing command and control channel. Stolen data is encoded into the normal communications channel using the same protocol as command and control communications.(Citation: C2 FRAMEWORKS)\n\nTactics: exfiltration\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000326", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may clear system logs to hide evidence of an intrusion. macOS and Linux both keep track of system or user-initiated actions via system logs. The majority of native system logging is stored under the `/var/log/` directory. Subfolders in this directory categorize logs by their related functions, such as:(Citation: Linux Logs) * `/var/log/messages:`: General and system-related messages * `/var/log/secure or /var/log/auth.log`: Authentication logs * `/var/log/utmp or /var/log/wtmp`: Login records * `/var/log/kern.log`: Kernel logs * `/var/log/cron.log`: Crond logs * `/var/log/maillog`: Mail server logs * `/var/log/httpd/`: Web server access and error logs\n\nTactics: defense-impairment\n\nPlatforms: Linux, macOS", "query_type": "nl"} +{"_id": "code_q_000327", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may use legitimate desktop support software to establish an interactive command and control channel to target systems within networks. Desktop support software provides a graphical interface for remotely controlling another computer, transmitting the display output, keyboard input, and mouse control between devices using various protocols. Desktop support software tools, such as `VNC`, `Team Viewer`, `AnyDesk`, `ScreenConnect`, `LogMein`, `AmmyyAdmin`, and other remote monitoring and management (RMM) tools, are commonly used as legitimate technical support software and may be allowed by application control within a target environment.(Citation: Symantec Living off the Land)(Citation: CrowdStrike 2015 Global Threat Report)(Citation: CrySyS Blog TeamSpy) Remote access modules/fe", "query_type": "nl"} +{"_id": "code_q_000328", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may steal web application or service session cookies and use them to gain access to web applications or Internet services as an authenticated user without needing credentials. Web applications and services often use session cookies as an authentication token after a user has authenticated to a website. Cookies are often valid for an extended period of time, even if the web application is not actively used. Cookies can be found on disk, in the process memory of the browser, and in network traffic to remote systems. Additionally, other applications on the targets machine might store sensitive authentication cookies in memory (e.g. apps which authenticate to cloud services). Session cookies can be used to bypasses some multi-factor authentication protocols.(Citation: Pass The Coo", "query_type": "nl"} +{"_id": "code_q_000329", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may physically introduce computer accessories, networking hardware, or other computing devices into a system or network that can be used as a vector to gain access. Rather than just connecting and distributing payloads via removable storage (i.e. [Replication Through Removable Media]( more robust the component can be used to introduce new functionalities and/or features into a system that can then be abused. While public references of usage by threat actors are scarce, many red teams/penetration testers leverage the component for initial access. Commercial and open source products can be leveraged with capabilities such as passive network tapping, network traffic modification (i.e. [Adversary-in-the-Middle]( keystroke injection, kernel memory reading via DMA, addition of new wi", "query_type": "nl"} +{"_id": "code_q_000330", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may execute active reconnaissance scans to gather information that can be used during targeting. Active scans are those where the adversary probes victim infrastructure via network traffic, as opposed to other forms of reconnaissance that do not involve direct interaction. Adversaries may perform different forms of the component depending on what information they seek to gather. These scans can also be performed in various ways, including using native features of network protocols such as ICMP.(Citation: Botnet Scan)(Citation: OWASP Fingerprinting) Information from these scans may reveal opportunities for other forms of reconnaissance (ex: [Search Open Websites/Domains]( or [Search Open Technical Databases]( establishing operational resources (ex: [Develop Capabilities]( or [Ob", "query_type": "nl"} +{"_id": "code_q_000331", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse PowerShell commands and scripts for execution. PowerShell is a powerful interactive command-line interface and scripting environment included in the Windows operating system.(Citation: TechNet PowerShell) PowerShell can also be installed on Linux and macOS.(Citation: Powershell installation) Adversaries can use PowerShell to perform a number of actions, including discovery of information and execution of code. Examples include the Start-Process cmdlet which can be used to run an executable and the Invoke-Command cmdlet which runs a command locally or on a remote computer (though administrator permissions are required to use PowerShell to connect to remote systems). PowerShell may also be used to download and run executables from the Internet,", "query_type": "nl"} +{"_id": "code_q_000333", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use the component to add junk data and change the on-disk representation of malware. This can be done without affecting the functionality or behavior of a binary, but can increase the size of the binary beyond what some security tools are capable of handling due to file size limitations. the component effectively changes the checksum of the file and can also be used to avoid hash-based blocklists and static anti-virus signatures.(Citation: ESET OceanLotus) The padding used is commonly generated by a function to create junk data and then appended to the end or applied to sections of malware.(Citation: Securelist Malware Tricks April 2017) Increasing the file size may decrease the effectiveness of certain tools and detection capabilities that are not designed or configured to", "query_type": "nl"} +{"_id": "code_q_000334", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may add new domain trusts, modify the properties of existing domain trusts, or otherwise change the configuration of trust relationships between domains and tenants to evade defenses and/or elevate privileges.Trust details, such as whether or not user identities are federated, allow authentication and authorization properties to apply between domains or tenants for the purpose of accessing shared resources.(Citation: Microsoft - Azure AD Federation) These trust objects may include accounts, credentials, and other authentication material applied to servers, tokens, and domains. Manipulating these trusts may allow an adversary to escalate privileges and/or evade defenses by modifying settings to add objects which they control. For example, in Microsoft Active Directory (AD) envir", "query_type": "nl"} +{"_id": "code_q_000336", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may mimic common operating system GUI components to prompt users for credentials with a seemingly legitimate prompt. When programs are executed that need additional privileges than are present in the current user context, it is common for the operating system to prompt the user for proper credentials to authorize the elevated privileges for the task (ex: [Bypass User Account Control]( Adversaries may mimic this functionality to prompt users for credentials with a seemingly legitimate prompt for a number of reasons that mimic normal usage, such as a fake installer requiring additional access or a fake malware removal suite.(Citation: OSX Malware Exploits MacKeeper) This type of prompt can be used to collect credentials via various languages such as [AppleScript]( LogRhythm Do Yo", "query_type": "nl"} +{"_id": "code_q_000338", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may rely upon specific actions by a user in order to gain execution. Users may be subjected to social engineering to get them to execute malicious code by, for example, opening a malicious document file or link. These user actions will typically be observed as follow-on behavior from forms of [Phishing]( While [the component]( frequently occurs shortly after Initial Access it may occur at other phases of an intrusion, such as when an adversary places a file in a shared directory or on a user's desktop hoping that a user will click on it. This activity may also be seen shortly after [Internal Spearphishing]( Adversaries may also deceive users into performing actions such as: * Enabling [Remote Access Tools]( allowing direct control of the system to the adversary * Running malic", "query_type": "nl"} +{"_id": "code_q_000339", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may disable network device-based firewall mechanisms entirely or add, delete, or modify particular rules in order to bypass controls limiting network usage. Adversaries may obtain access to devices such as routers, switches, or other perimeter/network devices and change access control lists (ACLs), security zones, or policy rules to permit otherwise blocked traffic. For example, adversaries may add new network firewall rules to allow access to all internal network subnets without restrictions. Allowing access to internal network subsets may enable unrestricted inbound/outbound connectivity or open paths for command and control and lateral movement. Adversaries may obtain access to network device management interfaces via [Valid Accounts]( or by exploiting vulnerabilities. In so", "query_type": "nl"} +{"_id": "code_q_000340", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may the component to hide the activity of an intrusion. Windows Event Logs are a record of a computer's alerts and notifications. There are three system-defined sources of events: System, Application, and Security, with five event types: Error, Warning, Information, Success Audit, and Failure Audit. With administrator privileges, the event logs can be cleared with the following utility commands: * `wevtutil cl system` * `wevtutil cl application` * `wevtutil cl security` These logs may also be cleared through other mechanisms, such as the event viewer GUI or [PowerShell]( For example, adversaries may use the PowerShell command `Remove-EventLog -LogName Security` to delete the Security EventLog and after reboot, disable future logging. Note: events may still be generated and logg", "query_type": "nl"} +{"_id": "code_q_000341", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to manipulate features of their artifacts to make them appear legitimate or benign to users and/or security tools. the component occurs when the name or location of an object, legitimate or malicious, is manipulated or abused for the sake of evading defenses and observation. This may include manipulating file metadata, tricking users into misidentifying the file type, and giving legitimate task or service names. Renaming abusable system utilities to evade security monitoring is also a form of [the component]( LOLBAS Main Site)\n\nTactics: stealth\n\nPlatforms: Containers, ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000342", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse a valid Kerberos ticket-granting ticket (TGT) or sniff network traffic to obtain a ticket-granting service (TGS) ticket that may be vulnerable to [Brute Force]( Empire InvokeKerberoast Oct 2016)(Citation: AdSecurity Cracking Kerberos Dec 2015) Service principal names (SPNs) are used to uniquely identify each instance of a Windows service. To enable authentication, Kerberos requires that SPNs be associated with at least one service logon account (an account specifically tasked with running a service).(Citation: Microsoft Detecting the component Feb 2018)(Citation: Microsoft SPN)(Citation: Microsoft SetSPN)(Citation: SANS Attacking Kerberos Nov 2014)(Citation: Harmj0y Kerberoast Nov 2016) Adversaries possessing a valid Kerberos ticket-granting ticket (TGT) may request o", "query_type": "nl"} +{"_id": "code_q_000344", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence and/or elevate privileges by executing malicious content triggered by application shims. The Microsoft Windows Application Compatibility Infrastructure/Framework (Application Shim) was created to allow for backward compatibility of software as the operating system codebase changes over time. For example, the the component feature allows developers to apply fixes to applications (without rewriting code) that were created for Windows XP so that they will work with Windows 10.(Citation: Elastic Process Injection July 2017) Within the framework, shims are created to act as a buffer between the program (or more specifically, the Import Address Table) and the Windows OS. When a program is executed, the shim cache is referenced to determine if the program req", "query_type": "nl"} +{"_id": "code_q_000345", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may register a the component to enable manipulation of Active Directory data. DCShadow may be used to create a the component (DC). DCShadow is a method of manipulating Active Directory (AD) data, including objects and schemas, by registering (or reusing an inactive registration) and simulating the behavior of a DC.(Citation: DCShadow Blog) Once registered, a rogue DC may be able to inject and replicate changes into AD infrastructure for any domain object, including credentials and keys. Registering a rogue DC involves creating a new server and nTDSDSA objects in the Configuration partition of the AD schema, which requires Administrator privileges (either Domain or local to the DC) or the KRBTGT hash.(Citation: Adsecurity Mimikatz Guide) This technique may bypass system logging ", "query_type": "nl"} +{"_id": "code_q_000347", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may attempt to discover infrastructure and resources that are available within an infrastructure-as-a-service (IaaS) environment. This includes compute service resources such as instances, virtual machines, and snapshots as well as resources of other services including the storage and database services. Cloud providers offer methods such as APIs and commands issued through CLIs to serve information about infrastructure. For example, AWS provides a DescribeInstances API within the Amazon EC2 API that can return information about one or more instances within an account, the ListBuckets API that returns a list of all buckets owned by the authenticated sender of the request, the HeadBucket API to determine a bucket’s existence along with acce", "query_type": "nl"} +{"_id": "code_q_000348", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may register malicious password filter dynamic link libraries (DLLs) into the authentication process to acquire user credentials as they are validated. Windows password filters are password policy enforcement mechanisms for both domain and local accounts. Filters are implemented as DLLs containing a method to validate potential passwords against password policies. Filter DLLs can be positioned on local computers for local accounts and/or domain controllers for domain accounts. Before registering new passwords in the Security Accounts Manager (SAM), the Local Security Authority (LSA) requests validation from each registered filter. Any potential changes cannot take effect until every registered filter acknowledges validation. Adversaries can register malicious password filters t", "query_type": "nl"} +{"_id": "code_q_000349", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may exploit software vulnerabilities in an attempt to elevate privileges. Exploitation of a software vulnerability occurs when an adversary takes advantage of a programming error in a program, service, or within the operating system software or kernel itself to execute adversary-controlled code. Security constructs such as permission levels will often hinder access to information and use of certain techniques, so adversaries will likely need to perform privilege escalation to include use of software exploitation to circumvent those restrictions. When initially gaining access to a system, an adversary may be operating within a lower privileged process which will prevent them from accessing certain resources on the system. Vulnerabilities may exist, usually in operating system co", "query_type": "nl"} +{"_id": "code_q_000350", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may disable or modify host-based or network firewalls to impair defensive mechanisms and enable further action. Once an adversary has gathered sufficient privileges, they can tamper with firewall services, policies, or rule sets to remove restrictions on inbound or outbound traffic. For example, this may include turning off firewall profiles, altering existing rules to permit previously blocked ports or protocols, or adding new rules that create covert communication paths (e.g., adding a new firewall rule for a well-known protocol (such as RDP) using a non-traditional and potentially less secure port).(Citation: change_rdp_port_conti) Adversaries may disable or modify firewalls using different behaviors, depending on the platform. For example, in ESXi, firewall rules may be mod", "query_type": "nl"} +{"_id": "code_q_000351", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use an existing, legitimate external Web service as a means for relaying data to/from a compromised system. Popular websites, cloud services, and social media acting as a mechanism for C2 may give a significant amount of cover due to the likelihood that hosts within a network are already communicating with them prior to a compromise. Using common services, such as those offered by Google, Microsoft, or Twitter, makes it easier for adversaries to hide in expected noise.(Citation: Broadcom BirdyClient Microsoft Graph API 2024) Web service providers commonly use SSL/TLS encryption, giving adversaries an added level of protection. Use of Web services may also protect back-end C2 infrastructure from discovery through malware binary analysis while also enabling operational resili", "query_type": "nl"} +{"_id": "code_q_000354", "text": "Retrieve a detection rule that identifies this adversary behavior: In addition to clearing system logs, an adversary may clear the command history of a compromised account to conceal the actions undertaken during an intrusion. Various command interpreters keep track of the commands users type in their terminal so that users can retrace what they've done. On Linux and macOS, these command histories can be accessed in a few different ways. While logged in, this command history is tracked in a file pointed to by the environment variable HISTFILE. When a user logs off a system, this information is flushed to a file in the user's home directory called ~/.bash_history. The benefit of this is that it allows users to go back to commands they've used before in different sessions. Adversaries may delete their commands from these logs by ma", "query_type": "nl"} +{"_id": "code_q_000356", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may deface systems internal to an organization in an attempt to intimidate or mislead users, thus discrediting the integrity of the systems. This may take the form of modifications to internal websites or server login messages, or directly to user systems with the replacement of the desktop wallpaper.(Citation: Novetta Blockbuster)(Citation: Varonis) Disturbing or offensive images may be used as a part of [the component]( in order to cause user discomfort, or to pressure compliance with accompanying messages. Since internally defacing systems exposes an adversary's presence, it often takes place after other intrusion goals have been accomplished.(Citation: Novetta Blockbuster Destructive Malware)\n\nTactics: impact\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000357", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use brute force techniques to gain access to accounts when passwords are unknown or when password hashes are obtained.(Citation: TrendMicro Pawn Storm Dec 2020) Without knowledge of the password for an account or set of accounts, an adversary may systematically guess the password using a repetitive or iterative mechanism.(Citation: Dragos Crashoverride 2018) Brute forcing passwords can take place via interaction with a service that will check the validity of those credentials or offline against previously acquired credential data, such as password hashes. Brute forcing credentials may take place at various points during a breach. For example, adversaries may attempt to brute force access to [Valid Accounts]( within a victim environment leveraging knowledge gathered from oth", "query_type": "nl"} +{"_id": "code_q_000358", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to find unsecured credentials in the component (GPP). GPP are tools that allow administrators to create domain policies with embedded credentials. These policies allow administrators to set local accounts.(Citation: Microsoft GPP 2016) These group policies are stored in SYSVOL on a domain controller. This means that any domain user can view the SYSVOL share and decrypt the password (using the AES key that has been made public).(Citation: Microsoft GPP Key) The following tools and scripts can be used to gather and decrypt the password file from Group Policy Preference XML files: * Metasploit’s post exploitation module: post/windows/gather/credentials/gpp * Get-GPPPassword(Citation: Obscuresecurity Get-GPPPassword) * gpprefdecrypt.py On the SYSVOL share, ", "query_type": "nl"} +{"_id": "code_q_000359", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse the Windows service control manager to execute malicious commands or payloads. The Windows service control manager (services.exe) is an interface to manage and manipulate services.(Citation: Microsoft Service Control Manager) The service control manager is accessible to users via GUI components as well as system utilities such as sc.exe and [Net]( [PsExec]( can also be used to execute commands or payloads via a temporary Windows service created through the service control manager API.(Citation: Russinovich Sysinternals) Tools such as [PsExec]( and sc.exe can accept remote servers as arguments and may be used to conduct remote execution. Adversaries may leverage these mechanisms to execute malicious content. This can be done by ei", "query_type": "nl"} +{"_id": "code_q_000361", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to get a listing of software and software versions that are installed on a system or in a cloud environment. Adversaries may use the information from [the component]( during automated discovery to shape follow-on behaviors, including whether or not the adversary fully infects the target and/or attempts specific actions. Such software may be deployed widely across the environment for configuration management or security reasons, such as [Software Deployment Tools]( and may allow adversaries broad access to infect devices or move laterally. Adversaries may attempt to enumerate software for a variety of reasons, such as figuring out what security measures are present or if the compromised system has a version of software that is vulnerable to [Exploitation for Privileg", "query_type": "nl"} +{"_id": "code_q_000362", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may compromise third-party infrastructure that can be used during targeting. Infrastructure solutions include physical or cloud servers, domains, network devices, and third-party web and DNS services. Instead of buying, leasing, or renting infrastructure an adversary may the component and use it during other phases of the adversary lifecycle.(Citation: Mandiant APT1)(Citation: ICANNDomainNameHijacking)(Citation: Talos DNSpionage Nov 2018)(Citation: FireEye EPS Awakens Part 2) Additionally, adversaries may compromise numerous machines to form a botnet they can leverage. Use of compromised infrastructure allows adversaries to stage, launch, and execute operations. Compromised infrastructure can help adversary operations blend in with traffic that is seen as normal, such as contac", "query_type": "nl"} +{"_id": "code_q_000363", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use MSBuild to proxy execution of code through a trusted Windows utility. MSBuild.exe (Microsoft Build Engine) is a software build platform used by Visual Studio. It handles XML formatted project files that define requirements for loading and building various platforms and configurations.(Citation: MSDN MSBuild) Adversaries can abuse MSBuild to proxy execution of malicious code. The inline task capability of MSBuild that was introduced in .NET version 4 allows for C# or Visual Basic code to be inserted into an XML project file.(Citation: MSDN MSBuild)(Citation: Microsoft MSBuild Inline Tasks 2017) MSBuild will compile and execute the inline task. MSBuild.exe is a signed Microsoft binary, so when it is used this way it can execute arbitrary code and bypass application contro", "query_type": "nl"} +{"_id": "code_q_000364", "text": "Retrieve a detection rule that identifies this adversary behavior: By responding to LLMNR/NBT-NS/mDNS network traffic, adversaries may spoof an authoritative source for name resolution to force communication with an adversary controlled system.(Citation: BlackCat ransomware) This activity may be used to collect or relay authentication materials. Link-Local Multicast Name Resolution (LLMNR) and NetBIOS Name Service (NBT-NS) are Microsoft Windows components that serve as alternate methods of host identification. LLMNR is based upon the Domain Name System (DNS) format and allows hosts on the same local link to perform name resolution for other hosts. NBT-NS identifies systems on a local network by their NetBIOS name.(Citation: Wikipedia LLMNR)(Citation: TechNet NetBIOS) Multicast Domain Name System(mDNS) is a zero-configuration service used to resolve hostna", "query_type": "nl"} +{"_id": "code_q_000366", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to access or create a copy of the Active Directory domain database in order to steal credential information, as well as obtain other information about domain members such as devices, users, and access rights. By default, the NTDS file (NTDS.dit) is located in %SystemRoot%\\NTDS\\Ntds.dit of a domain controller.(Citation: Wikipedia Active Directory) In addition to looking for NTDS files on active Domain Controllers, adversaries may search for backups that contain the same or similar information.(Citation: Metcalf 2015) The following tools and techniques can be used to enumerate the NTDS file and the contents of the entire Active Directory hashes. * Volume Shadow Copy * secretsdump.py * Using the in-built Windows tool, ntdsutil.exe * Invoke-NinjaCopy\n\nTacti", "query_type": "nl"} +{"_id": "code_q_000369", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may alter data en route to storage or other systems in order to manipulate external outcomes or hide activity, thus threatening the integrity of the data.(Citation: FireEye APT38 Oct 2018)(Citation: DOJ Lazarus Sony 2018) By manipulating transmitted data, adversaries may attempt to affect a business process, organizational understanding, and decision making. Manipulation may be possible over a network connection or between system processes where there is an opportunity deploy a tool that will intercept and change information. The type of modification and the impact it will have depends on the target transmission mechanism as well as the goals and objectives of the adversary. For complex systems, an adversary would likely need special expertise and possibly access to specialized", "query_type": "nl"} +{"_id": "code_q_000370", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to position themselves between two or more networked devices using an the component (AiTM) technique to support follow-on behaviors such as [Network Sniffing]( [Transmitted Data Manipulation]( or replay attacks ([Exploitation for Credential Access]( By abusing features of common networking protocols that can determine the flow of network traffic (e.g. ARP, DNS, LLMNR, etc.), adversaries may force a device to communicate through an adversary controlled system so they can collect information or perform additional actions.(Citation: Rapid7 MiTM Basics) For example, adversaries may manipulate victim DNS settings to enable other malicious activities such as preventing/redirecting users from accessing legitimate sites and/or pushing additional malware.(Citation: ttint_rat", "query_type": "nl"} +{"_id": "code_q_000371", "text": "Retrieve a detection rule that identifies this adversary behavior: An adversary may gather the system time and/or time zone settings from a local or remote system. The system time is set and stored by services, such as the Windows Time Service on Windows or systemsetup on macOS.(Citation: MSDN System Time)(Citation: Technet Windows Time Service)(Citation: systemsetup mac time) These time settings may also be synchronized between systems and services in an enterprise network, typically accomplished with a network time server within a domain.(Citation: Mac Time Sync)(Citation: linux system time) System time information may be gathered in a number of ways, such as with [Net]( on Windows by performing net time \\\\hostname to gather the system time on a remote system. The victim's time zone may also be inferred from the current system ", "query_type": "nl"} +{"_id": "code_q_000372", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse control.exe to proxy execution of malicious payloads. The Windows the component process binary (control.exe) handles execution of the component items, which are utilities that allow users to view and adjust computer settings. the component items are registered executable (.exe) or the component (.cpl) files; the latter are actually renamed dynamic-link library (.dll) files that export a CPlApplet function.(Citation: Microsoft Implementing CPL)(Citation: TrendMicro CPL Malware Jan 2014) For ease of use, the component items typically include graphical menus available to users after being registered and loaded into the the component.(Citation: Microsoft Implementing CPL) the component items can be executed directly from the command line, programmatically via", "query_type": "nl"} +{"_id": "code_q_000374", "text": "Retrieve a detection rule that identifies this adversary behavior: Once established within a system or network, an adversary may use automated techniques for collecting internal data. Methods for performing this technique could include use of a [Command and Scripting Interpreter]( to search for and copy information fitting set criteria such as file type, location, or name at specific time intervals. In cloud-based environments, adversaries may also use cloud APIs, data pipelines, command line interfaces, or extract, transform, and load (ETL) services to automatically collect data.(Citation: Mandiant UNC3944 SMS Phishing 2023) This functionality could also be built into remote access tools. This technique may incorporate use of other techniques such as [File and Directory Discovery]( and [Lateral Tool Transfer]( to identify and move files, as well as [Clou", "query_type": "nl"} +{"_id": "code_q_000376", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may impair command history logging to hide commands they run on a compromised system. Various command interpreters keep track of the commands users type in their terminal so that users can retrace what they have done. On Linux and macOS, command history is tracked in a file pointed to by the environment variable `HISTFILE`. When a user logs off a system, this information is flushed to a file in the user's home directory called `~/.bash_history`. The `HISTCONTROL` environment variable keeps track of what should be saved by the history command and eventually into the `~/.bash_history` file when a user logs out. `HISTCONTROL` does not exist by default on macOS, but can be set by the user and will be respected. The `HISTFILE` environment variable is also used in some ESXi systems.(", "query_type": "nl"} +{"_id": "code_q_000377", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may reflectively load code into a process in order to conceal the execution of malicious payloads. Reflective loading involves allocating then executing payloads directly within the memory of the process, vice creating a thread or process backed by a file path on disk (e.g., [Shared Modules]( Reflectively loaded payloads may be compiled binaries, anonymous files (only present in RAM), or just snubs of fileless executable code (ex: position-independent shellcode).(Citation: Introducing Donut)(Citation: S1 Custom Shellcode Tool)(Citation: Stuart ELF Memory)(Citation: 00sec Droppers)(Citation: Mandiant BYOL) For example, the `Assembly.Load()` method executed by [PowerShell]( may be abused to load raw code into the running process.(Citation: Microsoft AssemblyLoad) Reflective code ", "query_type": "nl"} +{"_id": "code_q_000378", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may exfiltrate data to a code repository rather than over their primary command and control channel. Code repositories are often accessible via an API (ex: Access to these APIs is often over HTTPS, which gives the adversary an additional level of protection. Exfiltration to a code repository can also provide a significant amount of cover to the adversary if it is a popular service already used by hosts within the network.\n\nTactics: exfiltration\n\nPlatforms: ESXi, Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000380", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may shut down/reboot systems to interrupt access to, or aid in the destruction of, those systems. Operating systems may contain commands to initiate a shutdown/reboot of a machine or network device. In some cases, these commands may also be used to initiate a shutdown/reboot of a remote computer or network device via [Network Device CLI]( (e.g. reload).(Citation: Microsoft Shutdown Oct 2017)(Citation: alert_TA18_106A) They may also include shutdown/reboot of a virtual machine via hypervisor / cloud consoles or command line tools. Shutting down or rebooting systems may disrupt access to computer resources for legitimate users while also impeding incident response/recovery. Adversaries may also use Windows API functions, such as `InitializeSystemShutdownExW` or `Exit", "query_type": "nl"} +{"_id": "code_q_000381", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may abuse BITS jobs to persistently execute code and perform various background tasks. Windows Background Intelligent Transfer Service (BITS) is a low-bandwidth, asynchronous file transfer mechanism exposed through [Component Object Model]( (COM).(Citation: Microsoft COM)(Citation: Microsoft BITS) BITS is commonly used by updaters, messengers, and other applications preferred to operate in the background (using available idle bandwidth) without interrupting other networked applications. File transfer tasks are implemented as BITS jobs, which contain a queue of one or more file operations. The interface to create and manage BITS jobs is accessible through [PowerShell]( and the [BITSAdmin]( tool.(Citation: Microsoft BITS)(Citation: Microsoft BITSAdmin) Adversaries may abuse BITS ", "query_type": "nl"} +{"_id": "code_q_000383", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence and/or elevate privileges by executing malicious content triggered by the component. Windows contains the component that may be launched with a key combination before a user has logged in (ex: when the user is on the Windows logon screen). An adversary can modify the way these programs are launched to get a command prompt or backdoor without logging in to the system. Two common accessibility programs are C:\\Windows\\System32\\sethc.exe, launched when the shift key is pressed five times and C:\\Windows\\System32\\utilman.exe, launched when the Windows + U key combination is pressed. The sethc.exe program is often referred to as \"sticky keys\", and has been used by adversaries for unauthenticated access through a remote desktop login ", "query_type": "nl"} +{"_id": "code_q_000384", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may interrupt availability of system and network resources by inhibiting access to accounts utilized by legitimate users. Accounts may be deleted, locked, or manipulated (ex: changed credentials, revoked permissions for SaaS platforms such as Sharepoint) to remove access to accounts.(Citation: Obsidian Security SaaS Ransomware June 2023) Adversaries may also subsequently log off and/or perform a [System Shutdown/Reboot]( to set malicious changes into place.(Citation: CarbonBlack LockerGoga 2019)(Citation: Unit42 LockerGoga 2019) In Windows, [Net]( utility, Set-LocalUser and Set-ADAccountPassword [PowerShell]( cmdlets may be used by adversaries to modify user accounts. Accounts could also be disabled by Group Policy. In Linux, the passwd ut", "query_type": "nl"} +{"_id": "code_q_000385", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may modify host software binaries to establish persistent access to systems. Software binaries/executables provide a wide range of system commands or services, programs, and libraries. Common software binaries are SSH clients, FTP clients, email clients, web browsers, and many other user or server applications. Adversaries may establish persistence through modifications to host software binaries. For example, an adversary may replace or otherwise infect a legitimate application binary (or support files) with a backdoor. Since these binaries may be routinely executed by applications or the user, the adversary can leverage this for persistent access to the host. An adversary may also modify a software binary such as an SSH client in order to persistently collect credentials durin", "query_type": "nl"} +{"_id": "code_q_000388", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use [Valid Accounts]( to log into a service that accepts remote connections, such as telnet, SSH, and VNC. The adversary may then perform actions as the logged-on user. In an enterprise environment, servers and workstations can be organized into domains. Domains provide centralized identity management, allowing users to log in using one set of credentials across the entire network. If an adversary is able to obtain a set of valid domain credentials, they could log in to many different machines using remote access protocols such as secure shell (SSH) or remote desktop protocol (RDP).(Citation: SSH Secure Shell)(Citation: TechNet Remote Desktop Services) They could also log in to accessible SaaS or IaaS services, such as those that federate their identities to the domain, or ", "query_type": "nl"} +{"_id": "code_q_000389", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may build capabilities that can be used during targeting. Rather than purchasing, freely downloading, or stealing capabilities, adversaries may develop their own capabilities in-house. This is the process of identifying development requirements and building solutions such as malware, exploits, and self-signed certificates. Adversaries may the component to support their operations throughout numerous phases of the adversary lifecycle.(Citation: Mandiant APT1)(Citation: Kaspersky Sofacy)(Citation: Bitdefender StrongPity June 2020)(Citation: Talos Promethium June 2020) As with legitimate development efforts, different skill sets may be required for developing capabilities. The skills needed may be located in-house, or may need to be contracted out. Use of a contractor may be consi", "query_type": "nl"} +{"_id": "code_q_000390", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may execute their own malicious payloads by hijacking the Registry entries used by services. Flaws in the permissions for Registry keys related to services can allow adversaries to redirect the originally specified executable to one they control, launching their own code when a service starts. Windows stores local service configuration information in the Registry under HKLM\\SYSTEM\\CurrentControlSet\\Services. The information stored under a service's Registry keys can be manipulated to modify a service's execution parameters through tools such as the service controller, sc.exe, [PowerShell]( or [Reg]( Access to Registry keys is controlled through access control lists and user permissions.(Citation: Registry Key Security)(Citation: malware_hides_service) If the permis", "query_type": "nl"} +{"_id": "code_q_000391", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may insert, delete, or manipulate data in order to influence external outcomes or hide activity, thus threatening the integrity of the data.(Citation: Sygnia Elephant Beetle Jan 2022) By manipulating data, adversaries may attempt to affect a business process, organizational understanding, or decision making. The type of modification and the impact it will have depends on the target application and process as well as the goals and objectives of the adversary. For complex systems, an adversary would likely need special expertise and possibly access to specialized software related to the system that would typically be gained through a prolonged information gathering campaign in order to have the desired impact.\n\nTactics: impact\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000393", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may forge credential materials that can be used to gain access to web applications or Internet services. Web applications and services (hosted in cloud SaaS environments or on-premise servers) often use session cookies, tokens, or other materials to authenticate and authorize user access. Adversaries may generate these credential materials in order to gain access to web resources. This differs from [Steal Web Session Cookie]( [Steal Application Access Token]( and other similar behaviors in that the credentials are new and forged by the adversary, rather than stolen or intercepted from legitimate users. The generation of web credentials often requires secret values, such as passwords, [Private Keys]( or other cryptographic seed values.(Citation: GitHub AWS-ADFS-Credential-Genera", "query_type": "nl"} +{"_id": "code_q_000395", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may attempt to dump credentials to obtain account login and credential material, normally in the form of a hash or a clear text password. Credentials can be obtained from OS caches, memory, or structures.(Citation: Brining MimiKatz to Unix) Credentials can then be used to perform [Lateral Movement]( and access restricted information. Several of the tools mentioned in associated sub-techniques may be used by both adversaries and professional security testers. Additional custom tools likely exist as well.\n\nTactics: credential-access\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000396", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may steal or forge certificates used for authentication to access remote systems or resources. Digital certificates are often used to sign and encrypt messages and/or files. Certificates are also used as authentication material. For example, Entra ID device certificates and Active Directory Certificate Services (AD CS) certificates bind to an identity and can be used as credentials for domain accounts.(Citation: O365 Blog Azure AD Device IDs)(Citation: Microsoft AD CS Overview) Authentication certificates can be both stolen and forged. For example, AD CS certificates can be stolen from encrypted storage (in the Registry or files)(Citation: APT29 Deep Look at Credential Roaming), misplaced certificate files (i.e. [Unsecured Credentials]( or directly from the Windows certificate ", "query_type": "nl"} +{"_id": "code_q_000397", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may establish persistence and/or elevate privileges using system mechanisms that trigger execution based on specific events. Various operating systems have means to monitor and subscribe to events such as logons or other user activity such as running specific applications/binaries. Cloud environments may also support various functions and services that monitor and can be invoked in response to specific cloud events.(Citation: Backdooring an AWS account)(Citation: Varonis Power Automate Data Exfiltration)(Citation: Microsoft DART Case Report 001) Adversaries may abuse these mechanisms as a means of maintaining persistent access to a victim via repeatedly executing malicious code. After gaining access to a victim system, adversaries may create/modify event triggers to point to ma", "query_type": "nl"} +{"_id": "code_q_000398", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may remove indicators from tools if they believe their malicious tool was detected, quarantined, or otherwise curtailed. They can modify the tool by removing the indicator and using the updated version that is no longer detected by the target's defensive systems or subsequent targets that may use similar systems. A good example of this is when malware is detected with a file signature and quarantined by anti-virus software. An adversary who can determine that the malware was quarantined because of its file signature may modify the file to explicitly avoid that signature, and then re-use the malware.(Citation: Files and Antivirus Detection)\n\nTactics: stealth\n\nPlatforms: Linux, macOS, Windows", "query_type": "nl"} +{"_id": "code_q_000399", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may modify access tokens to operate under a different user or system security context to perform actions and bypass access controls. Windows uses access tokens to determine the ownership of a running process. A user can manipulate access tokens to make a running process appear as though it is the child of a different process or belongs to someone other than the user that started the process. When this occurs, the process also takes on the security context associated with the new token. An adversary can use built-in Windows API functions to copy access tokens from existing processes; this is known as token stealing. These tokens can then be applied to an existing process (i.e. [Token Impersonation/Theft]( or used to spawn a new process (i.e. [Create Process with Token]( An adver", "query_type": "nl"} +{"_id": "code_q_000400", "text": "Retrieve a detection rule that identifies this adversary behavior: Adversaries may use the component to attempt to recover usable credentials, such as plaintext passwords, when credential material such as password hashes are obtained. [OS Credential Dumping]( can be used to obtain password hashes, this may only get an adversary so far when [Pass the Hash]( is not an option. Further, adversaries may leverage [Data from Configuration Repository]( in order to obtain hashed credentials for network devices.(Citation: US-CERT-TA18-106A) Techniques to systematically guess the passwords used to compute hashes are available, or the adversary may use a pre-computed rainbow table to crack hashes. Cracking hashes is usually done on adversary-controlled systems outside of the target network.(Citation: Wikipedia the component) The resulting plaintext password resulting", "query_type": "nl"} +{"_id": "code_q_000402", "text": "Find a secure code implementation example satisfying this security guidance: - [OWASP WSTG: Testing for Insecure Direct Object References]( - [OWASP SAMM: Security Testing]( - [OpenAPI 3.1.0: Security Scheme Object](", "query_type": "nl"} +{"_id": "code_q_000403", "text": "Find a secure code implementation example satisfying this security guidance: Validate both **syntax** (the expected type and format) and **semantics** (whether the value makes sense for the operation). For example, a booking needs valid dates and an end date after its start date. [this weakness]( describes these checks, including consistency between related fields. Define rules for each field: | Input | Rules to enforce | | --- | --- | | Fixed choices | Exact membership in the allowed set, including values submitted from drop-down menus | | Numbers and dates | Expected type, accepted format, and minimum and maximum values | | Strings | Length limits and the characters or structure required by the field | | Objects | Allowed fields, required fields, and rules for miss", "query_type": "nl"} +{"_id": "code_q_000404", "text": "Find a secure code implementation example satisfying this security guidance: RESTful web services should be careful to prevent leaking credentials. Passwords, security tokens, and API keys should not appear in the URL, as this can be captured in web server logs, which makes them intrinsically valuable. - In `POST`/`PUT` requests sensitive data should be transferred in the request body or request headers. - In `GET` requests sensitive data should be transferred in an HTTP Header. **OK:** ` ` **NOT OK:** ` because the apiKey is in the URL.", "query_type": "nl"} +{"_id": "code_q_000405", "text": "Find a secure code implementation example satisfying this security guidance: Passing user input to `include`, `require`, template loaders or similar functions lets an attacker load an unintended file and, depending on the language, run it as code. Map the input to a fixed allowlist of templates or modules instead of using it as a path. In PHP, [`open_basedir`]( limits which directory trees `include` and `fopen()` can access, which is a useful extra layer but not a replacement for not using the input as a path.", "query_type": "nl"} +{"_id": "code_q_000406", "text": "Find a secure code implementation example satisfying this security guidance: - Web Workers are allowed to use `XMLHttpRequest` object to perform in-domain and Cross Origin Resource Sharing requests. See relevant section of this Cheat Sheet to ensure CORS security. - While Web Workers don't have access to DOM of the calling page, malicious Web Workers can use excessive CPU for computation, leading to Denial of Service condition or abuse Cross Origin Resource Sharing for further exploitation. Ensure code in all Web Workers scripts is not malevolent. Don't allow creating Web Worker scripts from user supplied input. - Validate messages exchanged with a Web Worker. Do not try to exchange snippets of JavaScript for evaluation e.g. via `eval()` as that could introduce a [DO", "query_type": "nl"} +{"_id": "code_q_000407", "text": "Find a secure code implementation example satisfying this security guidance: This article is a guide to Cross Site Scripting (XSS) testing for application security professionals. This cheat sheet was originally based on RSnake's seminal XSS Cheat Sheet previously at: ` Now, the OWASP Cheat Sheet Series provides users with an updated and maintained version of the document. The very first OWASP Cheat Sheet, [Cross Site Scripting Prevention]( was inspired by RSnake's work and we thank RSnake for the inspiration!", "query_type": "nl"} +{"_id": "code_q_000410", "text": "Find a secure code implementation example satisfying this security guidance: ##endif // The only time we switch to debug is when asked. // NDEBUG or {nothing} results // in release build (fewer surprises at runtime). ##if defined(DEBUG) || defined(_DEBUG)", "query_type": "nl"} +{"_id": "code_q_000411", "text": "Find a secure code implementation example satisfying this security guidance: When security vulnerabilities are found, they pose a potentially serious threat if they are publicised without prior warning or appropriate remedial action for users who cannot protect themselves. It is recommended that security researchers follow a responsible disclosure program, which is a set of processes and guidelines that aims to connect the researchers with the vendor or maintainer of the vulnerable asset, in order to convey the vulnerability, its impact and applicability. Once the vulnerability is correctly triaged, the vendor and researcher coordinate a fix and a publication date for the vulnerability in an effort to provide an upgrade-path or remediation for affected users before t", "query_type": "nl"} +{"_id": "code_q_000412", "text": "Find a secure code implementation example satisfying this security guidance: The `SECRET_KEY` parameter in settings.py is used for cryptographic signing and should be kept confidential. Consider the following recommendations: - Generate a key at least 50 characters or more, containing a mix of letters, digits, and symbols. - Ensure that the `SECRET_KEY` is generated using a strong random generator, such as `get_random_secret_key()` function in Django. - Avoid hard coding the `SECRET_KEY` value in settings.py or any other location. Consider storing the key-value in environment variables or secrets managers. - Regularly rotate the key, keeping in mind that this action can invalidate sessions, password reset tokens, etc. Rotate the key immediately it if it ever gets exp", "query_type": "nl"} +{"_id": "code_q_000413", "text": "Find a secure code implementation example satisfying this security guidance: The following language-specific guidance attempts to enumerate safe methodologies for deserializing data that can't be trusted. ### PHP #### Clear-box Review Check the use of [`unserialize()`]( function and review how the external parameters are accepted. Use a safe, standard data interchange format such as JSON (via `json_decode()` and `json_encode()`) if you need to pass serialized data to the user. ### Python #### Opaque-box Review If the traffic data contains the symbol dot `.` at the end, it's very likely that the data was sent in serialization. It will be only true if the data is not being encoded using Base64 or Hexadecimal schemas. If the data is being encoded, then it's best to chec", "query_type": "nl"} +{"_id": "code_q_000414", "text": "Find a secure code implementation example satisfying this security guidance: All applications have dependencies and those dependencies can have vulnerabilities. One good practice is to audit the dependencies your project is using. In general, it is important to have a process for updating dependencies. A sample process might define three mechanisms for triggering an update of response: --Every month/quarter dependencies in general are updated. --Every week important security vulnerabilities are considered and potentially trigger an update. --In EXCEPTIONAL conditions, emergency updates may need to be applied. The Django Security team has information on [How Django discloses security issues]( When a library is under consideration, consider the \"Security Health\" of the", "query_type": "nl"} +{"_id": "code_q_000415", "text": "Find a secure code implementation example satisfying this security guidance: HTTP defines [status code]( When designing REST API, don't just use `200` for success or `404` for error. Always use the semantically appropriate status code for the response. Here is a non-exhaustive selection of security related REST API **status codes**. Use it to ensure you return the correct code. | Code | Message | Description | |-------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 200 | OK | Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELE", "query_type": "nl"} +{"_id": "code_q_000417", "text": "Find a secure code implementation example satisfying this security guidance: There are a number of [security related headers]( that can be returned in the HTTP responses to instruct browsers to act in specific ways. However, some of these headers are intended to be used with HTML responses, and as such may provide little or no security benefits on an API that does not return HTML. Note that if the API is only consumed by non-browser clients (e.g. mobile apps, server-to-server calls, command-line tools), most of these headers will have no effect since they are directives for browsers. The following headers should be included in all API responses that may be consumed by browser clients: | Header | Rationale | |--------|-----------| | `Cache-Control: no-store` | Instruc", "query_type": "nl"} +{"_id": "code_q_000420", "text": "Find a secure code implementation example satisfying this security guidance: - [Symfony CSRF Documentation]( - [Symfony Twig Documentation]( - [Doctrine Security Documentation](", "query_type": "nl"} +{"_id": "code_q_000421", "text": "Find a secure code implementation example satisfying this security guidance: input_validation_fail:[(fieldone,fieldtwo...),userid] **Description** When input validation fails on the server-side it must either be because a) sufficient validation was not provided on the client, or b) client-side validation was bypassed. In either case it's an opportunity for attack and should be mitigated quickly. **Level:** WARN **Example:** --- ### input_validation_discrete_fail[:field,userid] **Description** When server-side validation of a value against a discrete list of options (e.g. drop down list, radio buttons) fails, it is a strong indication of malicious activity as this indicates the client-side code has been tampered with. **Level:** CRITICAL **Example:** ---", "query_type": "nl"} +{"_id": "code_q_000422", "text": "Find a secure code implementation example satisfying this security guidance: **Do:** - Derive tenant context from a server-verified identity and current membership or service authorization. - Use an enforceable isolation boundary appropriate to the data and threat model; database controls such as RLS or schema and credential separation can provide defense in depth. - Include tenant scope in queries, cache keys, and storage boundaries when the resource or result varies by tenant. - Include tenant identity in rate limits and quotas when tenants share capacity or have tenant-level entitlements; retain any needed global, endpoint, user, or IP limits. - Bound tenant consumption of other shared bottlenecks, such as queued work, concurrency, database connections, and comput", "query_type": "nl"} +{"_id": "code_q_000423", "text": "Find a secure code implementation example satisfying this security guidance: Input Validation and Sanitization Input screening can flag known attack phrasing for logging, review, or rate limiting. It is not a security boundary: LLMs do not enforce a boundary between instructions and data in a prompt, and an attacker can rephrase an instruction in many ways that a deny list does not match ([NCSC]( The [OWASP LLM01 guidance]( lists string checks and semantic filters as one mitigation, and describes attackers who use other languages or encodings such as Base64 to evade filters. Keyword and fuzzy-matching filters make two kinds of errors: - **False positives.** Single words such as `delete`, `system`, or `reveal` appear in ordinary requests, for example \"How do I delete ", "query_type": "nl"} +{"_id": "code_q_000424", "text": "Find a secure code implementation example satisfying this security guidance: Quick response in the event of a secret exposure is perhaps one of the most critical considerations for secrets management. ### 9.1 Documentation Incident response in the event of secret exposure should ensure that everyone in the chain of custody is aware and understands how to respond. This includes application creators (every member of a development team), information security, and technology leadership. Documentation must include: - How to test for secrets and secrets handling, especially during business continuity reviews. - Whom to alert when a secret is detected. - Steps to take for containment - Information to log during the event ### 9.2 Remediation The primary goal of incident resp", "query_type": "nl"} +{"_id": "code_q_000425", "text": "Find a secure code implementation example satisfying this security guidance: Use the examples below as a **smoke test, not a security benchmark**. These 16 hand-picked attack inputs and nine benign requests are illustrative, not a representative sample of application traffic or attacks. Adapt them to your application's supported tasks, permissions, and input channels; a request outside the application's scope is not a benign control. Before testing, define each case's intended security violation or legitimate task, required context, and observable outcome. Use dummy data and sandboxed tool substitutes. For indirect injection, place the input in the external content channel being evaluated; submitting it as a user message tests a different boundary. These examples are", "query_type": "nl"} +{"_id": "code_q_000426", "text": "Find a secure code implementation example satisfying this security guidance: Automated tests should specifically target the ways authorization usually degrades over time. Implement the following test patterns in your regression suite. ### Horizontal Escalation (IDOR) Validation [Horizontal privilege escalation]( occurs when a user accesses a resource belonging to another user with the same privilege level. The [OWASP IDOR Prevention Cheat Sheet](Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.md) describes the root cause: missing server-side ownership checks on object identifiers. - **Pattern:** The \"Multi-User Replay.\" - **Implementation:** Authenticate as User A and create Resource X. Capture the resource identifier. Authenticate as User B (same role, diffe", "query_type": "nl"} +{"_id": "code_q_000427", "text": "Find a secure code implementation example satisfying this security guidance: - [npm: Trusted Publishing with OIDC]( - [npm: Configuring Two-Factor Authentication](", "query_type": "nl"} +{"_id": "code_q_000428", "text": "Find a secure code implementation example satisfying this security guidance: Session ID Guessing and Brute Force Detection If an attacker tries to guess or brute force a valid session ID, they need to launch multiple sequential requests against the target web application using different session IDs from a single (or set of) IP address(es). Additionally, if an attacker tries to analyze the predictability of the session ID (e.g. using statistical analysis), they need to launch multiple sequential requests from a single (or set of) IP address(es) against the target web application to gather new valid session IDs. Web applications must be able to detect both scenarios based on the number of attempts to gather (or use) different session IDs and alert and/or block the offe", "query_type": "nl"} +{"_id": "code_q_000429", "text": "Find a secure code implementation example satisfying this security guidance: - Observability/SRE groups must support the use of this standard and encourage developers to use it - Incident Response must either ingest this data OR provide a means by which other monitoring teams can send a notification of alert, preferably programmatically. - Architects must support, adopt, and contribute to this standard - Developers must embrace this standard and begin to implement (requires knowledge and intent to understand potential attacks and trap those errors in code).", "query_type": "nl"} +{"_id": "code_q_000430", "text": "Find a secure code implementation example satisfying this security guidance: - [Kubernetes: Securing a Cluster]( - [Kubernetes Security Checklist](", "query_type": "nl"} +{"_id": "code_q_000431", "text": "Find a secure code implementation example satisfying this security guidance: - Use the `sandbox` attribute of an `iframe` for untrusted content. - The `sandbox` attribute of an `iframe` enables restrictions on content within an `iframe`. The following restrictions are active when the `sandbox` attribute is set: 1. All markup is treated as being from a unique origin. 2. All forms and scripts are disabled. 3. All links are prevented from targeting other browsing contexts. 4. All features that trigger automatically are blocked. 5. All plugins are disabled. It is possible to have a [fine-grained control]( over `iframe` capabilities using the value of the `sandbox` attribute. - In old versions of user agents where this feature is not supported, this attribute will be igno", "query_type": "nl"} +{"_id": "code_q_000432", "text": "Find a secure code implementation example satisfying this security guidance: Node.js applications are increasing in number and they are no different from other frameworks and programming languages. Node.js applications are prone to all kinds of web application vulnerabilities.", "query_type": "nl"} +{"_id": "code_q_000433", "text": "Find a secure code implementation example satisfying this security guidance: The JAAS configuration file contains a `LoginModule` stanza for each `LoginModule` available for logging on to the application. A stanza from a JAAS configuration file: Note the placement of the semicolons, terminating both `LoginModule` entries and stanzas. The word required indicates the `LoginContext`'s `login()` method must be successful when logging in the user. The `LoginModule`-specific values `debug` and `succeeded` are passed to the `LoginModule`. They are defined by the `LoginModule` and their usage is managed inside the `LoginModule`. Note, Options are Configured using key-value pairing such as `debug=\"true\"` and the key and value should be separated by a `=` sign.", "query_type": "nl"} +{"_id": "code_q_000434", "text": "Find a secure code implementation example satisfying this security guidance: This *Cheatsheet* intends to provide security tips to developers building Laravel applications. It aims to cover all common vulnerabilities and how to ensure that your Laravel applications are secure. The Laravel Framework provides in-built security features and is meant to be secure by default. However, it also provides additional flexibility for complex use cases. This means that developers unfamiliar with the inner workings of Laravel may fall into the trap of using complex features in a way that is not secure. This guide is meant to educate developers to avoid common pitfalls and develop Laravel applications in a secure manner.", "query_type": "nl"} +{"_id": "code_q_000435", "text": "Find a secure code implementation example satisfying this security guidance: Cross-Site Scripting (XSS) Cross-Site Scripting (XSS) is a type of attack where malicious JavaScript code is injected into a displayed variable. For example, if the value of the variable name is ``, and we display it in HTML like this: `Hello {{name}}`, the injected script will be executed when the HTML is rendered. Symfony comes by default with twig templates that automatically protect applications from XSS attacks by using **output escaping** to transform variables containing special characters by wrapping the variable with `{{ }}` statement. If you are rendering a variable that is trusted and contains HTML contents, you can use *Twig raw filter* to disable o", "query_type": "nl"} +{"_id": "code_q_000436", "text": "Find a secure code implementation example satisfying this security guidance: Secrets Management goes hand in hand with encryption. After all, secrets must be stored encrypted somewhere to protect their confidentiality and integrity. ### 7.1 Encryption Types to Use You can use various encryption types to secure a secret as long as they provide sufficient security, including adequate resistance against quantum computing-based attacks. Given that this is a moving field, it is best to follow current recommendations such as [NIST SP 800-57 Part 1]( which lists comparable security strengths for algorithms and key lengths, and the time frames during which each strength is acceptable, as well as the NSA's [Commercial National Security Algorithm Suite 2.0]( which enumerates q", "query_type": "nl"} +{"_id": "code_q_000437", "text": "Find a secure code implementation example satisfying this security guidance: SSR and RSC execute React code in a server environment that has direct access to databases, secrets, and internal network resources. This execution context introduces a class of vulnerabilities that do not exist in client-side React applications. The most critical architectural concern is the server/client data boundary, the point at which data serialized on the server is transmitted to the browser. Props passed from a Server Component to a Client Component cross this boundary automatically through the React Server Components protocol ([Next.js: How to Think About Security]( and any data that crosses it becomes accessible to the client regardless of how it was originally obtained or marked. ", "query_type": "nl"} +{"_id": "code_q_000438", "text": "Find a secure code implementation example satisfying this security guidance: Code **must** be correct. It **should** be secure. It **can** be efficient. [Dr. Jon Bentley]( _\"If it doesn't have to be correct, I can make it as fast as you'd like it to be\"_. [Dr. Gary McGraw]( _\"Thou shalt not rely solely on security features and functions to build secure software as security is an emergent property of the entire system and thus relies on building and integrating all parts properly\"_.", "query_type": "nl"} +{"_id": "code_q_000439", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Insecure Storage Storing sensitive data like authentication tokens in localStorage or other unsecured locations makes it easy for attackers to access. ### Example: Insecure Storage ### Mitigation: Insecure Storage Avoid persisting sensitive user data in the extension: [extension storage is not encrypted]( For sensitive data needed only while the browser is running, use [`chrome.storage.session`]( which stores data in memory and is not exposed to content scripts by default. Keep that access restriction and clear data when it is no longer needed. This reduces persistence and content-script exposure; it does not protect secrets from a compromised extension or device. Never hardco", "query_type": "nl"} +{"_id": "code_q_000440", "text": "Find a secure code implementation example satisfying this security guidance: A single control is brittle. Combine controls at three layers: 1. **Edge layer** — CDN, WAF, or anti-bot service: IP reputation, ASN filtering, TLS fingerprint (JA3/JA4), HTTP/2 fingerprint, basic rate limits. 2. **Application layer** — session-aware rate limits, identity-bound quotas, behavioral signals, honeypots, CAPTCHA challenges. 3. **Backend / business layer** — anomaly detection on transactions, account-velocity rules, fraud scoring, async review queues. A request that looks human at one layer (good IP, valid CAPTCHA) may still fail at another (10 checkouts in 30 seconds with different cards).", "query_type": "nl"} +{"_id": "code_q_000442", "text": "Find a secure code implementation example satisfying this security guidance: - [OpenSSF: Concise Guide for Evaluating Open Source Software]( - [Debian security FAQ]( - [Red Hat: Backporting Security Fixes](", "query_type": "nl"} +{"_id": "code_q_000443", "text": "Find a secure code implementation example satisfying this security guidance: HTTP Headers are a great booster for web security with easy implementation. Proper HTTP response headers can help prevent security vulnerabilities like Cross-Site Scripting, Clickjacking, Information disclosure and more. In this cheat sheet, we will review all security-related HTTP headers, recommended configurations, and reference other sources for complicated headers.", "query_type": "nl"} +{"_id": "code_q_000444", "text": "Find a secure code implementation example satisfying this security guidance: The npm ecosystem is the single largest repository of application libraries among all the other language ecosystems. The registry and the libraries in it are at the core for JavaScript developers as they are able to leverage work that others have already built and incorporate it into their codebase. With that said, the increasing adoption of open source libraries in applications brings with it an increased risk of introducing security vulnerabilities. Many popular npm packages have been found to be vulnerable and may carry a significant risk without proper security auditing of your project’s dependencies. Some examples are npm [request]( [superagent]( [mongoose]( and even security-related pa", "query_type": "nl"} +{"_id": "code_q_000445", "text": "Find a secure code implementation example satisfying this security guidance: [XSS attacks]( are injection attacks where malicious scripts (such as JavaScript code snippets) are injected into trusted websites. Laravel's [Blade echo statements]( `{{ }}` HTML-escape ordinary string values using `htmlspecialchars`. This is appropriate for HTML text and quoted ordinary text attributes, but does not validate URL schemes or encode JavaScript or CSS contexts. Laravel also offers displaying unescaped data using the unescaped syntax `{!! !!}`. This must not be used on any untrusted data, otherwise your application will be subject to an XSS attack. For instance, if you have something like this in any of your Blade templates, it would result in a vulnerability: For example, rend", "query_type": "nl"} +{"_id": "code_q_000446", "text": "Find a secure code implementation example satisfying this security guidance: [Cross-Site Request Forgery (CSRF)]( is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site when the user is authenticated. Laravel provides CSRF protection out-of-the-box with its CSRF token validation middleware, which is part of the `web` middleware group by default, so routes in `routes/web.php` are protected. Keep it enabled ([Laravel: CSRF protection]( Next, for all your `POST` request forms, you may use the `@csrf` blade directive to generate the hidden CSRF input token fields: For AJAX requests, you can setup the [X-CSRF-Token header]( Laravel also lets you exclude", "query_type": "nl"} +{"_id": "code_q_000447", "text": "Find a secure code implementation example satisfying this security guidance: Windows accepts path forms that checks written for Unix often miss ([Microsoft: Naming Files, Paths, and Namespaces]( - Both `\\` and `/` are separators, and paths starting with a drive letter (`C:\\`) or a UNC prefix (`\\\\server\\share\\`) are absolute. - Reserved device names such as `CON`, `NUL`, `COM1` and `LPT1` refer to devices, even with an extension like `NUL.txt`. - Filenames that end with a space or a period aren't supported by Windows tools, so reject them. - On NTFS, `file.txt::$DATA` is another name for `file.txt` and `file.txt:name` refers to a named stream of it, so a check on the name or extension can see a different string than the file that gets opened. Reject `:` in filenames (", "query_type": "nl"} +{"_id": "code_q_000448", "text": "Find a secure code implementation example satisfying this security guidance: Using Alternative Data Formats A great reduction of risk is achieved by avoiding native (de)serialization formats. By switching to a pure data format like JSON or XML, you lessen the chance of custom deserialization logic being repurposed towards malicious ends. Many applications rely on a [data-transfer object pattern]( that involves creating a separate domain of objects for the explicit purpose data transfer. Of course, it's still possible that the application will make security mistakes after a pure data object is parsed. ### Only Deserialize Signed Data If the application knows before deserialization which messages will need to be processed, they could sign them as part of the serializat", "query_type": "nl"} +{"_id": "code_q_000451", "text": "Find a secure code implementation example satisfying this security guidance: Defense Option 1: Escape all variables using the right LDAP encoding function LDAP distinguished names and LDAP search filters require different escaping rules, defined by [RFC 4514]( and [RFC 4515]( respectively. Avoid custom escaping code and use a library encoder for the correct context. #### Distinguished Name Escaping The main way LDAP stores names is based on DN (distinguished name). You can think of this like a unique identifier. These are sometimes used to access resources, like a username. A DN might look like this `cn=Richard Feynman, ou=Physics Department, dc=Caltech, dc=edu` or `uid=inewton, ou=Mathematics Department, dc=Cambridge, dc=com` An allowlist can be used to restrict inp", "query_type": "nl"} +{"_id": "code_q_000452", "text": "Find a secure code implementation example satisfying this security guidance: XSS happens when an application puts untrusted data into a page in a way that lets the browser treat it as code. For example, a user's comment that should appear as plain text instead runs as JavaScript or adds HTML the attacker controls. Untrusted data is anything your application did not create itself, such as form input, URL parameters, data stored by users, and responses from other services. To prevent XSS, every place where untrusted data is added to the page needs protection. Coverage is what matters: an application that protects 99 places and misses one is still vulnerable. Many frameworks escape every value they render by default, whether it is trusted or not. We recommend this appro", "query_type": "nl"} +{"_id": "code_q_000454", "text": "Find a secure code implementation example satisfying this security guidance: - [ ] Map application endpoints to the OWASP Automated Threats (OAT) catalog. - [ ] Apply rate limits at IP, identity, and endpoint levels, using a sliding window. - [ ] Layer defenses across edge, application, and business logic. - [ ] Use TLS/HTTP-level fingerprints before resorting to browser fingerprinting. - [ ] Replace visible CAPTCHAs with attestation tokens, invisible scoring, or PoW where possible. - [ ] Add honeypot fields and tarpit responses for high-confidence detections. - [ ] Verify email and phone numbers at signup; track signup velocity. - [ ] Enforce per-account purchase, address, and payment-method limits on scarce inventory. - [ ] Sign API requests; advertise quotas via `", "query_type": "nl"} +{"_id": "code_q_000455", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Third-Party Dependencies Using outdated or vulnerable third-party libraries in an extension can introduce security risks if those libraries have known exploits. ### Example: Third-Party Dependencies ### Mitigation: Third-Party Dependencies Regularly audit third-party dependencies for security vulnerabilities. Use tools like npm audit or OWASP Dependency-Check to detect risks.Prefer actively maintained libraries with frequent security updates.", "query_type": "nl"} +{"_id": "code_q_000456", "text": "Find a secure code implementation example satisfying this security guidance: Most of the projects use third-party dependencies to delegate handling of different kind of operations, _e.g._ generation of document in a specific format, HTTP communications, data parsing of a specific format, etc. It's a good approach because it allows the development team to focus on the real application code supporting the expected business feature. The dependency brings forth an expected downside where the security posture of the real application is now resting on it. This aspect is referenced in the following projects: - [OWASP TOP 10 2017]( under the point _[A9 - Using Components with Known Vulnerabilities]( - [OWASP Application Security Verification Standard Project]( under the sect", "query_type": "nl"} +{"_id": "code_q_000457", "text": "Find a secure code implementation example satisfying this security guidance: - **CORS is not access control.** The browser enforces it, and only for scripts running in the browser. Scripts can't change the `Origin` header ([MDN: Forbidden request header]( but any other client can send whatever `Origin` it likes. Authenticate and authorize every request on the server as if CORS didn't exist. - **CORS doesn't prevent CSRF.** Some cross-origin requests, such as a form `POST`, are sent without a preflight, so the server processes them even if the response can't be read ([MDN: Simple requests]( [PortSwigger: CORS]( Use the defenses in the [Cross-Site Request Forgery Prevention Cheat Sheet](Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md). - **Not sending CORS headers", "query_type": "nl"} +{"_id": "code_q_000458", "text": "Find a secure code implementation example satisfying this security guidance: This cheat sheet helps developers prevent XSS vulnerabilities. Cross-Site Scripting (XSS) is a misnomer. Originally this term was derived from early versions of the attack that were primarily focused on stealing data cross-site. Since then, the term has widened to include injection of basically any content. XSS attacks are serious and can lead to account impersonation, observing user behavior, loading external content, stealing sensitive data, and more. **This cheatsheet contains techniques to prevent or limit the impact of XSS. Since no single technique will solve XSS, using the right combination of defensive techniques will be necessary to prevent XSS.**", "query_type": "nl"} +{"_id": "code_q_000460", "text": "Find a secure code implementation example satisfying this security guidance: You can enrich containers with secrets in multiple ways: build time (not recommended) and during orchestration/deployment. ### 5.1 Injection of Secrets (file, in-memory) There are three ways to get secrets to an app inside a Docker container. - Mounted volumes (file): With this method, we keep our secrets within a particular config/secret file and mount that file to our instance as a mounted volume. Ensure that these mounts are mounted in by the orchestrator and never built-in, as this will leak the secret with the container definition. Instead, make sure that the orchestrator mounts in the volume when required. - Fetch from the secret store (in-memory): A sidecar app/container fetches the s", "query_type": "nl"} +{"_id": "code_q_000461", "text": "Find a secure code implementation example satisfying this security guidance: Object injection, eval code injection and extract variable hijacking attacks involve unserializing, evaluating or using the `extract` function on untrusted user input data. Some examples are: In general, avoid passing any untrusted input data to these dangerous functions.", "query_type": "nl"} +{"_id": "code_q_000463", "text": "Find a secure code implementation example satisfying this security guidance: You should consider adding the following security headers to your web server or Laravel application middleware: - X-Frame-Options - X-Content-Type-Options - Strict-Transport-Security (for HTTPS only applications) - Content-Security-Policy For more information, refer the [OWASP secure headers project](", "query_type": "nl"} +{"_id": "code_q_000464", "text": "Find a secure code implementation example satisfying this security guidance: This cheat sheet provides tips to prevent common security issues when using JSON Web Tokens (JWT). [**JSON Web Tokens**]( (JWT) are security tokens for carrying information (**claims**), often about a user, an application, etc. (**subject**). JWTs can provide authenticity of the claims (**signed JWT**) and/or confidentiality of the claims (**encrypted JWT**). In addition, JWT defines [standard claims]( JWTs are used in a wide range of applications such as: - In [OpenID Connect]( the [ID token]( is a JWT used to represent the identity and attributes of the connected user. - In [OAuth 2]( the access token used to obtain access to a protected resource [can be a JWT]( - A JWT is often suggested ", "query_type": "nl"} +{"_id": "code_q_000466", "text": "Find a secure code implementation example satisfying this security guidance: Consider the following snippet which is **NOT recommended** for defending against clickjacking: This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frame's URL. Unfortunately, multiple ways of defeating this type of script have been made public. We outline some here. ### Double Framing Some frame busting techniques navigate to the correct page by assigning a value to `parent.location`. This works well if the victim page is framed by a single page. However, if the attacker encloses the victim in one frame inside another (a double frame), then accessing `parent.location` becomes a securit", "query_type": "nl"} +{"_id": "code_q_000467", "text": "Find a secure code implementation example satisfying this security guidance: Web Messaging Web Messaging (also known as Cross Domain Messaging) provides a means of messaging between documents from different origins in a way that is generally safer than the multiple hacks used in the past to accomplish this task. However, there are still some recommendations to keep in mind: - When posting a message, explicitly state the expected origin as the second argument to `postMessage` rather than `*` in order to prevent sending the message to an unknown origin after a redirect or some other means of the target window's origin changing. - The receiving page should **always**: - Check the `origin` attribute of the sender to verify the data is originating from the expected locati", "query_type": "nl"} +{"_id": "code_q_000468", "text": "Find a secure code implementation example satisfying this security guidance: There are several methods and attributes which can be used to directly render HTML content within JavaScript. These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example: ### Example Dangerous HTML Methods #### Attributes #### Methods ### Guideline To make dynamic updates to HTML in the DOM safe, we recommend: 1. HTML encoding, and then 2. JavaScript encoding all untrusted input, as shown in these examples:", "query_type": "nl"} +{"_id": "code_q_000470", "text": "Find a secure code implementation example satisfying this security guidance: SSRF is an attack vector that abuses an application to interact with the internal/external network or the machine itself. One of the enablers for this vector is the mishandling of URLs, as showcased in the following examples: - Image on an external server (*e.g.* user enters image URL of their avatar for the application to download and use). - Server-side rendering of user-influenced content, such as HTML to PDF or image and video conversion, where the engine fetches URLs found in the document (see the [Server-Side Document and Media Rendering Cheat Sheet](Server_Side_Document_and_Media_Rendering_Cheat_Sheet.md)). - Custom [WebHook]( (users have to specify Webhook handlers or Callback URLs).", "query_type": "nl"} +{"_id": "code_q_000471", "text": "Find a secure code implementation example satisfying this security guidance: Token Status List If revocation of the JWTs by the issuer is needed, the [Token Status Lists]( (TSL) can be used: - the JWT contains the URI of a TSL; - the TSL aggregates the revocation status of several tokens in compressed form; - the consumer of the token can fetch the TSL to obtain the revocation status of the JWT. The issuer includes a `status` claim in the JWT. This claims contains the URI of the associated TSL and the index of the status of the JWT within this list:", "query_type": "nl"} +{"_id": "code_q_000473", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Data Leakage Some extensions unintentionally expose user data by sending browsing activity or personal details to external servers without proper security measures. ### Example: Data Leakage ### Mitigation: Data Leakage Always use HTTPS for all communications to prevent data interception. Limit data collection and be transparent by clearly stating what data is collected in a Privacy Policy.Implement user consent mechanisms before collecting or sending any personal data.", "query_type": "nl"} +{"_id": "code_q_000475", "text": "Find a secure code implementation example satisfying this security guidance: Ordinary session cookies are bearer credentials: anyone possessing a valid cookie can use it until it expires or the server invalidates it. Device Bound Session Credentials (DBSC) uses a device-bound signing key to prove possession when refreshing short-lived cookies, as described in the [DBSC refresh design]( Ordinary application requests still use those cookies as bearer credentials; DBSC does not bind every request to the key. An attacker can replay a stolen cookie during its remaining lifetime. Protecting the key limits the attacker's ability to refresh the session from another device; it does not make a stolen cookie immediately unusable. DBSC also does not prevent abuse while an attack", "query_type": "nl"} +{"_id": "code_q_000476", "text": "Find a secure code implementation example satisfying this security guidance: - [OWASP Top 10 Proactive Controls 2024: C3 — Validate all Input & Handle Exceptions]( - [this weakness: Improper Input Validation]( - [Unicode Standard Annex #15: Unicode Normalization Forms](", "query_type": "nl"} +{"_id": "code_q_000477", "text": "Find a secure code implementation example satisfying this security guidance: All of the code in the attached JAAS cheat sheet has been copied verbatim from this [free source](", "query_type": "nl"} +{"_id": "code_q_000480", "text": "Find a secure code implementation example satisfying this security guidance: JWT denylist In some cases, the consumer of the token might want to maintain a JWT denylist. This might be for example used a simple form of JWT replay protection or as a workaround for the “stateless session” invalidation problem. A JWT deny list can typically be implemented based on the `jti` and `iss` claims: Depending on the application and the type of JWT, other claims might be more suitable. **Warning:** Using the raw JWT or a secure hash of the JWT (`SHA-256(token)`) as the denylist key is *not safe* and might expose the application to **denylist bypass through [JWT malleability]( An attacker in possession of a revoked JWT might be able to modify an alternative representation of the J", "query_type": "nl"} +{"_id": "code_q_000481", "text": "Find a secure code implementation example satisfying this security guidance: - Use `django.contrib.auth` app for views and forms for user authentication operations such as login, logout, password change, etc. Include the module and its dependencies `django.contrib.contenttypes` and `django.contrib.sessions` in the `INSTALLED_APPS` setting in the `settings.py` file. - Use the `@login_required` decorator to ensure that only authenticated users can access a view. The sample code below illustrates usage of `@login_required`. - Use password validators for enforcing password policies. Add or update the `AUTH_PASSWORD_VALIDATORS` setting in the `settings.py` file to include specific validators required by your application. - Store passwords using `make-password` utility fun", "query_type": "nl"} +{"_id": "code_q_000482", "text": "Find a secure code implementation example satisfying this security guidance: A view in Django is a Python class or a function that returns a web response after it receives a web request. That response can be in simple HTTP, an HTML template, or an HTTP redirect request that redirects a user to another page.", "query_type": "nl"} +{"_id": "code_q_000483", "text": "Find a secure code implementation example satisfying this security guidance: One way to defend against clickjacking is to include a \"frame-breaker\" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header. In the document HEAD element, add the following: First apply an ID to the style element itself: Then, delete that style by its ID immediately after in the script: This way, everything can be in the document HEAD and you only need one method/taglib in your API.", "query_type": "nl"} +{"_id": "code_q_000484", "text": "Find a secure code implementation example satisfying this security guidance: For each technology stack, the following configuration options are proposed: ### Standard Java Web Application For this kind of application, a global error handler can be configured at the **web.xml** deployment descriptor level. We propose here a configuration that can be used from Servlet specification *version 2.5* and above. With this configuration, any unexpected error will cause a redirection to the page **error.jsp** in which the error will be traced and a generic response will be returned. Configuration of the redirection into the **web.xml** file: ``` xml ... ` tag directly to DOM with `src` attribute pointing to a script of [web accessible resources]( When an extension uses sensitive user information in any scripts executed on the web page's context, the data becomes accessible to the page's scripts. So, if the web page is compromised or malicious, the data will be stolen. The reason why the data becomes accessible is beca", "query_type": "nl"} +{"_id": "code_q_000496", "text": "Find a secure code implementation example satisfying this security guidance: [Mass assignment](Mass_Assignment_Cheat_Sheet.md) is a common vulnerability in modern web applications that use an ORM like Laravel's Eloquent ORM. A mass assignment is a vulnerability where an ORM pattern is abused to modify data items that the user should not be normally allowed to modify. Consider the following code: The above profile route allows the logged in user to change their profile information. However, let's say there is an `is_admin` column in the users table. You probably do not want the user to be allowed to change the value of this column. However, the above code allows users to change any column values for their row in the users table. This is a mass assignment vulnerability", "query_type": "nl"} +{"_id": "code_q_000497", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Lack of Content Security Policy (CSP) Weakening an extension’s Content Security Policy (CSP) can increase the impact of script injection. [Chrome enforces a default and minimum CSP for Manifest V3 extension pages]( even when the manifest omits a custom policy. ### Example: Restrictive Manifest V3 Policy ### Mitigation: Lack of Content Security Policy (CSP) Configure `content_security_policy.extension_pages` in `manifest.json` and load scripts from the extension package. Do not apply ordinary webpage nonce or hash recommendations to Chrome Manifest V3 extension pages: their [allowed script sources are restricted]( Keep inline script execution blocked and restrict other resource", "query_type": "nl"} +{"_id": "code_q_000498", "text": "Find a secure code implementation example satisfying this security guidance: Framework Security Protections, Output Encoding, and HTML Sanitization will provide the best protection for your application. OWASP recommends these in all circumstances. Consider adopting the following controls in addition to the above. - Cookie Attributes - These change how JavaScript and browsers can interact with cookies. Cookie attributes try to limit the impact of an XSS attack but don’t prevent the execution of malicious content or address the root cause of the vulnerability. - Content Security Policy - An allowlist that prevents content being loaded. It’s easy to make mistakes with the implementation so it should not be your primary defense mechanism. Use a CSP as an additional layer", "query_type": "nl"} +{"_id": "code_q_000499", "text": "Find a secure code implementation example satisfying this security guidance: This article is focused on providing clear, actionable guidance for safely deserializing untrusted data in your applications.", "query_type": "nl"} +{"_id": "code_q_000502", "text": "Find a secure code implementation example satisfying this security guidance: These illustrative examples assume authenticated requests and a policy that only owners can read documents. `currentUser()` represents an application helper that obtains the user from the trusted authentication context. Consider a Spring Boot endpoint that returns a document by its identifier: The `{id}` path variable is controlled by the requester and flows directly into `findById()`. Nothing verifies that the returned document belongs to the currently authenticated user, so any user who can guess or obtain a valid identifier can read another user's document. ### Fixing the code Prefer a lookup limited to documents owned by the current user. This mirrors the scoped-query approach shown for ", "query_type": "nl"} +{"_id": "code_q_000504", "text": "Find a secure code implementation example satisfying this security guidance: - [FastAPI: Dependencies]( - [FastAPI: OAuth2 with JWT tokens](", "query_type": "nl"} +{"_id": "code_q_000505", "text": "Find a secure code implementation example satisfying this security guidance: if(!(exp)) { \\ std::ostringstream oss; \\ oss << \"Assertion failed: \" << (char*)(__FILE__) << \"(\" \\ << (int)__LINE__ << \"): \" << (char*)(__func__) \\ << \": \\\"\" << (msg) << \"\\\"\" << std::endl; \\ std::cerr << oss.str(); \\ raise(SIGTRAP); \\ } \\ } ##elif (defined(ESAPI_BUILD_DEBUG) && defined(ESAPI_OS_WINDOWS))", "query_type": "nl"} +{"_id": "code_q_000506", "text": "Find a secure code implementation example satisfying this security guidance: A `LoginModule` must have the following authentication methods: - `initialize()` - `login()` - `commit()` - `abort()` - `logout()` ### initialize() In `Main()`, after the `LoginContext` reads the correct stanza from the config file, the `LoginContext` instantiates the `LoginModule` specified in the stanza. - `initialize()` methods signature: - `public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)` - The arguments above should be saved as follows: - `this.subject = subject;` - `this.callbackHandler = callbackHandler;` - `this.sharedState = sharedState;` - `this.options = options;` - What the `initialize()` method does: - ", "query_type": "nl"} +{"_id": "code_q_000507", "text": "Find a secure code implementation example satisfying this security guidance: During the build phase, you should secure your Kubernetes container images by building secure images and scanning those images for any known vulnerabilities. ### What is a container image? A container image (CI) is an immutable, lightweight, standalone package that contains everything required to run an application — the application code, runtime, system libraries, configuration and system tools. Images are built as layered, read-only artifacts that are portable between hosts but share the host machine’s operating system kernel. See Docker: What is a container? (< Your CIs must be built on a approved and secure base image. This base image must be scanned and monitored at regular intervals to", "query_type": "nl"} +{"_id": "code_q_000508", "text": "Find a secure code implementation example satisfying this security guidance: FastAPI parses multipart uploads into `UploadFile` objects, which spool larger files to temporary disk storage. See the [UploadFile documentation]( ### Upload Protections - **Limit Payloads Before Parsing:** Set a request-body limit at the reverse proxy or gateway, for example Nginx's [`client_max_body_size`]( Ensure clients cannot bypass that layer. FastAPI [parses the form before running dependencies]( checking `UploadFile.size` in a dependency or endpoint does not protect against the resources already consumed during parsing. - **Treat Metadata as Untrusted:** Do not use `UploadFile.filename` directly as a storage path or trust `content_type` as proof of file type. Apply the filename, con", "query_type": "nl"} +{"_id": "code_q_000509", "text": "Find a secure code implementation example satisfying this security guidance: Open Redirection attacks in themselves are not that dangerous but they enable phishing attacks. Consider the following code: This code redirects the user to any external URL provided by user input. This could enable attackers to create seemingly safe URLs like ` For instance, attackers may use a URL of this type to spoof password reset emails and lead victims to expose their credentials on the attacker's website.", "query_type": "nl"} +{"_id": "code_q_000510", "text": "Find a secure code implementation example satisfying this security guidance: React route guards, hidden buttons, and role checks in components control the user interface. They do not authorize API requests. Enforce authorization on the server for each protected operation, independently of what the React client renders; follow the [OWASP Authorization Cheat Sheet]( Never rely on client-provided roles as proof of permission.", "query_type": "nl"} +{"_id": "code_q_000511", "text": "Find a secure code implementation example satisfying this security guidance: The [OWASP API Security Top 10]( is a list of the most critical security risks for APIs that was developed by the [Open Worldwide Application Security Project (OWASP)]( It is designed to help organizations identify and prioritize the most significant risks to their APIs so that they can implement appropriate controls to mitigate those risks. This section uses the 2019 version of the API Security Top 10. The best approach to securing your web API is to start at the top threat (A1 below) and work your way down. This will ensure that any time spent on security will be spent most effectively because you will cover the top threats first. After you look at the Top 10, it is generally advisable to ", "query_type": "nl"} +{"_id": "code_q_000512", "text": "Find a secure code implementation example satisfying this security guidance: This article describes examples of attacks and defenses against cross-site leaks vulnerability (XS Leaks). Since this vulnerability is based on the core mechanism of modern web browsers, it's also called a browser side-channel attack. XS-Leaks attacks seek to exploit the fact of seemingly insignificant information that is exchanged in cross-site communications between sites. This information infers answers to the previously asked questions about the victim's user account. Please take a look at the examples provided below: - Is the user currently logged in? - Is the user ID 1337? - Is the user an administrator? - Does the user have a person with a particular email address in their contact lis", "query_type": "nl"} +{"_id": "code_q_000513", "text": "Find a secure code implementation example satisfying this security guidance: React escapes text values rendered through JSX by default, but raw HTML and URL-bearing props require additional controls ([OWASP XSS Prevention Cheat Sheet, Framework Security]( This cheat sheet covers React-specific rendering, component data exposure, and the server/client boundary in server-side rendering (SSR) and React Server Components (RSC). Examples illustrate individual controls and require application-specific validation and testing.", "query_type": "nl"} +{"_id": "code_q_000514", "text": "Find a secure code implementation example satisfying this security guidance: This cheat sheet lists actions developers can take to develop secure Node.js applications. Each item has a brief explanation and solution that is specific to the Node.js environment.", "query_type": "nl"} +{"_id": "code_q_000515", "text": "Find a secure code implementation example satisfying this security guidance: Use a Content Security Policy to limit the damage of several threats described in this sheet. See the [OWASP Content Security Policy Cheat Sheet](", "query_type": "nl"} +{"_id": "code_q_000516", "text": "Find a secure code implementation example satisfying this security guidance: Code Pattern Analysis Focus on high-risk code patterns: - Input processing and validation functions - Database query construction and ORM usage - File operations and path handling - Authentication and session management logic - Authorization and access control checks - Cryptographic operations and key management - Error handling and logging mechanisms - Configuration loading and environment variables ### Data Flow Analysis Trace data through the application: 1. **Identify Sources**: User inputs, file uploads, API calls, database reads, environment variables 2. **Follow Processing**: Validation, transformation, business logic, caching 3. **Check Sinks**: Database queries, file writes, output ", "query_type": "nl"} +{"_id": "code_q_000517", "text": "Find a secure code implementation example satisfying this security guidance: npm outdated command Rushing to constantly upgrade dependencies to their latest releases is not necessarily a good practice if it is done without reviewing release notes, the code changes, and generally testing new upgrades in a comprehensive manner. With that said, staying out of date and not upgrading at all, or after a long time, is a source for trouble as well. The npm CLI can provide information about the freshness of dependencies you use with regards to their semantic versioning offset. By running `npm outdated`, you can see which packages are out of date. Dependencies in yellow correspond to the semantic versioning as specified in the `package.json` manifest, and dependencies colored ", "query_type": "nl"} +{"_id": "code_q_000518", "text": "Find a secure code implementation example satisfying this security guidance: Do not treat component state or props as a confidentiality boundary within the page. React has exposed component internals through DOM node properties, as shown in [React 19.2's DOM integration]( Although implementation details can change, omitting a value from rendered HTML does not make it private from scripts running in the same page. Minimize the sensitive data delivered to the browser and shared with components. ### Store Authentication Tokens in HttpOnly Cookies A React client cannot set an `HttpOnly` cookie; use a server-side layer to set session cookies. `HttpOnly` prevents scripts from reading the cookie, but does not stop injected scripts from making authenticated requests. Follow ", "query_type": "nl"} +{"_id": "code_q_000519", "text": "Find a secure code implementation example satisfying this security guidance: AI agents are autonomous systems powered by Large Language Models (LLMs) that can reason, plan, use tools, maintain memory, and take actions to accomplish goals. This expanded capability introduces unique security risks beyond traditional LLM prompt injection. This cheat sheet provides best practices to secure AI agent architectures and minimize attack surfaces.", "query_type": "nl"} +{"_id": "code_q_000520", "text": "Find a secure code implementation example satisfying this security guidance: **Do**: - Enforce least privilege per function. - Validate all event inputs. - Fetch secrets from vaults, not platform config. - Restrict network egress. - Monitor invocations and logs. **Don’t**: - Hardcode secrets in code or configs. - Assume clean runtime between invocations. - Give `*` IAM permissions. - Leave sensitive data in `/tmp` or globals. - Trust event sources blindly.", "query_type": "nl"} +{"_id": "code_q_000523", "text": "Find a secure code implementation example satisfying this security guidance: Session Cookies are given to users when they log in. If these are stolen by an attacker and used to hijack the session from the attacker's device, certain environment information used in the connection for session will change. For example, if stolen cookies are used by an attacker from another country, you can detect this by detecting a significant change in the IP address. In this way, there are multiple vectors that can be used to detect that the user environments has changed. - Access from different region (IP Address) - Access from different device (User-Agent) - Access from different language setting (Accept-Language) - Access at different time of day (Date) If you save this information", "query_type": "nl"} +{"_id": "code_q_000524", "text": "Find a secure code implementation example satisfying this security guidance: - [OWASP Java Encoder: Output Contexts and Boundaries]( - [DOMPurify Documentation]( - [CSSStyleDeclaration: setProperty() method]( - [Trusted Types API](", "query_type": "nl"} +{"_id": "code_q_000527", "text": "Find a secure code implementation example satisfying this security guidance: Implement Security Monitoring Monitor gRPC services for security events and potential attacks. Key metrics to monitor: - Request rates per method and client - Authentication and authorization failure rates - Error rates and types - Unusual traffic patterns Set up alerts for: - High authentication failure rates - Attempts to access non-existent methods - Resource exhaustion patterns ### Enable Distributed Tracing Track requests across microservices for security analysis.", "query_type": "nl"} +{"_id": "code_q_000528", "text": "Find a secure code implementation example satisfying this security guidance: When using JSON Web Tokens (JWTs), developers are responsible for token verification and key management. The [FastAPI OAuth2 with JWT tutorial]( demonstrates verification with PyJWT. ### Cryptographic Library Choice - **Use PyJWT:** Delegate token verification to the library rather than writing custom parsing or cryptographic logic. Configure verification using the [PyJWT decoding API]( ### Key Claims Verification - **Validate Required Claims:** Verify the signature and require `exp` (expiration), `iss` (issuer), and `aud` (audience) for authentication tokens. In PyJWT, use `options={\"require\": [\"exp\", \"iss\", \"aud\"]}` and supply the expected `issuer` and `audience`. Requiring a claim only ch", "query_type": "nl"} +{"_id": "code_q_000530", "text": "Find a secure code implementation example satisfying this security guidance: A path traversal attack aims to access files by manipulating request input data with `../` sequences and variations or by using absolute file paths. If you allow users to download files by filename, you may be exposed to this vulnerability if input data is not stripped of directory information. Consider the following code: Here, the filename is not stripped of directory information, so a malformed filename such as `../../.env` could expose your application credentials to potential attackers. Similar to unrestricted file uploads, you should use the `basename` PHP function to strip out directory information like so:", "query_type": "nl"} +{"_id": "code_q_000531", "text": "Find a secure code implementation example satisfying this security guidance: - Over-permissioned functions (broad IAM roles, `*` policies). - Unvalidated event inputs (API Gateway, S3, Pub/Sub, IoT). - Cold start data leakage (persistent state, side-channel timing). - Function chaining abuse (compromised function invoking others). - Shared environment risks (multi-tenant leakage, `/tmp` reuse). - Hardcoded secrets in code or platform config. - Excessive network access.", "query_type": "nl"} +{"_id": "code_q_000532", "text": "Find a secure code implementation example satisfying this security guidance: Classic npm tokens have been revoked. Prefer [trusted publishing with OpenID Connect]( for supported CI/CD publishing workflows because it avoids stored, long-lived publishing credentials. When a token is still required, use a [granular access token]( with only the packages, organizations, and permissions needed. Use read-only access for dependency installation, set the shortest practical expiration, restrict source IP ranges where stable, and enable bypassing 2FA only for non-interactive workflows that cannot use trusted publishing. Store the token in a CI secret store and never commit it. Review tokens regularly with `npm token list` and immediately revoke unnecessary or exposed tokens wit", "query_type": "nl"} +{"_id": "code_q_000534", "text": "Find a secure code implementation example satisfying this security guidance: [XPath variables represent values]( they do not substitute expression fragments. When a user chooses a query mode, map that choice to a complete, fixed expression defined by the application. Reject unknown choices and bind any external data values separately. For example, a catalog application can map the choices `books` and `magazines` to the fixed paths `/catalog/book` and `/catalog/magazine`. Do not insert the selected choice directly into a path or accept user-supplied predicates, operators, or function calls. Validate values against the application's expected types, lengths, and business rules, following the [Input Validation Cheat Sheet](Input_Validation_Cheat_Sheet.md). Validation com", "query_type": "nl"} +{"_id": "code_q_000535", "text": "Find a secure code implementation example satisfying this security guidance: Visible CAPTCHAs (image grids, distorted text) are accessibility-hostile, machine-solvable by ML, and outsourced to human solver farms for fractions of a cent per solve. Treat them as a **last-resort step-up**, not a primary defense. Prefer the following alternatives or layer them: - **Cryptographic attestation tokens** — [Privacy Pass]( lets an origin verify that a client satisfied an issuer's attestation policy, such as a CAPTCHA, a device check, or account validation. Select trusted issuers whose policies match your use case; a valid token is not a general proof that the requester is human. [Privacy guarantees]( depend on the deployment and its trust assumptions. - **Managed challenges** ", "query_type": "nl"} +{"_id": "code_q_000536", "text": "Find a secure code implementation example satisfying this security guidance: - [MDN: JavaScript prototype pollution]( - [Node.js: Command-line API](", "query_type": "nl"} +{"_id": "code_q_000537", "text": "Find a secure code implementation example satisfying this security guidance: Consult the project [OWASP Secure Headers]( in order to obtains the list of HTTP security headers that an application should use to enable defenses at browser level.", "query_type": "nl"} +{"_id": "code_q_000538", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Malicious Updates If an extension fetches updates from an untrusted server, an attacker could push malicious updates to all users. ### Example: Malicious Updates ### Mitigation: Malicious Updates Sign extension updates with digital signatures to ensure authenticity. Instead of fetching updates within the extension, rely on updates from the extension marketplace. See [\"Don’t inject or incorporate remote scripts\"]( Implement integrity checks before executing any fetched code.", "query_type": "nl"} +{"_id": "code_q_000539", "text": "Find a secure code implementation example satisfying this security guidance: XPath selects data from XML documents. [XPath injection]( occurs when external input becomes part of an expression's syntax, allowing it to change the query's meaning. Prevent it by keeping expressions under application control and passing external values through variable binding.", "query_type": "nl"} +{"_id": "code_q_000540", "text": "Find a secure code implementation example satisfying this security guidance: Java Bind the untrusted value with an [`XPathVariableResolver`]( (OK): Example of vulnerable code building a XPath query using dynamic input:", "query_type": "nl"} +{"_id": "code_q_000541", "text": "Find a secure code implementation example satisfying this security guidance: Remote Content Sanitization For systems processing external content: - Remove common injection patterns from external sources - Sanitize code comments and documentation before analysis - Filter suspicious markup in web content and documents - Validate encoding and decode suspicious content for inspection ### Hidden Text in Documents Ingestion pipelines usually pass the model a document's extracted text and discard how it renders, so text a reader cannot see still reaches the model. Check untrusted documents before the model reads them: - Render each page and flag extracted text that does not appear on it. [PhantomLint]( pairs phrase matching with an optical character recognition (OCR) check ", "query_type": "nl"} +{"_id": "code_q_000542", "text": "Find a secure code implementation example satisfying this security guidance: `Access-Control-Allow-Credentials: true` lets a cross-origin script read the response to a request that includes credentials: cookies, TLS client certificates, or HTTP authentication (not a token the script itself sets in the `Authorization` header). It doesn't decide whether cookies are sent: that depends on the request's credentials mode and the cookie's `SameSite` attribute, so the server still processes the request and the browser only withholds the response. The Fetch Standard calls sharing such responses \"rather unsafe\" and warns about the confused deputy problem ([Fetch Standard: CORS protocol and credentials]( - Only enable credentials for endpoints and origins that need them, and ke", "query_type": "nl"} +{"_id": "code_q_000543", "text": "Find a secure code implementation example satisfying this security guidance: The npm CLI works with package run-scripts. If you’ve ever run `npm start` or `npm test` then you’ve used package run-scripts too. The npm CLI builds on scripts that a package can declare, and allows packages to define scripts to run at specific entry points during the package’s installation in a project. For example, some of these [script hook]( entries may be `postinstall` scripts that a package that is being installed will execute in order to perform housekeeping chores. With this capability, bad actors may create or alter packages to perform malicious acts by running any arbitrary command when their package is installed. A couple of cases where we’ve seen this already happening is the po", "query_type": "nl"} +{"_id": "code_q_000544", "text": "Find a secure code implementation example satisfying this security guidance: - [MDN: Cross-Site Scripting (XSS)]( - [this weakness: Improper Neutralization of Input During Web Page Generation]( - [PortSwigger: Cross-Site Scripting (XSS) Cheat Sheet](", "query_type": "nl"} +{"_id": "code_q_000545", "text": "Find a secure code implementation example satisfying this security guidance: Mozilla Observatory The [Mozilla Observatory]( is an online tool which helps you to check your website's header status. ### SmartScanner [SmartScanner]( has a dedicated [test profile]( for testing security of HTTP headers. Online tools usually test the homepage of the given address. But SmartScanner scans the whole website. So, you can make sure all of your web pages have the right HTTP Headers in place.", "query_type": "nl"} +{"_id": "code_q_000547", "text": "Find a secure code implementation example satisfying this security guidance: 1. Principle of Least Privilege - Assign minimal IAM permissions to each function. - Use role-per-function (avoid shared high-privilege roles). - Scope database/API keys to the smallest set of actions needed. **Bad IAM Policy (too broad):** **Good IAM Policy (scoped):** ### 2. Environment Isolation - Disable default network access unless required (e.g. outbound internet access). - Place functions in private subnets with controlled egress. - Isolate sensitive functions (e.g. payment, auth) from general-purpose ones. - Separate production vs. staging environments with strict boundaries. **AWS Lambda VPC Config (restrictive):** ### 3. Secure Function Invocation - Enforce authentication and auth", "query_type": "nl"} +{"_id": "code_q_000548", "text": "Find a secure code implementation example satisfying this security guidance: - [gRPC Authentication Documentation]( - [gRPC: Deadlines]( - [gRPC: Reflection](", "query_type": "nl"} +{"_id": "code_q_000550", "text": "Find a secure code implementation example satisfying this security guidance: - [OpenSSF: Compiler Options Hardening Guide for C and C++]( - [GCC: Instrumentation Options]( - [Clang Compiler User’s Manual]( - [Microsoft: Security Best Practices for C++](", "query_type": "nl"} +{"_id": "code_q_000551", "text": "Find a secure code implementation example satisfying this security guidance: - [DOMPurify: HTML Sanitization]( - [React: use server Security Considerations]( - [Vite: Environment Variables and Modes](", "query_type": "nl"} +{"_id": "code_q_000553", "text": "Find a secure code implementation example satisfying this security guidance: - If your application uses cookies, make sure to set the appropriate [SameSite attribute](#samesite-cookies). - Think about whether you really want to allow your application to be embedded in frames. If not, consider using the mechanisms described in the [framing protection](#framing-protection) section. - To strengthen the isolation of your application between other origins, use [Cross Origin Resource Policy](#cross-origin-resource-policy-corp) and [Cross Origin Opener Policy](#cross-origin-opener-policy-coop) headers with appropriate values. - Use the headers available within Fetch Metadata to build your own resource isolation policy.", "query_type": "nl"} +{"_id": "code_q_000554", "text": "Find a secure code implementation example satisfying this security guidance: Django 6.0 and later provide built-in Content Security Policy (CSP) support. Enable `django.middleware.csp.ContentSecurityPolicyMiddleware` and configure `SECURE_CSP` to enforce a policy, or `SECURE_CSP_REPORT_ONLY` to monitor violations without blocking content. Follow [Django's CSP configuration guide]( Earlier versions require a third-party library such as `django-csp` or configuration of HTTP response headers. For more details: - [OWASP Content Security Policy Cheat Sheet]( - [Django Security Documentation](", "query_type": "nl"} +{"_id": "code_q_000555", "text": "Find a secure code implementation example satisfying this security guidance: Review query construction in application code and stored procedures. Check that untrusted values are bound rather than concatenated into SQL, and that dynamic identifiers and sort directions come from the query's fixed mapping. Preparing the outer call is not evidence that a procedure's internal SQL is safe. Use the [OWASP Web Security Testing Guide's SQL injection tests]( for manual and automated testing, including blind and out-of-band techniques.", "query_type": "nl"} +{"_id": "code_q_000557", "text": "Find a secure code implementation example satisfying this security guidance: Treat input screening and the structured prompts above as illustrative layers, not a complete prompt-injection defense. The [OWASP prompt-injection guidance]( describes both direct and indirect injection and recommends controls beyond filtering: - Identify untrusted content from every channel, including retrieved documents, tool results, and conversation history. Keep it separate from trusted instructions; labeling alone does not enforce that boundary. - Validate proposed tool arguments and enforce the caller's permissions in execution code outside the model. Grant each tool only the data and operations it needs. - Require action-specific approval for high-risk operations before they run, us", "query_type": "nl"} +{"_id": "code_q_000558", "text": "Find a secure code implementation example satisfying this security guidance: Use FastAPI's dependency injection system, through `Depends()`, to enforce authentication and authorization consistently. Missing or insufficient dependencies can leave sensitive operations accessible to unauthorized users. See the [FastAPI dependencies tutorial]( ### OAuth2PasswordBearer Does Not Validate Tokens The helper class `OAuth2PasswordBearer` checks the authorization scheme and extracts the bearer token from the `Authorization` header. It does **not validate the token or verify its signature**. An authentication dependency must verify the token and reject invalid credentials before returning a user. See the [OAuth2PasswordBearer reference]( ### Scoping Authorization Dependencies Au", "query_type": "nl"} +{"_id": "code_q_000559", "text": "Find a secure code implementation example satisfying this security guidance: Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings. In many cases, JavaScript encoding does not stop attacks within an execution context. For example, a JavaScript encoded string will execute even though it is JavaScript encoded. Therefore, the primary recommendation is to **avoid including untrusted data in this context**. If you must, the following examples describe some approaches that do and do not work. The `setAttribute(name_string,value_string)` method is dangerous because it implicitly coerces the *value_string* into the DOM attribute datatype of *name_str", "query_type": "nl"} +{"_id": "code_q_000560", "text": "Find a secure code implementation example satisfying this security guidance: Perform gRPC Security Testing Include gRPC-specific security tests in your development pipeline. Test categories: - Authentication bypass attempts - Authorization boundary testing - Input validation and injection testing - Rate limiting effectiveness - Message size limit enforcement Use tools like `grpcurl` and custom test clients to verify security controls. ### Security Assessment Guidelines - Test all gRPC methods for proper authentication and authorization - Verify input validation on all message fields - Test rate limiting and resource exhaustion protections - Validate TLS configuration and certificate handling - Check for information disclosure in error messages", "query_type": "nl"} +{"_id": "code_q_000561", "text": "Find a secure code implementation example satisfying this security guidance: - [Node.js Security Best Practices]( - [Node.js Permissions]( - [Express: Production Security Best Practices](", "query_type": "nl"} +{"_id": "code_q_000562", "text": "Find a secure code implementation example satisfying this security guidance: NoSQL databases (MongoDB, CouchDB, Cassandra etc.) power many modern applications with flexible schemas and horizontal scale. This cheat sheet summarizes guidance to reduce risk when using NoSQL systems.", "query_type": "nl"} +{"_id": "code_q_000563", "text": "Find a secure code implementation example satisfying this security guidance: This cheat sheet was previously named the AJAX Security Cheat Sheet. This document will provide a starting point for AJAX security and will hopefully be updated and expanded reasonably often to provide more detailed information about specific frameworks and technologies. For applications that compose independently deployed frontend features, see the [Micro-Frontend Security Cheat Sheet](Micro_Frontend_Security_Cheat_Sheet.md) for runtime isolation, cross-application messaging, and host-to-remote trust boundaries. **Before applying any specific control, developers must adopt a fundamental security mindset:** All data should be considered untrusted unless explicitly validated and safely handle", "query_type": "nl"} +{"_id": "code_q_000564", "text": "Find a secure code implementation example satisfying this security guidance: An XML document is malformed if it does not adhere to the XML syntax. A conforming parser rejects a malformed document and stops processing it, and the application should display an error message rather than continue. This is a syntax-level failure, distinct from a document that is well-formed but invalid against its schema. Typical causes are a missing end tag, elements ordered into a nonsensical structure, and forbidden characters. **To deal with malformed documents, use an XML processor that follows the W3C specifications, accept only well-formed documents, verify the contents of each element, and process only values within predefined boundaries.** Malformed input can also be expensive: s", "query_type": "nl"} +{"_id": "code_q_000565", "text": "Find a secure code implementation example satisfying this security guidance: Use \"new Set()\" or \"new Map()\" Developers should use `new Set()` or `new Map()` instead of using object literals: ### If objects or object literals are required If objects have to be used then they should be created using the `Object.create(null)` API to ensure they don't inherit from the Object prototype: If object literals are required then as a last resort you could use the `__proto__` property: ### Use object \"freeze\" and \"seal\" mechanisms Freezing built-in prototypes with [`Object.freeze()`]( prevents adding or removing their properties and makes existing data properties non-writable. Freezing is shallow: objects referenced by those properties remain mutable unless separately frozen. Te", "query_type": "nl"} +{"_id": "code_q_000566", "text": "Find a secure code implementation example satisfying this security guidance: - [W3C: Extensible Markup Language (XML) 1.0]( - [W3C: XML Schema Definition Language (XSD) 1.1, Part 2 — Datatypes]( - [Oracle Java 25: JAXP Security Guide](", "query_type": "nl"} +{"_id": "code_q_000567", "text": "Find a secure code implementation example satisfying this security guidance: Server Direct Data Layer A server-side collector can filter the data sent to vendors and move eligible tags out of the browser. It does not isolate any scripts that still run in the page. The data layer can perform any validation of the values, especially values from DOM objects exposed to the user like URL parameters and input fields, if these are required for the marketing analysis. An example statement for a corporate standard document is 'The tag JavaScript can only access values in the host data layer. The tag JavaScript can never access a URL parameter. You the host page developer have to agree with the third-party vendors or the tag manager what attribute in the data layer will have w", "query_type": "nl"} +{"_id": "code_q_000569", "text": "Find a secure code implementation example satisfying this security guidance: **Attackers may introduce unexpected values in documents to take advantage of an application that does not verify whether the document contains a valid set of values.** Treat schema validation as a fail-closed contract: accept a document only after the entire document passes validation; otherwise reject it. More than one schema language can be layered (structural validation first, value restrictions second, for example). Streaming validators can deliver content before reporting a later validation failure, so do not commit application effects until all validation succeeds, and discard buffered results on failure. Each XML document should be validated against a precisely defined [XML Schema]( ", "query_type": "nl"} +{"_id": "code_q_000570", "text": "Find a secure code implementation example satisfying this security guidance: Signed JWTs are not confidential A signed JWT ([JSON Web Signature]( JWS) provides integrity and authenticity, but not confidentiality. The payload is only base64url encoded, not encrypted, so anyone who obtains the token can read every claim. With a MAC (`HS*`), a valid signature also only proves that the token was produced by some holder of the shared secret, see [Public-key Signatures vs. MAC](#public-key-signatures-vs-mac). TLS prevents the token from being read in transit, but the claims remain exposed elsewhere: in application logs, in browser storage, in referrer headers, and to any intermediary that terminates TLS. [Omitting privacy-sensitive information from a JWT is the simplest wa", "query_type": "nl"} +{"_id": "code_q_000571", "text": "Find a secure code implementation example satisfying this security guidance: Input validation checks whether data meets an application's requirements before the application uses it. It reduces the risk of malformed data, invalid business operations, and excessive resource consumption. [OWASP's Proactive Control C3]( distinguishes validation from the additional defenses needed when using that data: - Use [parameterized queries](SQL_Injection_Prevention_Cheat_Sheet.md) for SQL and [context-aware output encoding](Cross_Site_Scripting_Prevention_Cheat_Sheet.md#output-encoding) to prevent cross-site scripting (XSS). - Check [authorization](Authorization_Cheat_Sheet.md) separately: a valid account identifier does not mean the caller may access that account.", "query_type": "nl"} +{"_id": "code_q_000572", "text": "Find a secure code implementation example satisfying this security guidance: - [OWASP LLM06:2025 Excessive Agency]( - [NIST Artificial Intelligence Risk Management Framework (AI RMF 1.0)]( - [Git: git-config documentation](", "query_type": "nl"} +{"_id": "code_q_000573", "text": "Find a secure code implementation example satisfying this security guidance: - [Django 5.2: Clickjacking Protection]( - [Django 5.2: Security Middleware](", "query_type": "nl"} +{"_id": "code_q_000574", "text": "Find a secure code implementation example satisfying this security guidance: Configure the ASGI server's proxy trust explicitly so clients cannot spoof the client address or request scheme using forwarding headers. See the [Uvicorn HTTP settings]( ### Deployment Configuration - **Limit Proxy Forwarding:** Set `--forwarded-allow-ips` to the addresses of trusted reverse proxies and configure those proxies to overwrite untrusted forwarding headers. Avoid `--forwarded-allow-ips=\"*\"`, which trusts every connecting client. Disable proxy-header handling with `--no-proxy-headers` if it is not needed. - **Disable Server Header:** Use `--no-server-header` to suppress Uvicorn's default `Server` header. This removes one identifying header; it does not prevent other forms of serv", "query_type": "nl"} +{"_id": "code_q_000575", "text": "Find a secure code implementation example satisfying this security guidance: Defending against XSS is hard. For that reason, some have sought shortcuts to preventing XSS. We're going to examine two common [anti-patterns]( that frequently show up in ancient posts, but are still commonly cited as solutions in modern posts about XSS defense on programmer forums such as Stack Overflow and other developer hangouts. ### Sole Reliance on Content-Security-Policy (CSP) Headers First, let us be clear, we are a strong proponent of CSP when it is used properly. In the context of XSS defense, CSP works best when it it is: - Used as a defense-in-depth technique. - Customized for each individual application rather than being deployed as a one-size-fits-all enterprise solution. What", "query_type": "nl"} +{"_id": "code_q_000576", "text": "Find a secure code implementation example satisfying this security guidance: Vulnerability: Cross-Site Scripting (XSS) If user input is not properly sanitized, attackers can inject malicious scripts into web pages, potentially stealing user data or performing unauthorized actions. ### Example: Cross-Site Scripting (XSS) ### Mitigation: Cross-Site Scripting (XSS) Implement Content Security Policy (CSP) to block inline scripts. Use libraries like DOMPurify to sanitize user input before displaying it. Avoid using innerHTML and instead use textContent to prevent execution of injected scripts.", "query_type": "nl"} +{"_id": "code_q_000579", "text": "Find a secure code implementation example satisfying this security guidance: - [AWS Lambda: Best practices]( - [Azure Functions: Security concepts]( - [Google Cloud Run: Security](", "query_type": "nl"} +{"_id": "code_q_000580", "text": "Find a secure code implementation example satisfying this security guidance: ##endif c // A debug assert which should be sprinkled liberally. // This assert fires and then continues rather // than calling abort(). Useful when examining negative // test cases from the command-line. ##if (defined(ESAPI_BUILD_DEBUG) && defined(ESAPI_OS_STARNIX))", "query_type": "nl"} +{"_id": "code_q_000582", "text": "Find a secure code implementation example satisfying this security guidance: Strict Policy A strict policy's role is to protect against classical stored, reflected, and some of the DOM XSS attacks and should be the optimal goal of any team trying to implement CSP. As noted above, Google went ahead and set up a detailed and methodological [instructions]( for creating a Strict CSP. Based on those instructions, one of the following two policies can be used to apply a strict policy: #### Nonce-based Strict Policy #### Hash-based Strict Policy ### Basic non-Strict CSP Policy This policy can be used if it is not possible to create a Strict Policy and it prevents cross-site framing and cross-site form-submissions. It will only allow resources from the originating domain for", "query_type": "nl"} +{"_id": "code_q_000583", "text": "Find a secure code implementation example satisfying this security guidance: Join the kubernetes-announce group (< for emails about security announcements. See the security reporting page (< for more on how to report vulnerabilities.", "query_type": "nl"} +{"_id": "code_q_000584", "text": "Find a secure code implementation example satisfying this security guidance: - [MDN: innerHTML Security Considerations]( - [DOMPurify: HTML Sanitization](", "query_type": "nl"} +{"_id": "code_q_000586", "text": "Find a secure code implementation example satisfying this security guidance: Project.delete(:name => 'name') ruby insert_new_user = db.prepare \"INSERT INTO users (name, age, gender) VALUES (?, ? ,?)\" insert_new_user.execute 'aizatto', '20', 'male' php $stmt = $dbh->prepare(\"INSERT INTO REGISTRY (name, value) VALUES (:name, :value)\"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); coldfusion SELECT * FROM #strDatabasePrefix#_courses WHERE intCourseID = perl my $sql = \"INSERT INTO foo (bar, baz) VALUES ( ?, ? )\"; my $sth = $dbh->prepare( $sql ); $sth->execute( $bar, $baz ); rust // Input from CLI args but could be any", "query_type": "nl"} +{"_id": "code_q_000587", "text": "Find a secure code implementation example satisfying this security guidance: Once a Kubernetes infrastructure is in place, you must configure it securely before any workloads are deployed. And as you configure your infrastructure, ensure that you have visibility into what CIs are being deployed and how they are being deployed or else you will not be able to identify and respond to security policy violations. Before deployment, your system should know and be able to tell you: - **What is being deployed** - including information about the image being used, such as components or vulnerabilities, and the pods that will be deployed. - **Where it is going to be deployed** - which clusters, namespaces, and nodes. - **How it is deployed** - whether it runs privileged, what o", "query_type": "nl"} +{"_id": "code_q_000588", "text": "Find a secure code implementation example satisfying this security guidance: **Deny-lists are bypass-prone. Prefer allow-lists.** **When unavoidable, block these minimum ranges:** | Service | Block IPs/Domains | |---------|-------------------| | **AWS IMDS** | `169.254.169.254`, `fd00:ec2::254` ([IPv6 endpoint]( | | **GCP Metadata** | `metadata.google.internal`, `169.254.169.254` | | **Azure IMDS** | `169.254.169.254` | | **Localhost** | `127.0.0.0/8`, `0.0.0.0/8`, `::1/128` | | **RFC1918 Private** | `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` | | **IPv4 Link-Local** | `169.254.0.0/16` ([RFC 3927]( which also covers the AWS credential endpoints for [ECS tasks]( (`169.254.170.2`) and [EKS Pod Identity]( (`169.254.170.23`) | | **IPv6 Unique Local** | `fc00::/7` ([R", "query_type": "nl"} +{"_id": "code_q_000589", "text": "Find a secure code implementation example satisfying this security guidance: When a `
    ` tag is used to submit data, it sends a [\"simple\" request]( that browsers do not designate as \"to be preflighted\". These \"simple\" requests introduce risk of CSRF because browsers permit them to be sent to any origin. If your application uses `` tags to submit data anywhere in your client, you will still need to protect them with alternate approaches described in this document such as tokens. > **Caveat:** Should a browser bug allow custom HTTP headers, or not enforce preflight on non-simple content types, it could compromise your security. Although unlikely, it is prudent to consider this in your threat model. Implementing CSRF tokens adds additional layer of defense and", "query_type": "nl"} +{"_id": "code_q_000590", "text": "Find a secure code implementation example satisfying this security guidance: Spring MVC #### Allow-listing See [Spring's model design guidance]( for dedicated input objects and allowed fields. #### Block-listing Spring describes `disallowedFields` as fragile because fields can be missed or added later. Prefer the allow-list above; this example only excludes the named property. See the [Spring data binding limitations]( ### NodeJS + Mongoose #### Allow-listing Take a look [here]( for the documentation. #### Block-listing Take a look [here]( for the documentation. ### Ruby On Rails Take a look [here]( for the documentation. ### Django Take a look [here]( for the documentation. ### ASP NET Take a look [here]( for the documentation. ### PHP Laravel + Eloquent #### Allow-", "query_type": "nl"} +{"_id": "code_q_000591", "text": "Find a secure code implementation example satisfying this security guidance: [DOM Clobbering]( is a type of code-reuse, HTML-only injection attack, where attackers confuse a web application by injecting HTML elements whose `id` or `name` attribute matches the name of security-sensitive variables or browser APIs, such as variables used for fetching remote content (e.g., script src), and overshadow their value. It is particularly relevant when script injection is not possible, e.g., when filtered by HTML sanitizers, or mitigated by disallowing or controlling script execution. In these scenarios, attackers may still inject non-script HTML markups into webpages and transform the initially secure markup into executable code, achieving [Cross-Site Scripting (XSS)]( **This ", "query_type": "nl"} +{"_id": "code_q_000593", "text": "Find a secure code implementation example satisfying this security guidance: Rate limiting is the foundational control. Apply it at multiple keys, not just IP. - **Per IP** — coarse, defeated by residential proxy networks but still useful as a floor. - **Per session / cookie** — defeated by cookie clearing, useful against unsophisticated bots. - **Per authenticated identity** — most reliable; applies after login. - **Per endpoint** — the login endpoint deserves a tighter limit than the home page. - **Per ASN or geo** — useful when traffic from datacenter ASNs is unexpected. Use a token-bucket or sliding-window algorithm. Avoid fixed-window counters: they allow bursts at boundary times. A correct login-endpoint rate limit applies **two independent buckets**, both of w", "query_type": "nl"} +{"_id": "code_q_000594", "text": "Find a secure code implementation example satisfying this security guidance: Authorization implementation is rarely static. As applications evolve, new API endpoints are added, data layers are refactored, and microservices are decoupled. While initial security testing might validate access controls at launch, the \"Day 2\" problem emerges quickly: **How do engineering teams ensure that new features or structural changes do not break existing authorization logic?** [Broken Access Control (BAC)]( was ranked the number-one risk in the OWASP Top Ten 2021, and [Insecure Direct Object Reference (IDOR)]( is one of its most frequently exploited sub-categories. This cheat sheet provides actionable, architectural guidance on implementing automated authorization regression testin", "query_type": "nl"} +{"_id": "code_q_000595", "text": "Find a secure code implementation example satisfying this security guidance: Docker is the most popular containerization technology. When used correctly, it can enhance security compared to running applications directly on the host system. However, certain misconfigurations can reduce security levels or introduce new vulnerabilities. The aim of this cheat sheet is to provide a straightforward list of common security errors and best practices to assist in securing your Docker containers.", "query_type": "nl"} +{"_id": "code_q_000598", "text": "Find a secure code implementation example satisfying this security guidance: Commonly discussed, overlapping categories of [XSS (Cross-Site Scripting)]( include: - [Reflected or Stored]( - [DOM Based XSS]( The [XSS Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension) of the [XSS Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md). Stored and reflected describe how an attack payload reaches a victim; server-side and client-side describe where untrusted data is handled unsafely. [Both stored and reflected XSS can occur on the client or server]( including stored ", "query_type": "nl"} +{"_id": "code_q_000599", "text": "Find a secure code implementation example satisfying this security guidance: - **NoSQL Injection** — Unsafe construction of query objects or query strings from untrusted input. - **Exposed Management Interfaces** — Admin GUIs, database ports or REST endpoints exposed to the internet. - **Weak/No Authentication & Authorization** — Default open access or excessive privileges for clients. - **Insecure Network Exposure** — No TLS, open ports, insufficient network segmentation. - **Insecure Defaults** — Default admin accounts, default passwords, unsecured configs. - **Poor Access Control Models** — Coarse roles allowing lateral abuse. - **Insecure Serialization / Deserialization** — Remote code execution via unsafe object deserialization. - **Misconfigured CORS / Public A", "query_type": "nl"} +{"_id": "code_q_000600", "text": "Find a secure code implementation example satisfying this security guidance: - [Pwned Passwords API]( - [OWASP Automated Threat Handbook](", "query_type": "nl"}