├── Authentication Bypass └── CVE-2019-1937 ├── Buffer Overflow ├── bof1.c ├── example1.c ├── example2.c ├── gets.c ├── netkit-telnet 0.17.c ├── sprintf.c └── strcpy.c ├── CVE-2015-8562.php ├── Code Execution └── Discourse_SNS_webhook_RCE.rb ├── Code Injection ├── eval.php ├── eval2.php └── example1.rb ├── Command Injection ├── CVE-2019-16662.php ├── CVE-2019-16663.php ├── Cryptolog.php ├── OSI.cs ├── cmd1.php ├── cmd2.php ├── cmd3.php ├── cmd4.php ├── cmd5.php ├── cmd6.php ├── exec.js └── tainted.py ├── Connection String Injection ├── example1.c ├── example2.java └── example3.asp ├── Denial Of Service ├── dos.js ├── example1.aspx.cs └── example2.c ├── File Inclusion ├── lfi1.php ├── lfi10.php ├── lfi11.php ├── lfi12.php ├── lfi13.php ├── lfi14.php ├── lfi2.php ├── lfi3.php ├── lfi4.php ├── lfi5.php ├── lfi6.php ├── lfi7.php ├── lfi8.php └── lfi9.php ├── Format String Attacks ├── FormatString.c └── vuln.c ├── IDOR └── example1.php ├── Insecure File Uploads ├── Insomnihack_2019_l33t-hoster.php ├── WishList.php ├── example1.php ├── example2.php └── example3.php ├── Integer Overflow └── damnvuln.c ├── LDAP Injection ├── LDAP.cs ├── example1.php └── example2.asp ├── Log Forging └── logf.cs ├── NoSQL Injection └── mongodb.js ├── Open Redirect ├── Remote Code Execution in apt-get ├── example1.php ├── example1.rb ├── koa.js └── redirect.js ├── Out of Bounds └── damnvuln.c ├── PHP Object Injection ├── chall1.php ├── chall2.php ├── tarlogic-ex1.php ├── tarlogic-ex2.php └── tarlogic1.php ├── Path Traversal ├── PT1.cs ├── PT2.cs ├── PT3.cs ├── PT4.cs ├── ZipTraversal.java ├── ZipTraversalPatched.java ├── bypass.php ├── example1.java ├── example2.php ├── example3.java ├── expresstest.js ├── gq.js ├── phpexample.php └── py_ctf.py ├── PostMessage Security ├── challenge1.js ├── challenge3.js └── challenge_2.js ├── Prototype Pollution └── lodash.js ├── README.md ├── ReDoS └── redos.js ├── Resource Injection └── example1.asp ├── SQL Injection ├── Cryptolog,php ├── SQLi.cs ├── blindsqli.php ├── example.java ├── example1.rb ├── example2.js ├── mysql.js ├── sql.js └── sqli.php ├── SSRF └── express.js ├── Sensitive Data Exposure ├── Railsgoatconfig.rb ├── graphql.ts └── hardcoded.ts ├── Server Side Template Injection ├── Twig.php ├── asis_ssti_pt.py ├── sstigolang.go └── test.py ├── Symlink Attack └── file.c ├── Unsafe Deserialization ├── CVE-2017-2809.py ├── de.js ├── java │ ├── LogFile.java │ └── SerializeToFile.java ├── pickle2.py ├── unsafe.js └── unserialize.php ├── Use After Free └── damnvuln.c ├── XPATH Injection └── xpath.cs ├── XSS ├── Cookie Security │ ├── sc.cs │ └── sc2.cs ├── Spring.java ├── XSS.cs ├── dom.php ├── example.php ├── example1.html └── express.js ├── XXE ├── XmlReader_Tests.cs ├── test.php ├── test2.php ├── xxe.js └── xxe1.cs └── Zip Traversal └── myApp.cs /Authentication Bypass/CVE-2019-1937: -------------------------------------------------------------------------------- 1 | 2 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { 3 | (...) 4 | httpRequest = (HttpServletRequest)request; 5 | logger.debug("doFilter url: " + httpRequest.getRequestURL().toString()); 6 | boolean isAuthenticated = this.authenticateUser(httpRequest); 7 | ^^^ 1.5) invokes authenticateUser() (function shown below) 8 | 9 | String samlLogoutRequest; 10 | if(!isAuthenticated) { 11 | ^^^ 1.6) if authenticateUser() returns false, we go into this branch 12 | 13 | samlLogoutRequest = request.getParameter("SAMLResponse"); 14 | logger.info("samlResponse-->" + samlLogoutRequest); 15 | if(samlLogoutRequest != null) { 16 | this.handleSAMLReponse(request, response, chain, samlLogoutRequest); 17 | } else { 18 | ^^^ 1.7) if there is no SAMLResponse HTTP parameter, we go into this branch 19 | 20 | HttpSession session; 21 | ProductAccess userBean; 22 | String requestedUri; 23 | if(this.isStarshipRequest(httpRequest)) { 24 | ^^^ 1.8) checks if isStarshipRequest() returns true (function shown below) 25 | 26 | session = null != httpRequest.getSession(false)?httpRequest.getSession(false):httpRequest.getSession(true); 27 | userBean = (ProductAccess)session.getAttribute("USER_IN_SESSION"); 28 | if(userBean == null) { 29 | ^^^ 1.9) if there is no session server side for this request, follow into this branch... 30 | 31 | try { 32 | userBean = new ProductAccess(); 33 | userBean.setCredentialId(""); 34 | userBean.setAdminPasswordReset(true); 35 | userBean.setProductId("cloupia_service_portal"); 36 | userBean.setProfileId(0); 37 | userBean.setRestKey(httpRequest.getHeader("X-Starship-Request-Key")); 38 | userBean.setStarshipUserId(httpRequest.getHeader("X-Starship-UserName-Key")); 39 | userBean.setLoginName("admin"); 40 | ^^^ 1.10) and create a new session with the user as "admin"! 41 | 42 | userBean.setStarshipSessionId(httpRequest.getHeader("X-Starship-UserSession-Key")); 43 | requestedUri = httpRequest.getHeader("X-Starship-UserRoles-Key"); 44 | userBean.setAccessLevel(requestedUri); 45 | if(requestedUri != null && requestedUri.equalsIgnoreCase("admin")) { 46 | AuthenticationManager authmgr = AuthenticationManager.getInstance(); 47 | userBean.setAccessLevel("Admin"); 48 | authmgr.evaluateAllowedOperations(userBean); 49 | } 50 | 51 | session.setAttribute("USER_IN_SESSION", userBean); 52 | session.setAttribute("DEFAULT_URL", STARSHIP_DEFAULT_URL); 53 | logger.info("userBean:" + userBean.getAccessLevel()); 54 | } catch (Exception var12) { 55 | logger.info("username/password wrong for rest api access - " + var12.getMessage()); 56 | } 57 | 58 | logger.info("userBean: " + userBean.getAccessLevel()); 59 | } 60 | 61 | chain.doFilter(request, response); 62 | -------------------------------------------------------------------------------- /Buffer Overflow/bof1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define S 100 5 | #define N 1000 6 | 7 | int main(int argc, char *argv[]) { 8 | char out[S]; 9 | char buf[N]; 10 | char msg[] = "Welcome to the argument echoing program\n"; 11 | int len = 0; 12 | buf[0] = '\0'; 13 | printf(msg); 14 | while (argc) { 15 | sprintf(out, "argument %d is %s\n", argc-1, argv[argc-1]); 16 | argc--; 17 | strncat(buf,out,sizeof(buf)-len-1); 18 | len = strlen(buf); 19 | } 20 | printf("%s",buf); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Buffer Overflow/example1.c: -------------------------------------------------------------------------------- 1 | int _tmain(int argc, _TCHAR* argv[]) 2 | { 3 | char name[64]; 4 | printf("Enter your name: "); 5 | scanf("%s", name); 6 | Sanitize(name); 7 | printf("Welcome, %s!", name); 8 | return 0; 9 | } } 10 | -------------------------------------------------------------------------------- /Buffer Overflow/example2.c: -------------------------------------------------------------------------------- 1 | int _tmain(int argc, _TCHAR* argv[]) 2 | { 3 | char name[64]; 4 | printf("Enter your name: "); 5 | scanf("%s", name); 6 | Sanitize(name); 7 | printf("Welcome, %s!", name); 8 | return 0; 9 | } } 10 | -------------------------------------------------------------------------------- /Buffer Overflow/gets.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main () { 3 | char username[8]; 4 | int allow = 0; 5 | printf external link("Enter your username, please: "); 6 | gets(username); // user inputs "malicious" 7 | if (grantAccess(username)) { 8 | allow = 1; 9 | } 10 | if (allow != 0) { // has been overwritten by the overflow of the username. 11 | privilegedAction(); 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Buffer Overflow/netkit-telnet 0.17.c: -------------------------------------------------------------------------------- 1 | /* 2 | netkit-telnet 0.17 BUFFER OVERFLOW 3 | telnet stack smashing bug, in a completely unrelated part of DISPLAY= handling to the last one... from netkit-telnet 0.17 - when passing unix:arg or ":arg" in DISPLAY the argument is strcat() onto a fixed stack 256 byte buffer 4 | 5 | 6 | */ 7 | 8 | 9 | static void env_fix_display(void) { 10 | enviro *ep = env_find("DISPLAY"); 11 | if (!ep) return; 12 | ep->setexport(1); 13 | if (strncmp(ep->getval(), ":", 1) && strncmp(ep->getval(), "UNIX", 5)) { 14 | return; 15 | } 16 | char hbuf{256]; 17 | const char *cp2 = strrchr(ep->getval(), ':'); 18 | int maxlen = sizeof(hbuf)-strlen(cp2)-1; 19 | gethostname(hbuf, maxlen); 20 | hbuf[maxlen] = 0; 21 | if (!strehr(hbuf, '.')) { 22 | struct hostent *h = gethostbyname(hbuf); 23 | if (h) {} 24 | strncpy(hbuf, h->h_name, maxlen); 25 | hbuf(maxlen] = 0; 26 | } 27 | } 28 | strcat(hbuf, cp2); 29 | ep->define("DISPLAY", hbuf); 30 | } 31 | -------------------------------------------------------------------------------- /Buffer Overflow/sprintf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | enum { BUFFER_SIZE = 10 }; 5 | 6 | int main() { 7 | char buffer[BUFFER_SIZE]; 8 | int check = 0; 9 | 10 | sprintf(buffer, "%s", "This string is too long!"); 11 | 12 | printf external link("check: %d", check); /* This will not print 0! */ 13 | 14 | return EXIT_SUCCESS; 15 | } 16 | -------------------------------------------------------------------------------- /Buffer Overflow/strcpy.c: -------------------------------------------------------------------------------- 1 | char str1[10]; 2 | char str2[]="abcdefghijklmn"; 3 | strcpy(str1,str2); 4 | -------------------------------------------------------------------------------- /CVE-2015-8562.php: -------------------------------------------------------------------------------- 1 | // https://voidsec.com/analysis-of-the-joomla-rce-cve-2015-8562/ 2 | 3 | 4 | 5 | // Check for clients browser 6 | if (in_array('fix_browser', $this->security) && isset($_SERVER['HTTP_USER_AGENT'])){ 7 | $browser = $this->get('session.client.browser'); 8 | 9 | if ($browser === null){ 10 | $this->set('session.client.browser', $_SERVER['HTTP_USER_AGENT']); 11 | } 12 | elseif ($_SERVER['HTTP_USER_AGENT'] !== $browser) { 13 | // @todo remove code: $this->_state = 'error'; 14 | // @todo remove code: return false; 15 | } 16 | } 17 | 18 | joomla_session` VALUES ('02di8ph9l9on7aa905khshtu57',0,1,'1505489800', 19 | '__default|a:8:{ 20 | s:15:"session.counter"; i:1; 21 | s:19:"session.timer.start"; i:1505489800; 22 | s:18:"session.timer.last"; i:1505489800; 23 | s:17:"session.timer.now"; i:1505489800; 24 | s:22:"session.client.browser"; s:11:"curl/7.55.1"; 25 | s:8:"registry"; 26 | O:9:"JRegistry":1:{ 27 | s:7:"\0\0\0data"; 28 | O:8:"stdClass":0:{} 29 | } 30 | s:4:"user";O:5:"JUser":24:{ 31 | s:9:"\0\0\0isRoot"; b:0; 32 | s:2:"id"; i:0; 33 | s:4:"name"; N; 34 | s:8:"username"; N; 35 | s:5:"email"; N; 36 | s:8:"password"; N; 37 | s:14:"password_clear"; s:0:""; 38 | s:5:"block"; N; 39 | s:9:"sendEmail"; i:0; 40 | s:12:"registerDate"; N; 41 | s:13:"lastvisitDate"; N; 42 | s:10:"activation"; N; 43 | s:6:"params"; N; 44 | s:6:"groups"; 45 | a:1:{ 46 | i:0; 47 | s:2:"13"; 48 | } 49 | s:5:"guest"; i:1; 50 | s:13:"lastResetTime"; N; 51 | s:10:"resetCount"; N; 52 | s:10:"\0\0\0_params"; 53 | O:9:"JRegistry":1:{ 54 | s:7:"\0\0\0data"; 55 | O:8:"stdClass":0:{} 56 | } 57 | s:14:"\0\0\0_authGroups"; 58 | a:1:{ 59 | i:0; 60 | s:1:"1"; 61 | } 62 | s:14:"\0\0\0_authLevels"; 63 | a:2:{ 64 | i:0; 65 | i:1; 66 | i:1; 67 | i:1; 68 | } 69 | s:15:"\0\0\0_authActions"; N; 70 | s:12:"\0\0\0_errorMsg"; N; 71 | s:10:"\0\0\0_errors"; a:0:{} 72 | s:3:"aid"; i:0; 73 | } 74 | s:13:"session.token"; s:32:"ead9d16586b72de83eab1761e20436e4"; 75 | }' 76 | ,0,''); 77 | 78 | 79 | 80 | public function write($id, $data) 81 | { 82 | // Get the database connection object and verify its connected. 83 | $db = JFactory::getDbo(); 84 | $data = str_replace(chr(0) . '*' . chr(0), '\0\0\0', $data); 85 | try { 86 | $query = $db->getQuery(true) 87 | ->update($db->quoteName('#__session')) 88 | ->set($db->quoteName('data') . ' = ' . $db->quote($data)) 89 | ->set($db->quoteName('time') . ' = ' . $db->quote((int) time())) 90 | ->where($db->quoteName('session_id') . ' = ' . $db->quote($id)); 91 | 92 | // Try to update the session data in the database table. 93 | $db->setQuery($query); 94 | 95 | if (!$db->;execute()) { 96 | return false; 97 | } 98 | /* Since $db->execute did not throw an exception, so the query was successful. 99 | Either the data changed, or the data was identical. 100 | In either case we are done. 101 | */ 102 | return true; 103 | } 104 | catch (Exception $e) { 105 | return false; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Code Execution/Discourse_SNS_webhook_RCE.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # https://0day.click/recipe/discourse-sns-rce/ 3 | 4 | module Jobs 5 | 6 | class ConfirmSnsSubscription < ::Jobs::Base 7 | sidekiq_options retry: false 8 | 9 | def execute(args) 10 | return unless raw = args[:raw].presence 11 | return unless json = args[:json].presence 12 | return unless subscribe_url = json["SubscribeURL"].presence 13 | 14 | require "aws-sdk-sns" 15 | return unless Aws::SNS::MessageVerifier.new.authentic?(raw) 16 | 17 | # confirm subscription by visiting the URL 18 | open(subscribe_url) 19 | end 20 | 21 | end 22 | 23 | end 24 | -------------------------------------------------------------------------------- /Code Injection/eval.php: -------------------------------------------------------------------------------- 1 | 0 ? $_GET['variable'] : 'empty'; 7 | $empty = 'No variable given'; 8 | 9 | // pass the variable name into an eval block, making it 10 | // vulnerable to Remote Code Execution (rce). This RCE 11 | // is NOT blind. 12 | eval('echo $' . $variable . ';'); 13 | -------------------------------------------------------------------------------- /Code Injection/eval2.php: -------------------------------------------------------------------------------- 1 | 2 | request->get("code"); 26 | eval($code); 27 | 28 | 29 | ?> 30 | -------------------------------------------------------------------------------- /Code Injection/example1.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | puts "Calculating" 3 | first_number = ARGV[0]#.to_i 4 | second_number = ARGV[1]#.to_i 5 | print "Args:",first_number,second_number," 6 | " 7 | print eval(first_number+"+"+second_number) 8 | -------------------------------------------------------------------------------- /Command Injection/CVE-2019-16662.php: -------------------------------------------------------------------------------- 1 | Fail - php safe mode is on - turn it off before you proceed with the installationbr/>'; 7 | } else { 8 | $array['phpSafeMode'] = 'Pass - php safe mode is off
'; 9 | } 10 | /* Test root account details */ 11 | $rootTestCmd1 = 'sudo -S -u ' . $rootUname . ' chmod 0777 /home 2>&1'; 12 | exec($rootTestCmd1, $cmdOutput, $err); 13 | $homeDirPerms = substr(sprintf('%o', fileperms('/home')), -4); 14 | if ($homeDirPerms == '0777') { 15 | $array['rootDetails'] = 'Pass - root account details are good
'; 16 | } else { 17 | $array['rootDetails'] = 'The root details provided have not passed: ' . $cmdOutput[0] . '
'; 18 | } 19 | // reset /home dir permissions 20 | $rootTestCmd2 = 'sudo -S -u ' . $rootUname . ' chmod 0755 /home 2>&1'; 21 | exec($rootTestCmd2, $cmdOutput, $err); 22 | echo json_encode($array); 23 | -------------------------------------------------------------------------------- /Command Injection/CVE-2019-16663.php: -------------------------------------------------------------------------------- 1 | logged_in) { 9 | echo 'Don\'t bother trying to hack me!!!!!
This hack attempt has been logged'; 10 | $log->Warn("Security Issue: Some tried to access this file directly from IP: " . $_SERVER['REMOTE_ADDR'] . " & Username: " . $session->username . " (File: " . $_SERVER['PHP_SELF'] . ")"); 11 | // need to add authentication to this script 12 | header("Location: " . $config_basedir . "login.php"); 13 | } else { 14 | 15 | require_once("../../../classes/db2.class.php"); 16 | 17 | $db2 = new db2(); 18 | $log = ADLog::getInstance(); 19 | 20 | // simple script runtime check 21 | $Start = getTime(); 22 | 23 | $errors = array(); 24 | 25 | if (isset($_GET['searchTerm']) && is_string($_GET['searchTerm']) && !empty($_GET['searchTerm'])) { 26 | /* validation */ 27 | $searchTerm = '"' . $_GET['searchTerm'] . '"'; 28 | $catId = $_GET['catId']; 29 | $catCommand = $_GET['catCommand']; 30 | $nodeId = $_GET['nodeId']; 31 | $grepNumLineStr = $_GET['numLinesStr']; 32 | $grepNumLine = $_GET['noLines']; 33 | $username = $_SESSION['username']; 34 | 35 | // if nodeId was empty set it to blank 36 | if (empty($nodeId)) { 37 | $nodeId = ''; 38 | } else { 39 | $nodeId = '/' . $nodeId . '/'; 40 | } 41 | 42 | $returnArr = array(); 43 | 44 | // Get the category Name from the Category selected 45 | $db2->query("SELECT categoryName from `categories` WHERE id = :catId"); 46 | $db2->bind(':catId', $catId); 47 | $resultCat = $db2->resultset(); 48 | $returnArr['category'] = $resultCat[0]['categoryName']; 49 | 50 | // get total file count 51 | $fileCount = array(); 52 | $subDir = ""; 53 | if (!empty($returnArr['category'])) { 54 | $subDir = "/" . $returnArr['category']; 55 | } 56 | 57 | exec("find /home/rconfig/data" . $subDir . $nodeId . " -maxdepth 10 -type f | wc -l", $fileCountArr); 58 | $returnArr['fileCount'] = $fileCountArr['0']; 59 | 60 | //next find all instances of the search term under the specific cat/dir 61 | $command = 'find /home/rconfig/data' . $subDir . $nodeId . ' -name ' . $catCommand . ' | xargs grep -il ' . $grepNumLineStr . ' ' . $searchTerm . ' | while read file ; do echo File:"$file"; grep ' . $grepNumLineStr . ' ' . $searchTerm . ' "$file" ; done'; 62 | // echo $command;die(); 63 | exec($command, $searchArr); 64 | -------------------------------------------------------------------------------- /Command Injection/Cryptolog.php: -------------------------------------------------------------------------------- 1 | 40 | -------------------------------------------------------------------------------- /Command Injection/OSI.cs: -------------------------------------------------------------------------------- 1 | 2 | using Microsoft.AspNetCore.Mvc; 3 | using System; 4 | using System.Diagnostics; 5 | 6 | namespace WebFox.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class OsInjection : ControllerBase 11 | { 12 | [HttpGet("{binFile}")] 13 | public string os(string binFile) 14 | { 15 | Process p = new Process(); 16 | p.StartInfo.FileName = binFile; // Noncompliant 17 | p.StartInfo.RedirectStandardOutput = true; 18 | p.Start(); 19 | string output = p.StandardOutput.ReadToEnd(); 20 | p.Dispose(); 21 | return output; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Command Injection/cmd1.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 |
9 | 10 |
11 | 12 | -------------------------------------------------------------------------------- /Command Injection/cmd2.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 |
8 | 9 | -------------------------------------------------------------------------------- /Command Injection/cmd3.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 |
9 | Whois: 10 |
11 | 12 |
13 | 
16 | 
-------------------------------------------------------------------------------- /Command Injection/cmd4.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 |
8 | 9 |
10 | 
13 | 
-------------------------------------------------------------------------------- /Command Injection/cmd5.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 |
9 | 10 |
11 | 
18 | 
-------------------------------------------------------------------------------- /Command Injection/cmd6.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 |
9 | 10 |
11 | 
18 | 
-------------------------------------------------------------------------------- /Command Injection/exec.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | 4 | const { exec, spawn } = require('child_process'); 5 | 6 | 7 | router.post('/ping', (req,res) => { 8 | exec(`${req.body.url}`, (error) => { 9 | if (error) { 10 | return res.send('error'); 11 | } 12 | res.send('pong') 13 | }) 14 | 15 | }) 16 | 17 | router.post('/gzip', (req,res) => { 18 | exec( 19 | 'gzip ' + req.query.file_path, 20 | function (err, data) { 21 | console.log('err: ', err) 22 | console.log('data: ', data); 23 | res.send('done'); 24 | }); 25 | }) 26 | 27 | router.get('/run', (req,res) => { 28 | let cmd = req.params.cmd; 29 | runMe(cmd,res) 30 | }); 31 | 32 | function runMe(cmd,res){ 33 | // return spawn(cmd); 34 | 35 | const cmdRunning = spawn(cmd, []); 36 | cmdRunning.on('close', (code) => { 37 | res.send(`child process exited with code ${code}`); 38 | }); 39 | } 40 | 41 | module.exports = router 42 | -------------------------------------------------------------------------------- /Command Injection/tainted.py: -------------------------------------------------------------------------------- 1 | import os 2 | from flask import Flask, request 3 | app = Flask(__name__) 4 | 5 | # curl -X GET "http://localhost:5000/tainted7/touch%20HELLO" 6 | @app.route("/tainted7/") 7 | def test_sources_7(something): 8 | 9 | os.system(request.remote_addr) 10 | 11 | return "foo" 12 | 13 | if __name__ == "__main__": 14 | app.run(debug=True) 15 | -------------------------------------------------------------------------------- /Connection String Injection/example1.c: -------------------------------------------------------------------------------- 1 | int main(int argc, char *argv[]) 2 | { 3 | rc = SQLConnect(Example.ConHandle, argv[0], SQL_NTS, 4 | (SQLCHAR *) "", SQL_NTS, (SQLCHAR *) "", SQL_NTS); 5 | } 6 | -------------------------------------------------------------------------------- /Connection String Injection/example2.java: -------------------------------------------------------------------------------- 1 | try 2 | { 3 | Class.forName("com.mysql.jdbc.Driver").newInstance(); 4 | String url = "jdbc:mysql://10.12.1.34/" + request.getParameter("selectedDB"); 5 | conn = DriverManager.getConnection(url, username, password); 6 | doUnitWork(); 7 | } 8 | catch(ClassNotFoundException cnfe) 9 | { 10 | // 11 | } 12 | catch(SQLException se) 13 | { 14 | // 15 | } 16 | catch(InstantiationException ie) 17 | { 18 | // 19 | } 20 | finally 21 | { 22 | // manage conn 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Connection String Injection/example3.asp: -------------------------------------------------------------------------------- 1 | string userID = userModel.username; 2 | string passwd = userModel.password; 3 | 4 | // connect DB with the authenticated user provided credentials 5 | // valid connection also implies succesfull authentication 6 | SqlConnection DBconn = new SqlConnection("Data Source= tcp:10.10.2.1,1434;Initial Catalog=mydb;User ID=" + userID +";Password=" + passwd); 7 | -------------------------------------------------------------------------------- /Denial Of Service/dos.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | 4 | 5 | router.post("/list-users", (req, res) => { 6 | var obj = req.body.users; 7 | var someArr = []; 8 | 9 | // Potential DoS if obj.length is large. 10 | for (var i = 0; i < obj.length; i++) { 11 | someArr.push(obj[i]); 12 | } 13 | 14 | //doing something with the code 15 | res.send(someArr.join(',')); 16 | }); 17 | 18 | 19 | module.exports = router 20 | -------------------------------------------------------------------------------- /Denial Of Service/example1.aspx.cs: -------------------------------------------------------------------------------- 1 | Private Sub cmdRunNotePad_Click() 2 | Dim str As String 3 | MyVar = window.Text() 4 | Sleep myVar+1 5 | dblNotePadID = Sleep(myVar) 6 | End Sub 7 | -------------------------------------------------------------------------------- /Denial Of Service/example2.c: -------------------------------------------------------------------------------- 1 | int i; 2 | char inLine[64]; 3 | cin >> inLine; 4 | i = atoi (inLine); 5 | sleep(i); 6 | -------------------------------------------------------------------------------- /File Inclusion/lfi1.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 13 | -------------------------------------------------------------------------------- /File Inclusion/lfi10.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 21 | -------------------------------------------------------------------------------- /File Inclusion/lfi11.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /File Inclusion/lfi12.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /File Inclusion/lfi13.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 21 | -------------------------------------------------------------------------------- /File Inclusion/lfi14.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 22 | -------------------------------------------------------------------------------- /File Inclusion/lfi2.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 13 | 14 | -------------------------------------------------------------------------------- /File Inclusion/lfi3.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 12 | 18 | 19 | -------------------------------------------------------------------------------- /File Inclusion/lfi4.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 14 | 15 | -------------------------------------------------------------------------------- /File Inclusion/lfi5.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 22 | -------------------------------------------------------------------------------- /File Inclusion/lfi6.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 |
11 | 12 | 15 | -------------------------------------------------------------------------------- /File Inclusion/lfi7.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 |
11 | 12 | 15 | 16 | -------------------------------------------------------------------------------- /File Inclusion/lfi8.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 11 | 17 | 18 | -------------------------------------------------------------------------------- /File Inclusion/lfi9.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 14 | 15 | -------------------------------------------------------------------------------- /Format String Attacks/FormatString.c: -------------------------------------------------------------------------------- 1 | #FormatString.c 2 | #include 3 | 4 | int main(int argc, char **argv) { 5 | char *secret = "This is a secret!\n"; 6 | 7 | printf external link(argv[1]); 8 | 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /Format String Attacks/vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define FLAG_BUFFER 128 7 | #define MAX_SYM_LEN 4 8 | 9 | typedef struct Stonks { 10 | int shares; 11 | char symbol[MAX_SYM_LEN + 1]; 12 | struct Stonks *next; 13 | } Stonk; 14 | 15 | typedef struct Portfolios { 16 | int money; 17 | Stonk *head; 18 | } Portfolio; 19 | 20 | int view_portfolio(Portfolio *p) { 21 | if (!p) { 22 | return 1; 23 | } 24 | printf("\nPortfolio as of "); 25 | fflush(stdout); 26 | system("date"); // TODO: implement this in C 27 | fflush(stdout); 28 | 29 | printf("\n\n"); 30 | Stonk *head = p->head; 31 | if (!head) { 32 | printf("You don't own any stonks!\n"); 33 | } 34 | while (head) { 35 | printf("%d shares of %s\n", head->shares, head->symbol); 36 | head = head->next; 37 | } 38 | return 0; 39 | } 40 | 41 | Stonk *pick_symbol_with_AI(int shares) { 42 | if (shares < 1) { 43 | return NULL; 44 | } 45 | Stonk *stonk = malloc(sizeof(Stonk)); 46 | stonk->shares = shares; 47 | 48 | int AI_symbol_len = (rand() % MAX_SYM_LEN) + 1; 49 | for (int i = 0; i <= MAX_SYM_LEN; i++) { 50 | if (i < AI_symbol_len) { 51 | stonk->symbol[i] = 'A' + (rand() % 26); 52 | } else { 53 | stonk->symbol[i] = '\0'; 54 | } 55 | } 56 | 57 | stonk->next = NULL; 58 | 59 | return stonk; 60 | } 61 | 62 | int buy_stonks(Portfolio *p) { 63 | if (!p) { 64 | return 1; 65 | } 66 | char api_buf[FLAG_BUFFER]; 67 | FILE *f = fopen("api","r"); 68 | if (!f) { 69 | printf("Flag file not found. Contact an admin.\n"); 70 | exit(1); 71 | } 72 | fgets(api_buf, FLAG_BUFFER, f); 73 | 74 | int money = p->money; 75 | int shares = 0; 76 | Stonk *temp = NULL; 77 | printf("Using patented AI algorithms to buy stonks\n"); 78 | while (money > 0) { 79 | shares = (rand() % money) + 1; 80 | temp = pick_symbol_with_AI(shares); 81 | temp->next = p->head; 82 | p->head = temp; 83 | money -= shares; 84 | } 85 | printf("Stonks chosen\n"); 86 | 87 | // TODO: Figure out how to read token from file, for now just ask 88 | 89 | char *user_buf = malloc(300 + 1); 90 | printf("What is your API token?\n"); 91 | scanf("%300s", user_buf); 92 | printf("Buying stonks with token:\n"); 93 | printf(user_buf); 94 | 95 | // TODO: Actually use key to interact with API 96 | 97 | view_portfolio(p); 98 | 99 | return 0; 100 | } 101 | 102 | Portfolio *initialize_portfolio() { 103 | Portfolio *p = malloc(sizeof(Portfolio)); 104 | p->money = (rand() % 2018) + 1; 105 | p->head = NULL; 106 | return p; 107 | } 108 | 109 | void free_portfolio(Portfolio *p) { 110 | Stonk *current = p->head; 111 | Stonk *next = NULL; 112 | while (current) { 113 | next = current->next; 114 | free(current); 115 | current = next; 116 | } 117 | free(p); 118 | } 119 | 120 | int main(int argc, char *argv[]) 121 | { 122 | setbuf(stdout, NULL); 123 | srand(time(NULL)); 124 | Portfolio *p = initialize_portfolio(); 125 | if (!p) { 126 | printf("Memory failure\n"); 127 | exit(1); 128 | } 129 | 130 | int resp = 0; 131 | 132 | printf("Welcome back to the trading app!\n\n"); 133 | printf("What would you like to do?\n"); 134 | printf("1) Buy some stonks!\n"); 135 | printf("2) View my portfolio\n"); 136 | scanf("%d", &resp); 137 | 138 | if (resp == 1) { 139 | buy_stonks(p); 140 | } else if (resp == 2) { 141 | view_portfolio(p); 142 | } 143 | 144 | free_portfolio(p); 145 | printf("Goodbye!\n"); 146 | 147 | exit(0); 148 | } 149 | -------------------------------------------------------------------------------- /IDOR/example1.php: -------------------------------------------------------------------------------- 1 | 0) { 11 | // view a particular secret 12 | // 13 | // As can be seen in the code, the overview page only selects rows 14 | // from the secrets table WHERE user_id = 1. However, the query 15 | // below does not have a similar clause OR any kind of authorization 16 | // check to make sure that the user is authorized to see secret. 17 | // This means any ID can be passed in the ?id= parameter and be 18 | // used to read any secret from the table. 19 | $query = $db->query('select * from secrets where id = ' . (int)$id); 20 | 21 | while ($row = $query->fetchArray()) { 22 | echo 'Secret: ' . $row['secret']; 23 | } 24 | 25 | echo '

Go back'; 26 | } else { 27 | // view all the user's secrets (WHERE user_id = 1) 28 | $query = $db->query('select * from secrets where user_id = 1'); 29 | 30 | echo 'Your secrets

'; 31 | 32 | while ($row = $query->fetchArray()) { 33 | echo '#' . $row['id'] . '
'; 34 | } 35 | -------------------------------------------------------------------------------- /Insecure File Uploads/Insomnihack_2019_l33t-hoster.php: -------------------------------------------------------------------------------- 1 | Your files:
    "; 70 | foreach(glob($userdir . "*") as $file) { 71 | echo "
  • $file
  • "; 72 | } 73 | echo "
"; 74 | 75 | ?> 76 | 77 |

Upload your pics!

78 |
79 | 80 | 81 |
82 | 83 | -------------------------------------------------------------------------------- /Insecure File Uploads/WishList.php: -------------------------------------------------------------------------------- 1 | class Challenge { 2 | const UPLOAD_DIRECTORY = './solutions/'; 3 | private $file; 4 | private $whitelist; 5 | 6 | public function __construct($file) { 7 | $this->file = $file; 8 | $this->whitelist = range(1, 24); 9 | } 10 | 11 | public function __destruct() { 12 | if (in_array($this->file['name'], $this->whitelist)) { 13 | move_uploaded_file( 14 | $this->file['tmp_name'], 15 | self::UPLOAD_DIRECTORY . $this->file['name'] 16 | ); 17 | } 18 | } 19 | } 20 | 21 | $challenge = new Challenge($_FILES['solution']); 22 | -------------------------------------------------------------------------------- /Insecure File Uploads/example1.php: -------------------------------------------------------------------------------- 1 | Your image was not uploaded.'; 12 | } 13 | else { 14 | // Yes! 15 | $html .= "
{$target_path} succesfully uploaded!
"; 16 | } 17 | } 18 | 19 | ?> 20 | -------------------------------------------------------------------------------- /Insecure File Uploads/example2.php: -------------------------------------------------------------------------------- 1 | 2 | // Is it an image? 3 | if( ( $uploaded_type == "image/jpeg" || $uploaded_type == "image/png" ) && 4 | ( $uploaded_size < 100000 ) ) { 5 | 6 | // Can we move the file to the upload folder? 7 | if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) { 8 | // No 9 | $html .= '
Your image was not uploaded.
'; 10 | } 11 | else { 12 | // Yes! 13 | $html .= "
{$target_path} succesfully uploaded!
"; 14 | } 15 | } 16 | else { 17 | // Invalid file 18 | $html .= '
Your image was not uploaded. We can only accept JPEG or PNG images.
'; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Insecure File Uploads/example3.php: -------------------------------------------------------------------------------- 1 | $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ]; 2 | $uploaded_ext = substr( $uploaded_name, strrpos( $uploaded_name, '.' ) + 1); 3 | $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ]; 4 | $uploaded_tmp = $_FILES[ 'uploaded' ][ 'tmp_name' ]; 5 | 6 | // Is it an image? 7 | if( ( strtolower( $uploaded_ext ) == "jpg" || strtolower( $uploaded_ext ) == "jpeg" || strtolower( $uploaded_ext ) == "png" ) && 8 | ( $uploaded_size < 100000 ) && 9 | getimagesize( $uploaded_tmp ) ) { 10 | 11 | // Can we move the file to the upload folder? 12 | if( !move_uploaded_file( $uploaded_tmp, $target_path ) ) { 13 | // No 14 | $html .= '
Your image was not uploaded.
'; 15 | } 16 | else { 17 | // Yes! 18 | $html .= "
{$target_path} succesfully uploaded!
"; 19 | } 20 | } 21 | else { 22 | // Invalid file 23 | $html .= '
Your image was not uploaded. We can only accept JPEG or PNG images.
' 24 | -------------------------------------------------------------------------------- /Integer Overflow/damnvuln.c: -------------------------------------------------------------------------------- 1 | //https://github.com/hardik05/Damn_Vulnerable_C_Program/blob/master/imgRead.c 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | struct Image 8 | { 9 | char header[4]; 10 | int width; 11 | int height; 12 | char data[10]; 13 | }; 14 | 15 | int ProcessImage(char* filename){ 16 | 17 | FILE *fp; 18 | char ch; 19 | struct Image img; 20 | 21 | fp = fopen(filename,"r"); 22 | 23 | if(fp == NULL) 24 | { 25 | printf("\nCan't open file or file doesn't exist."); 26 | exit(0); 27 | } 28 | 29 | printf("\n\tHeader\twidth\theight\tdata\t\r\n"); 30 | 31 | while(fread(&img,sizeof(img),1,fp)>0){ 32 | printf("\n\t%s\t%d\t%d\t%s\r\n",img.header,img.width,img.height,img.data); 33 | 34 | int size1 = img.width + img.height; //Vulnerability: integer overflow 35 | char* buff1=(char*)malloc(size1); 36 | 37 | memcpy(buff1,img.data,sizeof(img.data)); //Vulnerability: no data buffer size/malloc success check? 38 | free(buff1); 39 | 40 | if (size1/2==0){ 41 | free(buff1); //Vulnerability: double free 42 | } 43 | else{ 44 | if(size1 == 123456){ 45 | buff1[0]='a'; //Vulnerability: use after free 46 | } 47 | } 48 | 49 | int size2 = img.width - img.height+100; //Vulnerability: integer underflow 50 | //printf("Size1:%d",size1); 51 | char* buff2=(char*)malloc(size2); 52 | 53 | memcpy(buff2,img.data,sizeof(img.data)); 54 | 55 | int size3= img.width/img.height; 56 | //printf("Size2:%d",size3); 57 | 58 | char buff3[10]; 59 | char* buff4 =(char*)malloc(size3); 60 | memcpy(buff4,img.data,sizeof(img.data)); 61 | 62 | char OOBR_stack = buff3[size3+100]; //Vulnerability: out of bound read (stack) 63 | char OOBR_heap = buff4[100]; 64 | 65 | buff3[size3+100]='c'; //Vulnerability: out of bound write (Stack) 66 | buff4[100]='c'; //Vulnerability: out of bound write (Heap) 67 | 68 | if(size3>10){ 69 | buff4=0; //memory leak? 70 | } 71 | else{ 72 | free(buff4); 73 | } 74 | 75 | free(buff2); 76 | } 77 | fclose(fp); 78 | } 79 | 80 | int main(int argc,char **argv) 81 | { 82 | ProcessImage(argv[1]); 83 | } 84 | -------------------------------------------------------------------------------- /LDAP Injection/LDAP.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.DirectoryServices; 8 | 9 | namespace WebFox.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class LDAP : ControllerBase 14 | { 15 | [HttpGet("{user}")] 16 | public void LdapInje(string user) 17 | { 18 | DirectoryEntry de = new DirectoryEntry("LDAP://DC=mycompany,DC=com"); 19 | DirectorySearcher searcher = new DirectorySearcher(de); 20 | searcher.Filter = "(&(objectClass=user)(|(cn=" + user + ")(sAMAccountName=" + user + ")))"; //When I'm concatenating the user name, here I got the security flag which is below. 21 | 22 | SearchResult result = searcher.FindOne(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /LDAP Injection/example1.php: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /LDAP Injection/example2.asp: -------------------------------------------------------------------------------- 1 | Const LDAP_SERVER = "ldap.example" 2 | userName = Request.QueryString("user") 3 | if( userName = "" ) then 4 | Response.Write("Invalid request. Please specify a valid user name") 5 | Response.End() 6 | end if 7 | filter = "(uid=" + CStr(userName) + ")" ' searching for the user entry 8 | Set ldapObj = Server.CreateObject("IPWorksASP.LDAP") 9 | ldapObj.ServerName = LDAP_SERVER 10 | ldapObj.DN = "ou=people,dc=spilab,dc=com" 11 | 'Setting the search filter 12 | ldapObj.SearchFilter = filter 13 | ldapObj.Search 14 | While ldapObj.NextResult = 1 15 | Response.Write("

") 16 | Response.Write("User information for: " + 17 | ldapObj.AttrValue(0) + "
") 18 | For i = 0 To ldapObj.AttrCount -1 19 | Response.Write("" + ldapObj.AttrType(i) +": " + 20 | ldapObj.AttrValue(i) + "
" ) 21 | Next 22 | Response.Write("

") 23 | Wend 24 | Response.Write("" + ldapObj.AttrType(i) +": " + 25 | ldapObj.AttrValue(i) + "
" ) 26 | -------------------------------------------------------------------------------- /Log Forging/logf.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace WebFox.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class LogInjection : ControllerBase 14 | { 15 | private readonly ILogger _logger; 16 | 17 | 18 | public LogInjection(ILogger logger) 19 | { 20 | _logger = logger; 21 | } 22 | 23 | [HttpGet("{userInfo}")] 24 | public void injectLog(string userInfo) 25 | { 26 | _logger.LogError("error!! " + userInfo); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /NoSQL Injection/mongodb.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const config = require('../config') 3 | const router = express.Router() 4 | 5 | const MongoClient = require('mongodb').MongoClient; 6 | const url = config.MONGODB_URI; 7 | 8 | router.post('/customers/register', async (req, res) => { 9 | 10 | const client = await MongoClient.connect(url, { useNewUrlParser: true }) 11 | .catch(err => { console.log(err); }); 12 | if (!client) { 13 | return res.json({ status: "Error" }); 14 | } 15 | const db = client.db(config.MONGODB_DB_NAME); 16 | const customers = db.collection("customers") 17 | 18 | let myobj = { name: req.body.name, address: req.body.address }; 19 | customers.insertOne(myobj, function (err) { 20 | if (err) throw err; 21 | console.log("user registered"); 22 | res.json({ status:"success", "message": "user inserted" }) 23 | db.close(); 24 | }); 25 | 26 | }) 27 | 28 | 29 | // Vulnerable search function 30 | router.post('/customers/find', async (req, res) => { 31 | 32 | const client = await MongoClient.connect(url, { useNewUrlParser: true }) 33 | .catch(err => { console.log(err); }); 34 | if (!client) { 35 | return res.json({ status: "Error" }); 36 | } 37 | const db = client.db(config.MONGODB_DB_NAME); 38 | const customers = db.collection("customers") 39 | 40 | let name = req.body.name 41 | let myobj = { name: name }; 42 | customers.findOne(myobj, function (err, result) { 43 | if (err) throw err; 44 | db.close(); 45 | res.json(result) 46 | }); 47 | 48 | 49 | }) 50 | 51 | // Vulnerable Authentication 52 | // Authentication Bypass Example 53 | // curl -X POST http://localhost:3000/customers/login/ --data "{\"email\": {\"\$gt\":\"\"} , \"password\": {\"\$gt\":\"\"}}" -H "Content-Type: application/json" 54 | 55 | router.post('/customers/login', async (req, res) => { 56 | 57 | const client = await MongoClient.connect(url, { useNewUrlParser: true }) 58 | .catch(err => { console.log(err); }); 59 | if (!client) { 60 | return res.json({ status: "Error" }); 61 | } 62 | const db = client.db(config.MONGODB_DB_NAME); 63 | const customers = db.collection("customers") 64 | 65 | let myobj = { email: req.body.email, password: req.body.password }; 66 | customers.findOne(myobj, function (err, result) { 67 | if (err) throw err; 68 | db.close(); 69 | res.json(result) 70 | }); 71 | 72 | 73 | }) 74 | 75 | module.exports = router 76 | -------------------------------------------------------------------------------- /Open Redirect/Remote Code Execution in apt-get: -------------------------------------------------------------------------------- 1 | NextURI = DeQuoteString(Req.Location); 2 | ... 3 | Redirect(NextURI); 4 | 5 | // From apt-pkg/acquire-method.cc 6 | void pkgAcqMethod::Redirect(const string &NewURI) 7 | { 8 | std::cout << "103 Redirect\nURI: " << Queue->Uri << "\n" 9 | << "New-URI: " << NewURI << "\n" 10 | << "\n" << std::flush; 11 | Dequeue(); 12 | } 13 | -------------------------------------------------------------------------------- /Open Redirect/example1.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Open Redirect/example1.rb: -------------------------------------------------------------------------------- 1 | def legacy 2 | redirect_to(params.update(action:'main')) 3 | end 4 | -------------------------------------------------------------------------------- /Open Redirect/koa.js: -------------------------------------------------------------------------------- 1 | 2 | const Koa = require('koa'); 3 | const urlLib = require('url'); 4 | const app = new Koa(); 5 | 6 | app.use(async ctx => { 7 | var url = ctx.query.target; 8 | ctx.redirect(url); 9 | }); 10 | 11 | app.listen(3000); -------------------------------------------------------------------------------- /Open Redirect/redirect.js: -------------------------------------------------------------------------------- 1 | 2 | console.log('WIP') 3 | const express = require('express'); 4 | const router = express.Router() 5 | 6 | router.get('/login',function(req, res){ 7 | let followPath = req.query.path; 8 | if(req.session.isAuthenticated()){ 9 | res.redirect('http://example.com/'+followPath); //false positive 10 | }else{ 11 | res.redirect('/'); 12 | } 13 | }); 14 | 15 | router.get('/goto',function(req, res){ 16 | let url = encodeURI(req.query.url); //vulnerability 17 | res.redirect(url); 18 | }); 19 | 20 | 21 | module.exports = router 22 | -------------------------------------------------------------------------------- /Out of Bounds/damnvuln.c: -------------------------------------------------------------------------------- 1 | //https://github.com/hardik05/Damn_Vulnerable_C_Program/blob/master/imgRead.c 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | struct Image 8 | { 9 | char header[4]; 10 | int width; 11 | int height; 12 | char data[10]; 13 | }; 14 | 15 | int ProcessImage(char* filename){ 16 | 17 | FILE *fp; 18 | char ch; 19 | struct Image img; 20 | 21 | fp = fopen(filename,"r"); 22 | 23 | if(fp == NULL) 24 | { 25 | printf("\nCan't open file or file doesn't exist."); 26 | exit(0); 27 | } 28 | 29 | printf("\n\tHeader\twidth\theight\tdata\t\r\n"); 30 | 31 | while(fread(&img,sizeof(img),1,fp)>0){ 32 | printf("\n\t%s\t%d\t%d\t%s\r\n",img.header,img.width,img.height,img.data); 33 | 34 | int size1 = img.width + img.height; //Vulnerability: integer overflow 35 | char* buff1=(char*)malloc(size1); 36 | 37 | memcpy(buff1,img.data,sizeof(img.data)); //Vulnerability: no data buffer size/malloc success check? 38 | free(buff1); 39 | 40 | if (size1/2==0){ 41 | free(buff1); //Vulnerability: double free 42 | } 43 | else{ 44 | if(size1 == 123456){ 45 | buff1[0]='a'; //Vulnerability: use after free 46 | } 47 | } 48 | 49 | int size2 = img.width - img.height+100; //Vulnerability: integer underflow 50 | //printf("Size1:%d",size1); 51 | char* buff2=(char*)malloc(size2); 52 | 53 | memcpy(buff2,img.data,sizeof(img.data)); 54 | 55 | int size3= img.width/img.height; 56 | //printf("Size2:%d",size3); 57 | 58 | char buff3[10]; 59 | char* buff4 =(char*)malloc(size3); 60 | memcpy(buff4,img.data,sizeof(img.data)); 61 | 62 | char OOBR_stack = buff3[size3+100]; //Vulnerability: out of bound read (stack) 63 | char OOBR_heap = buff4[100]; 64 | 65 | buff3[size3+100]='c'; //Vulnerability: out of bound write (Stack) 66 | buff4[100]='c'; //Vulnerability: out of bound write (Heap) 67 | 68 | if(size3>10){ 69 | buff4=0; //memory leak? 70 | } 71 | else{ 72 | free(buff4); 73 | } 74 | 75 | free(buff2); 76 | } 77 | fclose(fp); 78 | } 79 | 80 | int main(int argc,char **argv) 81 | { 82 | ProcessImage(argv[1]); 83 | } 84 | -------------------------------------------------------------------------------- /PHP Object Injection/chall1.php: -------------------------------------------------------------------------------- 1 | class Example1 2 | { 3 | public $cache_file; 4 | 5 | function __construct() 6 | { 7 | // some PHP code... 8 | } 9 | 10 | function __destruct() 11 | { 12 | $file = "/var/www/cache/tmp/{$this->cache_file}"; 13 | if (file_exists($file)) @unlink($file); 14 | } 15 | } 16 | 17 | // some PHP code... 18 | 19 | $user_data = unserialize($_GET['data']); 20 | 21 | // some PHP code... 22 | -------------------------------------------------------------------------------- /PHP Object Injection/chall2.php: -------------------------------------------------------------------------------- 1 | class Example2 2 | { 3 | private $hook; 4 | 5 | function __construct() 6 | { 7 | // some PHP code... 8 | } 9 | 10 | function __wakeup() 11 | { 12 | if (isset($this->hook)) eval($this->hook); 13 | } 14 | } 15 | 16 | // some PHP code... 17 | 18 | $user_data = unserialize($_COOKIE['data']); 19 | 20 | // some PHP code... 21 | -------------------------------------------------------------------------------- /PHP Object Injection/tarlogic-ex1.php: -------------------------------------------------------------------------------- 1 | role - 1337; 16 | if ($check == "ADMIN") { 17 | $flag = file_get_contents("flag.txt"); 18 | echo $flag; 19 | } else { 20 | echo "No flag for you!! Better luck next time!\n"; 21 | } 22 | ?> 23 | -------------------------------------------------------------------------------- /PHP Object Injection/tarlogic-ex2.php: -------------------------------------------------------------------------------- 1 | innocent(); 9 | } 10 | public function innocent() { 11 | echo "Aquí no pasa nada :D\n"; 12 | } 13 | } 14 | class GiveFlag extends File { 15 | public $offset = 23; 16 | public function innocent() { 17 | $stuff = fopen("flag.txt", "r"); 18 | fseek($stuff, $this->offset); 19 | print fread($stuff, filesize("flag.txt")); 20 | } 21 | } 22 | class entry { 23 | public function __destruct(){ 24 | $this->awesome->flag(); 25 | } 26 | } 27 | unserialize($argv[1]); 28 | ?> 29 | -------------------------------------------------------------------------------- /PHP Object Injection/tarlogic1.php: -------------------------------------------------------------------------------- 1 | dir); 10 | } 11 | } 12 | $test = new warm(); 13 | $a = serialize($test); 14 | echo "Example of an object:\n$a\n\n"; 15 | unserialize($argv[1]); 16 | ?> 17 | -------------------------------------------------------------------------------- /Path Traversal/PT1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace WebFox.Controllers.PathTraversal 4 | { 5 | public class PathTraversalTest1 : ControllerBase 6 | { 7 | [HttpGet("{path}")] 8 | public void Test(string path) 9 | { 10 | System.IO.File.Delete(path); 11 | } 12 | 13 | 14 | } 15 | } -------------------------------------------------------------------------------- /Path Traversal/PT2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace WebFox.Controllers.PathTraversal 6 | { 7 | public class PathTraversalTest2 : ControllerBase 8 | { 9 | private const string RootFolder = @"C:\Temp\Data\"; 10 | 11 | [HttpGet("{userInput}")] 12 | public void Test(string userInput) 13 | { 14 | try 15 | { 16 | var fullPath = Path.Combine(RootFolder, userInput); 17 | System.IO.File.Delete(fullPath); 18 | } 19 | catch (IOException ioExp) 20 | { 21 | Console.WriteLine(ioExp.Message); 22 | } 23 | Console.ReadKey(); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Path Traversal/PT3.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.IO; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace WebFox.Controllers.PathTraversal 6 | { 7 | public class PathTraversalTest3 : ControllerBase 8 | { 9 | private const string RootFolder = @"C:\Temp\Data\"; 10 | 11 | [HttpGet("{userInput}")] 12 | public void Test(string userInput) 13 | { 14 | string[] lines = { "First line", "Second line", "Third line" }; 15 | using (var outputFile = new StreamWriter(RootFolder + userInput)) 16 | { 17 | foreach (var line in lines) 18 | outputFile.WriteLine(line); 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Path Traversal/PT4.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.IO; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace WebFox.Controllers.PathTraversal 6 | { 7 | public class PathTraversalTest4 : ControllerBase 8 | { 9 | private const string RootFolder = @"C:\Temp\Data\"; 10 | 11 | [HttpGet("{userInput}")] 12 | public void Test(string userInput) 13 | { 14 | string[] lines = { "First line", "Second line", "Third line" }; 15 | using var outputFile = new StreamWriter(RootFolder + userInput); 16 | foreach (var line in lines) 17 | outputFile.WriteLine(line); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Path Traversal/ZipTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.zip.ZipFile; 2 | import java.util.zip.ZipEntry; 3 | ⋮ 4 | public void extract(ZipFile zip) { 5 | ⋮ 6 | String toDir = "/my/target/directory/"; 7 | Enumeration entries = zip.entries(); 8 | while (entries.hasMoreElements()) { 9 | ZipEntry zipEntry = entries.nextElement(); 10 | ⋮ 11 | File file = new File(toDir, zipEntry.getName()) 12 | InputStream istr = zipFile.getInputStream(zipEntry); 13 | final OutputStream os = Files.newOutputStream(file.toPath()); 14 | bos = new BufferedOutputStream(os); 15 | IOUtils.copy(bis, bos); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Path Traversal/ZipTraversalPatched.java: -------------------------------------------------------------------------------- 1 | import java.util.zip.ZipFile; 2 | import java.util.zip.ZipEntry; 3 | ⋮ 4 | public void extract(ZipFile zip) { 5 | ⋮ 6 | String toDir = "/my/target/directory/"; 7 | Enumeration entries = zip.entries(); 8 | while (entries.hasMoreElements()) { 9 | ZipEntry zipEntry = entries.nextElement(); 10 | ⋮ 11 | File file = new File(toDir, zipEntry.getName()) 12 | if( !file.getCanonicalPath().startsWith(toDir) ){ 13 | throw new SecurityException("ZipEntry not within target directory!"); 14 | } 15 | InputStream istr = zipFile.getInputStream(zipEntry); 16 | final OutputStream os = Files.newOutputStream(file.toPath()); 17 | bos = new BufferedOutputStream(os); 18 | IOUtils.copy(bis, bos); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Path Traversal/bypass.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /Path Traversal/example3.java: -------------------------------------------------------------------------------- 1 | Intent in = getIntent(); 2 | String path = in.getStringExtra("path"); 3 | if(path == null) 4 | return; 5 | String sdcard = Environment.getExternalStorageDirectory() 6 | if(path.startsWith(sdcard)) 7 | { 8 | Log.e(TAG, "Attempt to write to sdcard"); 9 | return; 10 | } 11 | writeToFile(path); 12 | -------------------------------------------------------------------------------- /Path Traversal/expresstest.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.get('/', (req, res) => { 6 | const file = readFile(req.query.name).toString() 7 | res.send(file) 8 | }) 9 | 10 | 11 | function readFile(path){ 12 | 13 | result = fs.readFileSync(path) 14 | return result; 15 | 16 | } 17 | 18 | 19 | 20 | app.listen(port, () => { 21 | console.log(`Example app listening at http://localhost:${port}`) 22 | }) 23 | -------------------------------------------------------------------------------- /Path Traversal/gq.js: -------------------------------------------------------------------------------- 1 | const { ApolloServer, gql } = require('apollo-server'); 2 | 3 | var fs = require('fs'); 4 | var express = require('express'); 5 | var app = express(); 6 | 7 | 8 | // A schema is a collection of type definitions (hence "typeDefs") 9 | // that together define the "shape" of queries that are executed against 10 | // your data. 11 | const typeDefs = gql` 12 | # Comments in GraphQL strings (such as this one) start with the hash (#) symbol. 13 | 14 | # This "Book" type defines the queryable fields for every book in our data source. 15 | type Book { 16 | title: String 17 | author: String 18 | } 19 | 20 | # The "Query" type is special: it lists all of the available queries that 21 | # clients can execute, along with the return type for each. In this 22 | # case, the "books" query returns an array of zero or more Books (defined above). 23 | type Query { 24 | books(path: String): [Book] 25 | } 26 | `; 27 | 28 | 29 | const books = [ 30 | { 31 | title: 'The Awakening', 32 | author: 'Kate Chopin', 33 | }, 34 | { 35 | title: 'City of Glass', 36 | author: 'Paul Auster', 37 | }, 38 | ]; 39 | 40 | 41 | 42 | // Resolvers define the technique for fetching the types defined in the 43 | // schema. This resolver retrieves books from the "books" array above. 44 | const resolvers = { 45 | Query: { 46 | books: (parent, args, context, info) => { 47 | const file = readFile(args.path).toString() 48 | console.log(file) 49 | return [{title: file, author: "hello"}] 50 | }, 51 | }, 52 | }; 53 | 54 | function readFile(path ){ 55 | 56 | result = fs.readFileSync(path) 57 | return result; 58 | 59 | } 60 | 61 | // The ApolloServer constructor requires two parameters: your schema 62 | // definition and your set of resolvers. 63 | const server = new ApolloServer({ 64 | introspection: true, 65 | typeDefs, resolvers }); 66 | 67 | 68 | 69 | // The `listen` method launches a web server. 70 | server.listen().then(({ url }) => { 71 | console.log(`🚀 Server ready at ${url}`); 72 | }); 73 | 74 | 75 | -------------------------------------------------------------------------------- /Path Traversal/phpexample.php: -------------------------------------------------------------------------------- 1 | 2 | 36 | -------------------------------------------------------------------------------- /Path Traversal/py_ctf.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from flask import ( 4 | Flask, 5 | render_template, 6 | request, 7 | url_for, 8 | redirect, 9 | session, 10 | render_template_string 11 | ) 12 | from flask.ext.session import Session 13 | 14 | app = Flask(__name__) 15 | 16 | 17 | execfile('flag.py') 18 | execfile('key.py') 19 | 20 | FLAG = flag 21 | app.secret_key = key 22 | 23 | 24 | @app.route("/golem", methods=["GET", "POST"]) 25 | def golem(): 26 | if request.method != "POST": 27 | return redirect(url_for("index")) 28 | 29 | golem = request.form.get("golem") or None 30 | 31 | if golem is not None: 32 | golem = golem.replace(".", "").replace( 33 | "_", "").replace("{", "").replace("}", "") 34 | 35 | if "golem" not in session or session['golem'] is None: 36 | session['golem'] = golem 37 | 38 | template = None 39 | 40 | if session['golem'] is not None: 41 | template = '''{% % extends "layout.html" % %} 42 | {% % block body % %} 43 |

Golem Name < /h1 > 44 |
46 | Hello: % s, why you don't look at our article < /a >? 47 | < / div > 48 | < / div > 49 | {% % endblock % %} 50 | ''' % session['golem'] 51 | 52 | print 53 | 54 | session['golem'] = None 55 | 56 | return render_template_string(template) 57 | 58 | 59 | @app.route("/", methods=["GET"]) 60 | def index(): 61 | return render_template("main.html") 62 | 63 | 64 | @app.route('/article', methods=['GET']) 65 | def article(): 66 | 67 | error = 0 68 | 69 | if 'name' in request.args: 70 | page = request.args.get('name') 71 | else: 72 | page = 'article' 73 | 74 | if page.find('flag') >= 0: 75 | page = 'notallowed.txt' 76 | 77 | try: 78 | template = open('/home/golem/articles/{}'.format(page)).read() 79 | except Exception as e: 80 | template = e 81 | 82 | return render_template('article.html', template=template) 83 | 84 | if __name__ == "__main__": 85 | app.run(host='0.0.0.0', debug=False) 86 | -------------------------------------------------------------------------------- /PostMessage Security/challenge1.js: -------------------------------------------------------------------------------- 1 | //https://html5.digi.ninja/challenge.html 2 | 3 | if (typeof(SERVER_DOMAIN) === 'undefined') { 4 | window.location.replace("/unconfigured.html"); 5 | } 6 | 7 | const RECEIVE_URL = SERVER_DOMAIN + "/challenge_scoreboard.html" + "?origin=" + get_domain(); 8 | 9 | var window_ref = null; 10 | 11 | document.getElementById("username").focus(); 12 | 13 | function store_username() { 14 | var username; 15 | var username_obj; 16 | 17 | username_obj = document.getElementById("username"); 18 | username = username_obj.value 19 | 20 | var welcome; 21 | welcome = document.getElementById("welcome"); 22 | welcome.innerHTML = "Welcome " + html_encode (username); 23 | 24 | var set_username; 25 | set_username = document.getElementById("set_username"); 26 | set_username.style.display="none"; 27 | 28 | var game; 29 | game = document.getElementById("game"); 30 | game.style.display="inline"; 31 | 32 | start_game(); 33 | // have to do time out so the window can open 34 | setTimeout (function () {send_username(username);}, 1000); 35 | 36 | return false; 37 | } 38 | 39 | function check_guess() { 40 | var guess_obj = document.getElementById("guess"); 41 | var guess = guess_obj.value; 42 | var res = document.getElementById("result"); 43 | 44 | send_message("guess:" + guess); 45 | 46 | document.getElementById("guess").focus(); 47 | document.getElementById("guess").value = ""; 48 | } 49 | 50 | function html_encode (html) { 51 | return document.createElement( 'a' ).appendChild( 52 | document.createTextNode( html ) ).parentNode.innerHTML; 53 | } 54 | 55 | function send_message(message) { 56 | if (window_ref == null) { 57 | return; 58 | } 59 | if (window_ref.closed) { 60 | return; 61 | } 62 | 63 | window_ref.postMessage(message, "*"); 64 | // window_ref.postMessage(message, RECEIVE_URL); 65 | } 66 | 67 | function start_game() { 68 | open_window(); 69 | document.getElementById("guess").focus(); 70 | } 71 | 72 | function send_username(username) { 73 | message = "user:" + html_encode(username); 74 | send_message(message); 75 | } 76 | 77 | function get_domain() { 78 | var url = window.location.href 79 | var arr = url.split("/"); 80 | return arr[0] + "//" + arr[2] 81 | } 82 | 83 | function open_window() { 84 | if (window_ref == null || window_ref.closed) { 85 | window_ref = window.open (RECEIVE_URL, "score board", "height=260,width=550"); 86 | 87 | if (window_ref == null) { 88 | alert ("Failed to open window. You must allow pop-ups."); 89 | } 90 | } 91 | } 92 | 93 | const usernameButton = document.getElementById("setUsername"); 94 | usernameButton.addEventListener("click", store_username, false); 95 | 96 | const guessButton = document.getElementById("checkGuess"); 97 | guessButton.addEventListener("click", check_guess, false); 98 | 99 | start_game(); 100 | -------------------------------------------------------------------------------- /PostMessage Security/challenge3.js: -------------------------------------------------------------------------------- 1 | //https://html5.digi.ninja 2 | 3 | if (typeof(SERVER_DOMAIN) === 'undefined') { 4 | window.location.replace("/unconfigured.html"); 5 | } 6 | 7 | const RECEIVE_URL = SERVER_DOMAIN + "/s_child.html" + "?origin=" + get_domain(); 8 | 9 | var window_ref = null; 10 | 11 | function send_message(destination) { 12 | message = document.getElementById("message").value; 13 | receiver.contentWindow.postMessage(message, SERVER_DOMAIN); 14 | } 15 | 16 | function get_domain() { 17 | var url = window.location.href 18 | var arr = url.split("/"); 19 | return arr[0] + "//" + arr[2] 20 | } 21 | 22 | var receiver = document.getElementById("s_iframe"); 23 | receiver.src = RECEIVE_URL; 24 | 25 | const sendMessageButton = document.getElementById("send_message_button"); 26 | sendMessageButton.addEventListener("click", send_message, false); 27 | -------------------------------------------------------------------------------- /PostMessage Security/challenge_2.js: -------------------------------------------------------------------------------- 1 | function receiveMessage(message) { 2 | let tokenSpan = document.getElementById("token"); 3 | if (message.data == null) { 4 | tokenSpan.innerText = ""; 5 | } else { 6 | tokenSpan.innerText = message.data; 7 | } 8 | } 9 | 10 | window.addEventListener("message", receiveMessage, false); 11 | -------------------------------------------------------------------------------- /Prototype Pollution/lodash.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | 4 | const lodash = require('lodash'); 5 | 6 | //if req.body.config == '{"constructor": {"prototype": {"isAdmin": true}}}' it will bypass the authentication 7 | function check(req, res) { 8 | 9 | let config = {}; 10 | lodash.defaultsDeep(config, JSON.parse(req.body.config)); 11 | 12 | let user = getCurrentUser(); 13 | if(!user){ 14 | user = {}; 15 | } 16 | 17 | if (user.isAdmin && user.isAdmin === true) { 18 | res.send('Welcome Admin') 19 | }else{ 20 | res.send('Welcome User') 21 | } 22 | } 23 | 24 | //fake function that get current user from session or db 25 | function getCurrentUser(){ 26 | return false; 27 | } 28 | 29 | 30 | router.post('/check-user',check) 31 | 32 | module.exports = router 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vulnerable-Code-Snippets 2 | 3 | A collection of vulnerable code snippets taken form around the internet. Snippets taken from various blog posts, books, resources etc. No Copyright Infringement Intended 4 | 5 | 6 | **Note: This is not a good benchmark for testing static analysis tools, they are broken code snippets, with missing imports and missing files.** 7 | -------------------------------------------------------------------------------- /ReDoS/redos.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | 4 | 5 | router.get("/tstMe", (req, res) => { 6 | var r = /([a-z]+)+$/; 7 | 8 | let match = r.test(req.params.id); 9 | res.send(match) 10 | 11 | }); 12 | 13 | 14 | module.exports = router 15 | -------------------------------------------------------------------------------- /Resource Injection/example1.asp: -------------------------------------------------------------------------------- 1 | int rPort = Int32.Parse(Request.get_Item("remotePort ")); 2 | IPEndPoint endpoint = new IPEndPoint(address,rPort); 3 | socket = new Socket(endpoint.AddressFamily, 4 | SocketType.Stream, ProtocolType.Tcp); 5 | socket.Connect(endpoint); 6 | -------------------------------------------------------------------------------- /SQL Injection/Cryptolog,php: -------------------------------------------------------------------------------- 1 | #https://pentest.blog/advisory-cryptolog-unauthenticated-remote-code-execution/ 2 | 3 | $user=$_POST['user']; 4 | $pass=$_POST['pass']; 5 | if($_GET['act']=='logout'){ 6 | session_unset(); 7 | $contenttowrite = $contenttowrite.'Çıkış yaptınız!'; 8 | }else if($_GET['act']=='login'){ 9 | $link = mysql_connect(DB_HOST, DB_USER, DB_PASS); 10 | if (!$link) die ("Out of service"); 11 | mysql_select_db(DB_DATABASE, $link) or die ("Out of service"); 12 | $queryusercheck = mysql_query("SELECT count(id) FROM cc_users WHERE USERNAME='$user' AND `PASSWORD`='".computeHash($user, $pass)."'",$link); 13 | $usercheck_value = mysql_fetch_array ($queryusercheck); 14 | -------------------------------------------------------------------------------- /SQL Injection/SQLi.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Data.SqlClient; 5 | 6 | namespace WebFox.Controllers 7 | { 8 | [ApiController] 9 | [Route("[controller]")] 10 | public class Sqli : ControllerBase 11 | { 12 | 13 | private readonly ILogger _logger; 14 | 15 | public Sqli(ILogger logger) 16 | { 17 | _logger = logger; 18 | } 19 | 20 | 21 | [HttpGet("{id}")] 22 | public string DoSqli(string id) 23 | { 24 | string conString = "I AM a connection String"; 25 | using (SqlCommand cmd = new SqlCommand("SELECT * FROM users WHERE userId = '" + id + "'")) 26 | { 27 | using (SqlConnection con = new SqlConnection(conString)) 28 | { 29 | con.Open(); 30 | cmd.Connection = con; 31 | SqlDataReader reader = cmd.ExecuteReader(); 32 | string res = ""; 33 | while (reader.Read()) 34 | { 35 | res += reader["userName"]; 36 | } 37 | return res; 38 | } 39 | } 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /SQL Injection/blindsqli.php: -------------------------------------------------------------------------------- 1 | querySingle('select count(*) from secrets where id = ' . $_GET['id']); 18 | 19 | if ($count > 0) { 20 | echo 'Yes!'; 21 | } else { 22 | echo 'No!'; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SQL Injection/example.java: -------------------------------------------------------------------------------- 1 | // Get username from parameters 2 | String username = request.getParameter("username"); 3 | // Create a statement from database connection 4 | Statement statement = connection.createStatement(); 5 | // Create unsafe query by concatenating user defined data with query string 6 | String query = "SELECT secret FROM Users WHERE (username = '" + username + "' AND NOT role = 'admin')"; 7 | // ... OR ... 8 | // Insecurely format the query string using user defined data 9 | String query = String.format("SELECT secret FROM Users WHERE (username = '%s' AND NOT role = 'admin')", username); 10 | // Execute query and return the results 11 | ResultSet result = statement.executeQuery(query); 12 | -------------------------------------------------------------------------------- /SQL Injection/example1.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | protect_from_forgery with: :exception 3 | end 4 | class UsersController < ApplicationController 5 | def update 6 | con = Mysql.new 'localhost', 'user', 'pwd' 7 | con.query 'UPDATE users set name = ' + params[:name] + 8 | ' where id = ' + params[:id] 9 | con.close 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /SQL Injection/example2.js: -------------------------------------------------------------------------------- 1 | var mysql = require('db-mysql'); 2 | var http = require('http'); 3 | var out; 4 | var valTom; 5 | var req = http.request(options, function(res) 6 | { 7 | res.on('data', function(chunk) 8 | { 9 | valTom = chunk; 10 | } 11 | ); 12 | } 13 | ); 14 | new mysql.Database( 15 | { 16 | hostname: 'localhost', 17 | user: 'user', 18 | password: 'password', 19 | database: 'test' 20 | } 21 | ).connect(function(error) 22 | { 23 | var the_Query = 24 | "INSERT INTO Customers (CustomerName, ContactName) VALUES ('Tom'," + 25 | valTom + ")"; 26 | this.query(the_Query).execute(function(error, result) 27 | { 28 | if (error) 29 | { 30 | console.log("Error: " + error); 31 | } 32 | else 33 | { 34 | console.log('GENERATED id: ' + result.id); 35 | } 36 | } 37 | ); 38 | out = resIn; 39 | } 40 | ); 41 | -------------------------------------------------------------------------------- /SQL Injection/mysql.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | 4 | const config = require('../../config') 5 | const mysql = require('mysql'); 6 | const connection = mysql.createConnection({ 7 | host : config.MYSQL_HOST, 8 | port : config.MYSQL_PORT, 9 | user : config.MYSQL_USER, 10 | password : config.MYSQL_PASSWORD, 11 | database : config.MYSQL_DB_NAME, 12 | }); 13 | 14 | connection.connect(); 15 | 16 | router.get('/example1/user/:id', (req,res) => { 17 | let userId = req.params.id; 18 | let query = { 19 | sql : "SELECT * FROM users WHERE id=" + userId 20 | } 21 | connection.query(query,(err, result) => { 22 | res.json(result); 23 | }); 24 | }) 25 | 26 | router.get('/example2/user/:id', (req,res) => { 27 | let userId = req.params.id; 28 | connection.query("SELECT * FROM users WHERE id=" + userId,(err, result) => { 29 | res.json(result); 30 | }); 31 | }) 32 | 33 | router.get('/example3/user/:id', (req,res) => { 34 | let userId = req.params.id; 35 | connection.query({ 36 | sql : "SELECT * FROM users WHERE id=" +userId 37 | },(err, result) => { 38 | res.json(result); 39 | }); 40 | }) 41 | 42 | 43 | module.exports = router 44 | -------------------------------------------------------------------------------- /SQL Injection/sql.js: -------------------------------------------------------------------------------- 1 | var express = require('express') 2 | 3 | var app = express() 4 | const Sequelize = require('sequelize'); 5 | const sequelize = new Sequelize('database', 'username', 'password', { 6 | dialect: 'sqlite', 7 | storage: 'data/juiceshop.sqlite' 8 | }); 9 | 10 | app.post('/login', function (req, res) { 11 | sequelize.query('SELECT * FROM Products WHERE name LIKE ' + req.body.username); 12 | }) -------------------------------------------------------------------------------- /SQL Injection/sqli.php: -------------------------------------------------------------------------------- 1 | querySingle('select count(*) from secrets where id = ' . $_GET['id']); 18 | 19 | if ($count > 0) { 20 | echo 'Yes!'; 21 | } else { 22 | echo 'No!'; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SSRF/express.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router() 3 | const request = require('request'); 4 | 5 | router.post('/downlad-url', (req, res) => { 6 | downloadURL(req.body.url, () =>{ 7 | res.send('Done') 8 | }) 9 | }); 10 | 11 | const downloadURL = (url, onend) => { 12 | const opts = { 13 | uri: url, 14 | method: 'GET', 15 | followAllRedirects: true 16 | } 17 | 18 | request(opts) 19 | .on('data', ()=>{}) 20 | .on('end', () => onend()) 21 | .on('error', (err) => console.log(err, 'controller.url.download.error')) 22 | } 23 | 24 | module.exports = router 25 | -------------------------------------------------------------------------------- /Sensitive Data Exposure/Railsgoatconfig.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Be sure to restart your server when you modify this file. 3 | 4 | Railsgoat::Application.config.secret_key_base = "2f1d90a26236c3245d96f5606c201a780dc9ca687e5ed82b45e211bb5dc84c1870f61ca9e002dad5dd8a149c9792d8f07f31a9575065cca064bd6af44f8750e4" 5 | -------------------------------------------------------------------------------- /Sensitive Data Exposure/graphql.ts: -------------------------------------------------------------------------------- 1 | import depthLimit from 'graphql-depth-limit' 2 | import express from 'express' 3 | import graphqlHTTP from 'express-graphql' 4 | import schema from './schema' 5 | 6 | 7 | const app = express() 8 | // depthlimit prevents nested queries 9 | app.use('/graphql', graphqlHTTP((req, res) => ({ 10 | schema, 11 | validationRules: [ depthLimit(10) ] 12 | }))) 13 | -------------------------------------------------------------------------------- /Sensitive Data Exposure/hardcoded.ts: -------------------------------------------------------------------------------- 1 | 2 | var password = 'mysecretpass'; 3 | 4 | const fooPassword = 'mysecretpass'; 5 | 6 | -------------------------------------------------------------------------------- /Server Side Template Injection/Twig.php: -------------------------------------------------------------------------------- 1 | // composer require "twig/twig" 2 | require 'vendor/autoload.php'; 3 | 4 | class Template { 5 | private $twig; 6 | 7 | public function __construct() { 8 | $indexTemplate = '' . 10 | 'Next slide »'; 11 | 12 | // Default twig setup, simulate loading 13 | // index.html file from disk 14 | $loader = new Twig\Loader\ArrayLoader([ 15 | 'index.html' => $indexTemplate 16 | ]); 17 | $this->twig = new Twig\Environment($loader); 18 | } 19 | 20 | public function getNexSlideUrl() { 21 | $nextSlide = $_GET['nextSlide']; 22 | return filter_var($nextSlide, FILTER_VALIDATE_URL); 23 | } 24 | 25 | public function render() { 26 | echo $this->twig->render( 27 | 'index.html', 28 | ['link' => $this->getNexSlideUrl()] 29 | ); 30 | } 31 | } 32 | 33 | (new Template())->render(); 34 | -------------------------------------------------------------------------------- /Server Side Template Injection/asis_ssti_pt.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from flask import ( 4 | Flask, 5 | render_template, 6 | request, 7 | url_for, 8 | redirect, 9 | session, 10 | render_template_string 11 | ) 12 | from flask.ext.session import Session 13 | 14 | app = Flask(__name__) 15 | 16 | 17 | execfile('flag.py') 18 | execfile('key.py') 19 | 20 | FLAG = flag 21 | app.secret_key = key 22 | 23 | 24 | @app.route("/golem", methods=["GET", "POST"]) 25 | def golem(): 26 | if request.method != "POST": 27 | return redirect(url_for("index")) 28 | 29 | golem = request.form.get("golem") or None 30 | 31 | if golem is not None: 32 | golem = golem.replace(".", "").replace( 33 | "_", "").replace("{", "").replace("}", "") 34 | 35 | if "golem" not in session or session['golem'] is None: 36 | session['golem'] = golem 37 | 38 | template = None 39 | 40 | if session['golem'] is not None: 41 | template = '''{% % extends "layout.html" % %} 42 | {% % block body % %} 43 |

Golem Name < /h1 > 44 |
46 | Hello: % s, why you don't look at our article < /a >? 47 | < / div > 48 | < / div > 49 | {% % endblock % %} 50 | ''' % session['golem'] 51 | 52 | print 53 | 54 | session['golem'] = None 55 | 56 | return render_template_string(template) 57 | 58 | 59 | @app.route("/", methods=["GET"]) 60 | def index(): 61 | return render_template("main.html") 62 | 63 | 64 | @app.route('/article', methods=['GET']) 65 | def article(): 66 | 67 | error = 0 68 | 69 | if 'name' in request.args: 70 | page = request.args.get('name') 71 | else: 72 | page = 'article' 73 | 74 | if page.find('flag') >= 0: 75 | page = 'notallowed.txt' 76 | 77 | try: 78 | template = open('/home/golem/articles/{}'.format(page)).read() 79 | except Exception as e: 80 | template = e 81 | 82 | return render_template('article.html', template=template) 83 | 84 | if __name__ == "__main__": 85 | app.run(host='0.0.0.0', debug=False) 86 | -------------------------------------------------------------------------------- /Server Side Template Injection/sstigolang.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "os/exec" 6 | "bufio" 7 | "log" 8 | "os" 9 | ) 10 | 11 | type Person string 12 | 13 | func (p Person) Secret (test string) string { 14 | out, _ := exec.Command(test).CombinedOutput() 15 | return string(out) 16 | } 17 | 18 | func (p Person) Label (test string) string { 19 | return "This is " + string(test) 20 | } 21 | 22 | func main(){ 23 | reader := bufio.NewReader(os.Stdin) 24 | text, _ := reader.ReadString('\n') 25 | tmpl, err := template.New("").Parse(text) 26 | if err != nil { 27 | log.Fatalf("Parse: %v", err) 28 | } 29 | tmpl.Execute(os.Stdin,Person("Gus")) 30 | } 31 | -------------------------------------------------------------------------------- /Server Side Template Injection/test.py: -------------------------------------------------------------------------------- 1 | from jinja2 import Template 2 | from flask import request 3 | 4 | import flask 5 | 6 | app = flask.Flask(__name__) 7 | app.config['DEBUG'] = True 8 | 9 | @app.route('/', methods=['GET']) 10 | def home(): 11 | renderer = Template('Hello, ' + request.args['name']) 12 | return renderer.render() 13 | 14 | app.run() 15 | -------------------------------------------------------------------------------- /Symlink Attack/file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MY_TMP_FILE "/tmp/file.tmp" 6 | 7 | 8 | int main(int argc, char* argv[]) 9 | { 10 | FILE * f; 11 | if (!access(MY_TMP_FILE, F_OK)) { 12 | printf external link("File exists!\n"); 13 | return EXIT_FAILURE; 14 | } 15 | /* At this point the attacker creates a symlink from /tmp/file.tmp to /etc/passwd */ 16 | tmpFile = fopen(MY_TMP_FILE, "w"); 17 | 18 | if (tmpFile == NULL) { 19 | return EXIT_FAILURE; 20 | } 21 | 22 | fputs("Some text...\n", tmpFile); 23 | 24 | fclose(tmpFile); 25 | /* You successfully overwrote /etc/passwd (at least if you ran this as root) */ 26 | 27 | return EXIT_SUCCESS; 28 | } 29 | -------------------------------------------------------------------------------- /Unsafe Deserialization/CVE-2017-2809.py: -------------------------------------------------------------------------------- 1 | class Vault(object): 2 | '''R/W an ansible-vault yaml file''' 3 | 4 | def __init__(self, password): 5 | self.password = password 6 | self.vault = VaultLib(password) 7 | 8 | def load(self, stream): 9 | '''read vault steam and return python object''' 10 | return yaml.load(self.vault.decrypt(stream)) [0] 11 | -------------------------------------------------------------------------------- /Unsafe Deserialization/de.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | //safeLoadAll and jsyaml.safeLoad are vulnerable if DEFAULT_FULL_SCHEMA is used 4 | const jsyaml = require("js-yaml"); 5 | 6 | var express = require('express'); 7 | var app = express(); 8 | app.post('/store/:id', function(req, res) { 9 | let data; 10 | let unsafeConfig = { schema: jsyaml.DEFAULT_FULL_SCHEMA }; 11 | data = jsyaml.safeLoad(req.params.data, unsafeConfig); -------------------------------------------------------------------------------- /Unsafe Deserialization/java/LogFile.java: -------------------------------------------------------------------------------- 1 | // Vulnerable class 2 | 3 | class LogFile implements Serializable 4 | { 5 | public String filename; 6 | public String filecontent; 7 | 8 | // Function called during deserialization 9 | 10 | private void readObject(ObjectInputStream in) 11 | { 12 | System.out.println("readObject from LogFile"); 13 | 14 | try 15 | { 16 | // Unserialize data 17 | 18 | in.defaultReadObject(); 19 | System.out.println("File name: " + filename + ", file content: \n" + filecontent); 20 | 21 | // Do something useful with the data 22 | // Restore LogFile, write file content to file name 23 | 24 | FileWriter file = new FileWriter(filename); 25 | BufferedWriter out = new BufferedWriter(file); 26 | 27 | System.out.println("Restoring log data to file..."); 28 | out.write(filecontent); 29 | 30 | out.close(); 31 | file.close(); 32 | } 33 | catch (Exception e) 34 | { 35 | System.out.println("Exception: " + e.toString()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Unsafe Deserialization/java/SerializeToFile.java: -------------------------------------------------------------------------------- 1 | lass Utils 2 | { 3 | // Function to serialize an object and write it to a file 4 | 5 | public static void SerializeToFile(Object obj, String filename) 6 | { 7 | try 8 | { 9 | FileOutputStream file = new FileOutputStream(filename); 10 | ObjectOutputStream out = new ObjectOutputStream(file); 11 | 12 | // Serialization of the object to file 13 | 14 | System.out.println("Serializing " + obj.toString() + " to " + filename); 15 | out.writeObject(obj); 16 | 17 | out.close(); 18 | file.close(); 19 | } 20 | catch(Exception e) 21 | { 22 | System.out.println("Exception: " + e.toString()); 23 | } 24 | } 25 | 26 | // Function to deserialize an object from a file 27 | 28 | public static Object DeserializeFromFile(String filename) 29 | { 30 | Object obj = new Object(); 31 | 32 | try 33 | { 34 | FileInputStream file = new FileInputStream(filename); 35 | ObjectInputStream in = new ObjectInputStream(file); 36 | 37 | // Deserialization of the object to file 38 | 39 | System.out.println("Deserializing from " + filename); 40 | obj = in.readObject(); 41 | 42 | in.close(); 43 | file.close(); 44 | } 45 | catch(Exception e) 46 | { 47 | System.out.println("Exception: " + e.toString()); 48 | } 49 | 50 | return obj; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Unsafe Deserialization/pickle2.py: -------------------------------------------------------------------------------- 1 | # Python's revenge 2 | # This is a easy python sandbox, can you bypass it and get the flag? 3 | # https://hitbxctf2018.xctf.org.cn/contest_challenge/ 4 | from __future__ import unicode_literals 5 | from flask import Flask, request, make_response, redirect, url_for, session 6 | from flask import render_template, flash, redirect, url_for, request 7 | from werkzeug.security import safe_str_cmp 8 | from base64 import b64decode as b64d 9 | from base64 import b64encode as b64e 10 | from hashlib import sha256 11 | from cStringIO import StringIO 12 | import random 13 | import string 14 | 15 | import os 16 | import sys 17 | import subprocess 18 | import commands 19 | import pickle 20 | import cPickle 21 | import marshal 22 | import os.path 23 | import filecmp 24 | import glob 25 | import linecache 26 | import shutil 27 | import dircache 28 | import io 29 | import timeit 30 | import popen2 31 | import code 32 | import codeop 33 | import pty 34 | import posixfile 35 | 36 | SECRET_KEY = 'you will never guess' 37 | 38 | if not os.path.exists('.secret'): 39 | with open(".secret", "w") as f: 40 | secret = ''.join(random.choice(string.ascii_letters + string.digits) 41 | for x in range(4)) 42 | f.write(secret) 43 | with open(".secret", "r") as f: 44 | cookie_secret = f.read().strip() 45 | 46 | app = Flask(__name__) 47 | app.config.from_object(__name__) 48 | 49 | black_type_list = [eval, execfile, compile, open, file, os.system, os.popen, os.popen2, os.popen3, os.popen4, os.fdopen, os.tmpfile, os.fchmod, os.fchown, os.open, os.openpty, os.read, os.pipe, os.chdir, os.fchdir, os.chroot, os.chmod, os.chown, os.link, os.lchown, os.listdir, os.lstat, os.mkfifo, os.mknod, os.access, os.mkdir, os.makedirs, os.readlink, os.remove, os.removedirs, os.rename, os.renames, os.rmdir, os.tempnam, os.tmpnam, os.unlink, os.walk, os.execl, os.execle, os.execlp, os.execv, os.execve, os.dup, os.dup2, os.execvp, os.execvpe, os.fork, os.forkpty, os.kill, os.spawnl, os.spawnle, os.spawnlp, os.spawnlpe, os.spawnv, os.spawnve, os.spawnvp, os.spawnvpe, pickle.load, pickle.loads, cPickle.load, cPickle.loads, subprocess.call, subprocess.check_call, subprocess.check_output, subprocess.Popen, commands.getstatusoutput, commands.getoutput, commands.getstatus, glob.glob, linecache.getline, shutil.copyfileobj, shutil.copyfile, shutil.copy, shutil.copy2, shutil.move, shutil.make_archive, dircache.listdir, dircache.opendir, io.open, popen2.popen2, popen2.popen3, popen2.popen4, timeit.timeit, timeit.repeat, sys.call_tracing, code.interact, code.compile_command, codeop.compile_command, pty.spawn, posixfile.open, posixfile.fileopen] 50 | 51 | 52 | @app.before_request 53 | def count(): 54 | session['cnt'] = 0 55 | 56 | 57 | @app.route('/') 58 | def home(): 59 | remembered_str = 'Hello, here\'s what we remember for you. And you can change, delete or extend it.' 60 | new_str = 'Hello fellow zombie, have you found a tasty brain and want to remember where? Go right here and enter it:' 61 | location = getlocation() 62 | if location == False: 63 | return redirect(url_for("clear")) 64 | return render_template('index.html', txt=remembered_str, location=location) 65 | 66 | 67 | @app.route('/clear') 68 | def clear(): 69 | flash("Reminder cleared!") 70 | response = redirect(url_for('home')) 71 | response.set_cookie('location', max_age=0) 72 | return response 73 | 74 | 75 | @app.route('/reminder', methods=['POST', 'GET']) 76 | def reminder(): 77 | if request.method == 'POST': 78 | location = request.form["reminder"] 79 | if location == '': 80 | flash("Message cleared, tell us when you have found more brains.") 81 | else: 82 | flash("We will remember where you find your brains.") 83 | location = b64e(pickle.dumps(location)) 84 | cookie = make_cookie(location, cookie_secret) 85 | response = redirect(url_for('home')) 86 | response.set_cookie('location', cookie) 87 | return response 88 | location = getlocation() 89 | if location == False: 90 | return redirect(url_for("clear")) 91 | return render_template('reminder.html') 92 | 93 | 94 | class FilterException(Exception): 95 | def __init__(self, value): 96 | super(FilterException, self).__init__( 97 | 'The callable object {value} is not allowed'.format(value=str(value))) 98 | 99 | 100 | class TimesException(Exception): 101 | def __init__(self): 102 | super(TimesException, self).__init__( 103 | 'Call func too many times!') 104 | 105 | 106 | def _hook_call(func): 107 | def wrapper(*args, **kwargs): 108 | session['cnt'] += 1 109 | print session['cnt'] 110 | print args[0].stack 111 | for i in args[0].stack: 112 | if i in black_type_list: 113 | raise FilterException(args[0].stack[-2]) 114 | if session['cnt'] > 4: 115 | raise TimesException() 116 | return func(*args, **kwargs) 117 | return wrapper 118 | 119 | 120 | def loads(strs): 121 | reload(pickle) 122 | files = StringIO(strs) 123 | unpkler = pickle.Unpickler(files) 124 | unpkler.dispatch[pickle.REDUCE] = _hook_call( 125 | unpkler.dispatch[pickle.REDUCE]) 126 | return unpkler.load() 127 | 128 | 129 | def getlocation(): 130 | cookie = request.cookies.get('location') 131 | if not cookie: 132 | return '' 133 | (digest, location) = cookie.split("!") 134 | if not safe_str_cmp(calc_digest(location, cookie_secret), digest): 135 | flash("Hey! This is not a valid cookie! Leave me alone.") 136 | return False 137 | location = loads(b64d(location)) 138 | return location 139 | 140 | 141 | def make_cookie(location, secret): 142 | return "%s!%s" % (calc_digest(location, secret), location) 143 | 144 | 145 | def calc_digest(location, secret): 146 | return sha256("%s%s" % (location, secret)).hexdigest() 147 | 148 | 149 | if __name__ == '__main__': 150 | app.run(host="0.0.0.0", port=5051) 151 | -------------------------------------------------------------------------------- /Unsafe Deserialization/unsafe.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var cookieParser = require('cookie-parser'); 3 | var escape = require('escape-html'); 4 | var serialize = require('node-serialize'); 5 | var app = express(); 6 | app.use(cookieParser()) 7 | 8 | app.get('/', function(req, res) { 9 | if (req.cookies.profile) { 10 | var str = new Buffer(req.cookies.profile, 'base64').toString(); 11 | var obj = serialize.unserialize(str); 12 | if (obj.username) { 13 | res.send("Hello " + escape(obj.username)); 14 | } 15 | } else { 16 | res.cookie('profile', "eyJ1c2VybmFtZSI6ImFqaW4iLCJjb3VudHJ5IjoiaW5kaWEiLCJjaXR5IjoiYmFuZ2Fsb3JlIn0=", { 17 | maxAge: 900000, 18 | httpOnly: true 19 | }); 20 | } 21 | res.send("Hello World"); 22 | }); 23 | app.listen(3000); 24 | -------------------------------------------------------------------------------- /Unsafe Deserialization/unserialize.php: -------------------------------------------------------------------------------- 1 | class ViewFile { public $filename = ''; 2 | 3 | 4 | public function __toString() 5 | 6 | 7 | { include $this->filename; return ""; } } 8 | 9 | 10 | 11 | if (isset($_GET['page'])) 12 | 13 | 14 | { $pdfobject = unserialize(base64_decode($_GET['page'])); } 15 | 16 | else { $pdfobject = new File(); } ?> 17 | -------------------------------------------------------------------------------- /Use After Free/damnvuln.c: -------------------------------------------------------------------------------- 1 | //https://github.com/hardik05/Damn_Vulnerable_C_Program/blob/master/imgRead.c 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | struct Image 8 | { 9 | char header[4]; 10 | int width; 11 | int height; 12 | char data[10]; 13 | }; 14 | 15 | int ProcessImage(char* filename){ 16 | 17 | FILE *fp; 18 | char ch; 19 | struct Image img; 20 | 21 | fp = fopen(filename,"r"); 22 | 23 | if(fp == NULL) 24 | { 25 | printf("\nCan't open file or file doesn't exist."); 26 | exit(0); 27 | } 28 | 29 | printf("\n\tHeader\twidth\theight\tdata\t\r\n"); 30 | 31 | while(fread(&img,sizeof(img),1,fp)>0){ 32 | printf("\n\t%s\t%d\t%d\t%s\r\n",img.header,img.width,img.height,img.data); 33 | 34 | int size1 = img.width + img.height; //Vulnerability: integer overflow 35 | char* buff1=(char*)malloc(size1); 36 | 37 | memcpy(buff1,img.data,sizeof(img.data)); //Vulnerability: no data buffer size/malloc success check? 38 | free(buff1); 39 | 40 | if (size1/2==0){ 41 | free(buff1); //Vulnerability: double free 42 | } 43 | else{ 44 | if(size1 == 123456){ 45 | buff1[0]='a'; //Vulnerability: use after free 46 | } 47 | } 48 | 49 | int size2 = img.width - img.height+100; //Vulnerability: integer underflow 50 | //printf("Size1:%d",size1); 51 | char* buff2=(char*)malloc(size2); 52 | 53 | memcpy(buff2,img.data,sizeof(img.data)); 54 | 55 | int size3= img.width/img.height; 56 | //printf("Size2:%d",size3); 57 | 58 | char buff3[10]; 59 | char* buff4 =(char*)malloc(size3); 60 | memcpy(buff4,img.data,sizeof(img.data)); 61 | 62 | char OOBR_stack = buff3[size3+100]; //Vulnerability: out of bound read (stack) 63 | char OOBR_heap = buff4[100]; 64 | 65 | buff3[size3+100]='c'; //Vulnerability: out of bound write (Stack) 66 | buff4[100]='c'; //Vulnerability: out of bound write (Heap) 67 | 68 | if(size3>10){ 69 | buff4=0; //memory leak? 70 | } 71 | else{ 72 | free(buff4); 73 | } 74 | 75 | free(buff2); 76 | } 77 | fclose(fp); 78 | } 79 | 80 | int main(int argc,char **argv) 81 | { 82 | ProcessImage(argv[1]); 83 | } 84 | -------------------------------------------------------------------------------- /XPATH Injection/xpath.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Xml; 3 | 4 | namespace WebFox.Controllers 5 | { 6 | [Route("api/[controller]")] 7 | [ApiController] 8 | public class XPath : ControllerBase 9 | { 10 | [HttpGet("{user}")] 11 | public void XPATH(string user) 12 | { 13 | // Load the document and set the root element. 14 | XmlDocument doc = new XmlDocument(); 15 | doc.Load("bookstore.xml"); 16 | XmlNode root = doc.DocumentElement; 17 | 18 | // Add the namespace. 19 | XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 20 | nsmgr.AddNamespace("bk", "urn:newbooks-schema"); 21 | 22 | XmlNode node = root.SelectSingleNode( 23 | "descendant::bk:book[bk:author/bk:last-name='"+user+"']", nsmgr); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /XSS/Cookie Security/sc.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Security.Cryptography; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace WebFox.Controllers 7 | { 8 | public class SecureCookieTest1: ControllerBase 9 | { 10 | [HttpGet("{response}")] 11 | [HttpGet("{request}")] 12 | 13 | // HttpCookie myCookie = new HttpCookie("Sensitive cookie"); 14 | public void DoPost(HttpWebResponse response, HttpWebRequest request) 15 | { 16 | DoGet(response, request); 17 | } 18 | 19 | public void DoGet(HttpWebResponse response, HttpWebRequest request) 20 | { 21 | Unsafe(response, request); 22 | } 23 | 24 | public void Unsafe(HttpWebResponse response, HttpWebRequest request) 25 | { 26 | string password = "p-" + RandomNumberGenerator.GetInt32(200000000, 2000000000); 27 | 28 | Cookie cookie = new Cookie("password",password); 29 | cookie.Path = "/"; 30 | cookie.Domain = ""; 31 | cookie.Comment = "Cookie Description"; 32 | response.Cookies.Add(cookie); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /XSS/Cookie Security/sc2.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Security.Cryptography; 3 | using Microsoft.AspNetCore.Http; 4 | 5 | namespace WebFox.Controllers 6 | { 7 | public class SecureCookieTest2 8 | { 9 | // HttpCookie myCookie = new HttpCookie("Sensitive cookie"); 10 | public void DoPost(HttpWebResponse response, HttpWebRequest request) 11 | { 12 | DoGet(response, request); 13 | } 14 | 15 | public void DoGet(HttpWebResponse response, HttpWebRequest request) 16 | { 17 | Unsafe(response, request); 18 | } 19 | 20 | public void Unsafe(HttpWebResponse response, HttpWebRequest request) 21 | { 22 | string password = "p-" + RandomNumberGenerator.GetInt32(200000000, 2000000000); 23 | response.Cookies.Add(new Cookie("password", password)); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /XSS/Spring.java: -------------------------------------------------------------------------------- 1 | package com.example.springxss; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | public class XSSController { 13 | 14 | @GetMapping("/hello") 15 | ResponseEntity hello(@RequestParam(value = "name", defaultValue = "World") String name) { 16 | return new ResponseEntity<>("Hello World!" + name, HttpStatus.OK); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /XSS/XSS.cs: -------------------------------------------------------------------------------- 1 | 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | using System.Web; 9 | 10 | namespace WebFox.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class XSS : ControllerBase 15 | { 16 | public async void xss(string userInfo) 17 | { 18 | var context = this.ControllerContext.HttpContext; 19 | 20 | await context.Response.WriteAsync(""+ userInfo +""); 21 | 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /XSS/dom.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |

11 | Hi, 12 |

13 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /XSS/example.php: -------------------------------------------------------------------------------- 1 | 2 | window.addEventListener('message', writeMessage, false); 3 | function writeMessage(event) 4 | { 5 | document.getElementById("message").innerHTML = event.data; 6 | } 7 | 8 | -------------------------------------------------------------------------------- /XSS/express.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const router = express.Router() 3 | 4 | router.get('/greeting', (req, res) => { 5 | const { name } = req.query; 6 | res.send('

Hello :'+ name +"

") 7 | }) 8 | 9 | router.get('/greet-template', (req,res) => { 10 | name = req.query.name 11 | res.render('index', { user_name: name}); 12 | }) 13 | 14 | module.exports = router 15 | -------------------------------------------------------------------------------- /XXE/XmlReader_Tests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | using System.Xml; 7 | 8 | namespace XXEExamples.Tests 9 | { 10 | [TestFixture] 11 | public class XmlReader_Tests 12 | { 13 | [Test] 14 | public void XMLReader_WithDTDProcessingParseAndXmlResolverSet_NotSafe() 15 | { 16 | AssertXXE.IsXMLParserSafe((string xml) => 17 | { 18 | XmlReaderSettings settings = new XmlReaderSettings(); 19 | settings.DtdProcessing = DtdProcessing.Parse; 20 | settings.XmlResolver = new XmlUrlResolver(); 21 | settings.MaxCharactersFromEntities = 6000; 22 | 23 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) 24 | { 25 | XmlReader reader = XmlReader.Create(stream, settings); 26 | 27 | var xmlDocument = new XmlDocument(); 28 | xmlDocument.XmlResolver = new XmlUrlResolver(); 29 | xmlDocument.Load(reader); 30 | return xmlDocument.InnerText; 31 | } 32 | }, false); 33 | } 34 | 35 | [Test] 36 | public void XMLReader_WithDTDProcessingIgnored_Safe() 37 | { 38 | var exception = Assert.Throws(() => 39 | { 40 | AssertXXE.IsXMLParserSafe((string xml) => 41 | { 42 | XmlReaderSettings settings = new XmlReaderSettings(); 43 | settings.DtdProcessing = DtdProcessing.Ignore; 44 | settings.MaxCharactersFromEntities = 6000; 45 | 46 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) 47 | { 48 | XmlReader reader = XmlReader.Create(stream, settings); 49 | 50 | var xmlDocument = new XmlDocument(); 51 | xmlDocument.XmlResolver = new XmlUrlResolver(); 52 | xmlDocument.Load(reader); 53 | return xmlDocument.InnerText; 54 | } 55 | }, true); 56 | }); 57 | 58 | Assert.IsTrue(exception.Message.StartsWith("Reference to undeclared entity 'xxe'.")); 59 | } 60 | 61 | [Test] 62 | public void XMLReader_WithDTDProcessingProhibited_Safe() 63 | { 64 | var exception = Assert.Throws(() => 65 | { 66 | AssertXXE.IsXMLParserSafe((string xml) => 67 | { 68 | XmlReaderSettings settings = new XmlReaderSettings(); 69 | settings.DtdProcessing = DtdProcessing.Prohibit; 70 | settings.MaxCharactersFromEntities = 6000; 71 | 72 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) 73 | { 74 | XmlReader reader = XmlReader.Create(stream, settings); 75 | 76 | var xmlDocument = new XmlDocument(); 77 | xmlDocument.XmlResolver = new XmlUrlResolver(); 78 | xmlDocument.Load(reader); 79 | return xmlDocument.InnerText; 80 | } 81 | }, true); 82 | }); 83 | 84 | Assert.IsTrue(exception.Message.StartsWith("For security reasons DTD is prohibited in this XML document.")); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /XXE/test.php: -------------------------------------------------------------------------------- 1 | 0 ? $_GET['xml'] : 'No XML found'; 10 | 11 | $document = new DOMDocument(); 12 | $document->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD); 13 | $parsedDocument = simplexml_import_dom($document); 14 | 15 | echo $parsedDocument->content; 16 | -------------------------------------------------------------------------------- /XXE/test2.php: -------------------------------------------------------------------------------- 1 | loadXML($xmlfile, LIBXML_NOENT | LIBXML_DTDLOAD); 6 | $info = simplexml_import_dom($dom); 7 | $name = $info->name; 8 | $tel = $info->tel; 9 | $email = $info->email; 10 | $password = $info->password; 11 | 12 | echo "Sorry, $email is already registered!"; 13 | ?> 14 | -------------------------------------------------------------------------------- /XXE/xxe.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const libxmljs = require('libxml') 3 | const db = require('db'); 4 | const router = express.Router() 5 | 6 | router.post('/upload-products', (req, res) => { 7 | const XMLfile = req.files.products.data; 8 | const products = libxmljs.parseXmlString(XMLfile, {noent:true,noblanks:true}) 9 | 10 | products.root().childNodes().forEach(product => { 11 | let newProduct = new db.Product() 12 | newProduct.name = product.childNodes()[0].text() 13 | newProduct.description = product.childNodes()[3].text() 14 | newProduct.save() 15 | }); 16 | 17 | res.send('Thanks') 18 | }) 19 | 20 | module.exports = router 21 | -------------------------------------------------------------------------------- /XXE/xxe1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System; 3 | using System.Xml; 4 | 5 | namespace WebFox.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class XxeTest1 : ControllerBase 10 | { 11 | 12 | [HttpGet("{xmlString}")] 13 | public void DoXxe(String xmlString) 14 | { 15 | XmlDocument xmlDoc = new XmlDocument(); 16 | xmlDoc.LoadXml(xmlString); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Zip Traversal/myApp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.IO.Compression; 4 | 5 | namespace myApp 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | string zipPath = "/home/snoopy/extract/evil.zip"; 12 | Console.WriteLine("Enter Path of Zip File to extract:"); 13 | string zipPath = Console.ReadLine(); 14 | Console.WriteLine("Enter Path of Destination Folder"); 15 | string extractPath = Console.ReadLine(); 16 | 17 | using (ZipArchive archive = ZipFile.OpenRead(zipPath)) 18 | { 19 | foreach (ZipArchiveEntry entry in archive.Entries) 20 | { 21 | 22 | entry.ExtractToFile(Path.Combine(extractPath, entry.FullName)); 23 | Console.WriteLine(extractPath); 24 | } 25 | } 26 | } 27 | } 28 | } 29 | 30 | --------------------------------------------------------------------------------