├── Open Redirect ├── example1.php ├── example1.rb ├── koa.js ├── Remote Code Execution in apt-get └── redirect.js ├── Buffer Overflow ├── strcpy.c ├── example1.c ├── example2.c ├── sprintf.c ├── gets.c ├── bof1.c └── netkit-telnet 0.17.c ├── Denial Of Service ├── example2.c ├── example1.aspx.cs └── dos.js ├── Sensitive Data Exposure ├── hardcoded.ts ├── Railsgoatconfig.rb └── graphql.ts ├── README.md ├── Path Traversal ├── example2.php ├── example1.java ├── example3.java ├── PT1.cs ├── expresstest.js ├── bypass.php ├── PT4.cs ├── ZipTraversal.java ├── PT3.cs ├── phpexample.php ├── PT2.cs ├── ZipTraversalPatched.java ├── gq.js └── py_ctf.py ├── Connection String Injection ├── example1.c ├── example3.asp └── example2.java ├── Code Injection ├── example1.rb ├── eval.php └── eval2.php ├── Format String Attacks ├── FormatString.c └── vuln.c ├── Resource Injection └── example1.asp ├── LDAP Injection ├── example1.php ├── LDAP.cs └── example2.asp ├── ReDoS └── redos.js ├── PostMessage Security ├── challenge_2.js ├── challenge3.js └── challenge1.js ├── Server Side Template Injection ├── test.py ├── sstigolang.go ├── Twig.php └── asis_ssti_pt.py ├── Command Injection ├── tainted.py ├── cmd2.php ├── cmd1.php ├── cmd4.php ├── cmd3.php ├── OSI.cs ├── exec.js ├── cmd5.php ├── cmd6.php ├── CVE-2019-16662.php ├── Cryptolog.php └── CVE-2019-16663.php ├── PHP Object Injection ├── chall2.php ├── tarlogic1.php ├── chall1.php ├── tarlogic-ex1.php └── tarlogic-ex2.php ├── File Inclusion ├── lfi1.php ├── lfi6.php ├── lfi11.php ├── lfi12.php ├── lfi2.php ├── lfi4.php ├── lfi7.php ├── lfi9.php ├── lfi13.php ├── lfi3.php ├── lfi8.php ├── lfi14.php ├── lfi10.php └── lfi5.php ├── SQL Injection ├── sql.js ├── Cryptolog,php ├── example2.js └── SQLi.cs ├── Insecure File Uploads ├── example1.php ├── WishList.php ├── example2.php ├── example3.php └── Insomnihack_2019_l33t-hoster.php ├── Code Execution └── Discourse_SNS_webhook_RCE.rb ├── Log Forging └── logf.cs ├── Prototype Pollution └── lodash.js ├── IDOR └── example1.php ├── Integer Overflow └── damnvuln.c ├── Out of Bounds └── damnvuln.c ├── NoSQL Injection └── mongodb.js └── Authentication Bypass └── CVE-2019-1937 /Open Redirect/example1.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Open Redirect/example1.rb: -------------------------------------------------------------------------------- 1 | def legacy 2 | redirect_to(params.update(action:'main')) 3 | end 4 | -------------------------------------------------------------------------------- /Buffer Overflow/strcpy.c: -------------------------------------------------------------------------------- 1 | char str1[10]; 2 | char str2[]="abcdefghijklmn"; 3 | strcpy(str1,str2); 4 | -------------------------------------------------------------------------------- /Denial Of Service/example2.c: -------------------------------------------------------------------------------- 1 | int i; 2 | char inLine[64]; 3 | cin >> inLine; 4 | i = atoi (inLine); 5 | sleep(i); 6 | -------------------------------------------------------------------------------- /Sensitive Data Exposure/hardcoded.ts: -------------------------------------------------------------------------------- 1 | 2 | var password = 'mysecretpass'; 3 | 4 | const fooPassword = 'mysecretpass'; 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vulnerable-Code-Snippets 2 | 3 | 4 | **Checkout my Website:** https://bughuntar.com 5 | 6 | **Follow me on Twitter:** https://twitter.com/bughuntar 7 | -------------------------------------------------------------------------------- /Path Traversal/example2.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Path Traversal/example1.java: -------------------------------------------------------------------------------- 1 | def path = System.console().readLine 'Enter file path:' 2 | if (path.startsWith("/safe_dir/")) 3 | { 4 | File f = new File(path); 5 | f.delete() 6 | } 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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); -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LDAP Injection/example1.php: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Command Injection/cmd2.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 |
8 | 9 | -------------------------------------------------------------------------------- /File Inclusion/lfi1.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Command Injection/cmd1.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 |
9 | 10 |
11 | 12 | -------------------------------------------------------------------------------- /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 | }) -------------------------------------------------------------------------------- /File Inclusion/lfi6.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 |
11 | 12 | 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Command Injection/cmd4.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 |
8 | 9 |
10 | 
13 | 
-------------------------------------------------------------------------------- /File Inclusion/lfi2.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 13 | 14 | -------------------------------------------------------------------------------- /Command Injection/cmd3.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 |
9 | Whois: 10 |
11 | 12 |
13 | 
16 | 
-------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /File Inclusion/lfi4.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 14 | 15 | -------------------------------------------------------------------------------- /File Inclusion/lfi7.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 |
11 | 12 | 15 | 16 | -------------------------------------------------------------------------------- /File Inclusion/lfi9.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 14 | 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /File Inclusion/lfi13.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 21 | -------------------------------------------------------------------------------- /Path Traversal/bypass.php: -------------------------------------------------------------------------------- 1 | Your image was not uploaded.'; 12 | } 13 | else { 14 | // Yes! 15 | $html .= "
{$target_path} succesfully uploaded!
"; 16 | } 17 | } 18 | 19 | ?> 20 | -------------------------------------------------------------------------------- /File Inclusion/lfi3.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 12 | 18 | 19 | -------------------------------------------------------------------------------- /File Inclusion/lfi8.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 11 | 17 | 18 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /File Inclusion/lfi14.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 22 | -------------------------------------------------------------------------------- /File Inclusion/lfi10.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 |
9 | 10 | 21 | -------------------------------------------------------------------------------- /File Inclusion/lfi5.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 |
10 | 11 | 22 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Code Injection/eval2.php: -------------------------------------------------------------------------------- 1 | 2 | request->get("code"); 26 | eval($code); 27 | 28 | 29 | ?> 30 | -------------------------------------------------------------------------------- /Path Traversal/phpexample.php: -------------------------------------------------------------------------------- 1 | 2 | 36 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Command Injection/Cryptolog.php: -------------------------------------------------------------------------------- 1 | 40 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 |

    "; 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------