File size: 20,555 Bytes
d38f080 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | #!/usr/bin/env python3
"""AppSecBench v1.1.0 — Ruby (Rails) and Scala (Spring Boot) snippet generator.
Compact, idiom-specific vulnerable/secure pairs for every catalog vulnerability.
Placeholders filled by generic_ruby_scala(): {p}=param, {tbl}=table, {ep}=endpoint,
{id}=identifier, {fn}=function name. All snippets are ORIGINAL.
"""
from __future__ import annotations
import random
from vuln_catalog import CATALOG_BY_NAME
FUNCS = ["process", "handle", "resolve", "doAction", "run", "execute", "load", "save", "update", "delete"]
def _pick(rng, seq):
return rng.choice(seq)
# (vuln, ruby_vuln, ruby_secure, scala_vuln, scala_secure)
RUBY_SCALA = [
("SQL Injection",
'def {fn}({p})\n # VULNERABLE: string interpolation into SQL\n User.find_by_sql("SELECT * FROM users WHERE name = \'#{params[:{p}]}\'")\nend',
'def {fn}({p})\n # SECURE: bound parameter\n User.where("name = ?", params[:{p}])\nend',
'def {fn}({p}: String): java.util.List[User] =\n // VULNERABLE: string concatenation\n jdbcTemplate.queryForList("SELECT * FROM users WHERE name = \'" + {p} + "\'")\n',
'def {fn}({p}: String): java.util.List[User] =\n // SECURE: parameterized query\n jdbcTemplate.queryForList("SELECT * FROM users WHERE name = ?", {p})\n'),
("Cross-Site Scripting",
'def {fn}\n # VULNERABLE: raw user input rendered\n @out = params[:{p}]\n render inline: @out\nend',
'def {fn}\n # SECURE: auto-escaped / html_escape\n @out = ERB::Util.html_escape(params[:{p}])\nend',
'def {fn}({p}: String): String =\n // VULNERABLE: raw into template model\n s"Hello ${{{p}}}"\n',
'def {fn}({p}: String): String =\n // SECURE: escaped output\n org.apache.commons.text.StringEscapeUtils.escapeHtml4({p})\n'),
("Server-Side Request Forgery",
'def {fn}\n # VULNERABLE: fetch arbitrary user URL\n uri = URI.parse(params[:{p}])\n Net::HTTP.get(uri)\nend',
'def {fn}\n # SECURE: allow-list of hosts\n host = URI.parse(params[:{p}]).host\n raise "blocked" unless %w[api.a.com].include?(host)\n Net::HTTP.get(URI.parse(params[:{p}]))\nend',
'def {fn}({p}: String): String =\n // VULNERABLE: fetch arbitrary URL\n scala.io.Source.fromURL({p}).mkString\n',
'def {fn}({p}: String): String =\n // SECURE: allow-list + private-network block\n if (Set("https://api.a.com").contains({p})) scala.io.Source.fromURL({p}).mkString else throw new SecurityException("blocked")\n'),
("Command Injection",
'def {fn}\n # VULNERABLE: shell with user input\n `ping -c 1 #{params[:{p}]}`\nend',
'def {fn}\n # SECURE: argument array, no shell\n system("ping", "-c", "1", params[:{p}])\nend',
'def {fn}({p}: String): Int =\n // VULNERABLE: shell interpolation\n import sys.process._\n s"ping -c 1 ${{{p}}}".!\n',
'def {fn}({p}: String): Int =\n // SECURE: argument vector\n Seq("ping", "-c", "1", {p}).!\n'),
("Path Traversal",
'def {fn}\n # VULNERABLE: user path joined to root\n send_file(Rails.root.join("public", params[:{p}]))\nend',
'def {fn}\n # SECURE: canonicalize + scope check\n p = File.expand_path(File.join("public", params[:{p}]))\n raise "bad" unless p.start_with?(Rails.root.join("public").to_s)\n send_file(p)\nend',
'def {fn}({p}: String): java.io.File =\n // VULNERABLE: join without canonicalization\n new java.io.File("uploads/" + {p})\n',
'def {fn}({p}: String): java.io.File =\n // SECURE: canonicalize and confine to base\n val f = java.nio.file.Paths.get("uploads", {p}).normalize\n if (f.startsWith(java.nio.file.Paths.get("uploads"))) f.toFile else throw new SecurityException("bad")\n'),
("XML External Entity",
'def {fn}(xml)\n # VULNERABLE: default parser resolves entities\n doc = Nokogiri::XML(xml)\n doc.xpath("//data").text\nend',
'def {fn}(xml)\n # SECURE: disable DTD / entities\n doc = Nokogiri::XML(xml) { |cfg| cfg.nonet; cfg.noent = false }\n doc.xpath("//data").text\nend',
'def {fn}(xml: String): String =\n // VULNERABLE: DOCTYPE allowed\n val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance\n val doc = factory.newDocumentBuilder.parse(new java.io.ByteArrayInputStream(xml.getBytes))\n doc.getElementsByTagName("data").item(0).getTextContent\n',
'def {fn}(xml: String): String =\n // SECURE: disallow DOCTYPE\n val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance\n factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)\n val doc = factory.newDocumentBuilder.parse(new java.io.ByteArrayInputStream(xml.getBytes))\n doc.getElementsByTagName("data").item(0).getTextContent\n'),
("Insecure Direct Object Reference",
'def {fn}\n # VULNERABLE: trust client id\n @doc = Document.find(params[:id])\nend',
'def {fn}\n # SECURE: scope to owner\n @doc = current_user.documents.find(params[:id])\nend',
'def {fn}(id: Long): Doc =\n // VULNERABLE: no ownership check\n docRepo.findById(id).get\n',
'def {fn}(id: Long): Doc =\n // SECURE: owner scoping\n docRepo.findByIdAndOwner(id, currentUser)\n'),
("Broken Access Control",
'def {fn}\n # VULNERABLE: no role check\n Admin::PanelController.new.index\nend',
'def {fn}\n # SECURE: authorize before action\n authorize! :admin, :panel\n Admin::PanelController.new.index\nend',
'def {fn}(): Unit =\n // VULNERABLE: no authorization\n adminService.deleteAll()\n',
'def {fn}(): Unit =\n // SECURE: role gate\n if (auth.hasRole("ADMIN")) adminService.deleteAll() else throw new SecurityException("no")\n'),
]
RUBY_SCALA += [
("Broken Authentication",
'def {fn}\n # VULNERABLE: plaintext compare\n user = User.find_by(name: params[:user])\n session[:uid] = user.id if user && user.pw == params[:pw]\nend',
'def {fn}\n # SECURE: bcrypt + lockout\n user = User.find_by(name: params[:user])\n if user && user.authenticate(params[:pw]) && !user.locked\n session[:uid] = user.id\n end\nend',
'def {fn}(user: String, pw: String): Unit =\n // VULNERABLE: plaintext compare\n val u = userRepo.findByName(user)\n if (u != null && u.pw == pw) session.put("uid", u.id)\n',
'def {fn}(user: String, pw: String): Unit =\n // SECURE: bcrypt + lockout\n val u = userRepo.findByName(user)\n if (u != null && u.locked == false && BCrypt.checkpw(pw, u.pw)) session.put("uid", u.id)\n'),
("Broken Authorization",
'def {fn}(doc)\n # VULNERABLE: no per-object authz\n doc.update(visible: true)\nend',
'def {fn}(doc)\n # SECURE: policy check\n authorize!(:update, doc)\n doc.update(visible: true)\nend',
'def {fn}(id: Long): Unit =\n // VULNERABLE: no authz\n docRepo.save(docRepo.findById(id).get.copy(visible = true))\n',
'def {fn}(id: Long): Unit =\n // SECURE: authz gate\n if (authz.can(currentUser, "update", id)) docRepo.save(docRepo.findById(id).get.copy(visible = true))\n'),
("JWT Vulnerabilities",
'def {fn}(token)\n # VULNERABLE: none alg / weak secret\n payload = JWT.decode(token, "secret", "none")\nend',
'def {fn}(token)\n # SECURE: verify HS256 + exp + aud\n payload = JWT.decode(token, Rails.application.secrets.jwt_secret, "HS256", verify_expiration: true)\nend',
'def {fn}(token: String): Claims =\n // VULNERABLE: no signature verify\n Jwts.parser.parseClaimsJwt(token).getBody\n',
'def {fn}(token: String): Claims =\n // SECURE: verify signature + exp\n Jwts.parser.setSigningKey(secret).parseClaimsJws(token).getBody\n'),
("OAuth Vulnerabilities",
'def {fn}\n # VULNERABLE: no redirect_uri validation\n redirect_to params[:redirect_uri]\nend',
'def {fn}\n # SECURE: allow-list redirect\n raise "bad" unless params[:redirect_uri].start_with?("https://app.example.com")\n redirect_to params[:redirect_uri]\nend',
'def {fn}(ru: String): Token =\n // VULNERABLE: no registered-uri check\n oauth.exchange(code, ru)\n',
'def {fn}(ru: String): Token =\n // SECURE: registered URI + PKCE\n if (registered.contains(ru)) oauth.exchange(code, ru, pkce) else throw new IllegalArgumentException()\n'),
("Session Management",
'def {fn}\n # VULNERABLE: session in URL / no rotation\n redirect_to "/home?sid=#{session.id}"\nend',
'def {fn}\n # SECURE: rotate on login, http-only cookie\n reset_session\n session[:uid] = current_user.id\nend',
'def {fn}(): Unit =\n // VULNERABLE: session id in URL\n redirect(s"/home?sid=${{session.getId}}")\n',
'def {fn}(): Unit =\n // SECURE: rotate + http-only\n session.invalidate(); val s = request.getSession(true); s.setAttribute("uid", uid)\n'),
("Cross-Site Request Forgery",
'def {fn}\n # VULNERABLE: no CSRF token\n # (Rails has per-form tokens by default; this disables it)\n skip_before_action :verify_authenticity_token\nend',
'def {fn}\n # SECURE: keep CSRF protection on\n protect_from_forgery with: :exception\nend',
'def {fn}(): Unit =\n // VULNERABLE: CSRF disabled\n // (Spring Security csrf().disable())\n "noop"\n',
'def {fn}(): Unit =\n // SECURE: CSRF enabled\n // (Spring Security http.csrf())\n "noop"\n'),
("Insecure File Upload",
'def {fn}\n # VULNERABLE: save by original name, no type check\n File.open(Rails.root.join("public", params[:file].original_filename), "wb") { |f| f.write(params[:file].read) }\nend',
'def {fn}\n # SECURE: random name + content-type allow-list\n ext = File.extname(params[:file].original_filename)\n raise "bad" unless %w[.png .jpg].include?(ext)\n File.open(Rails.root.join("public", SecureRandom.hex + ext), "wb") { |f| f.write(params[:file].read) }\nend',
'def {fn}(file: MultipartFile): Unit =\n // VULNERABLE: original filename, no check\n Files.copy(file.getInputStream, Paths.get("uploads/" + file.getOriginalFilename))\n',
'def {fn}(file: MultipartFile): Unit =\n // SECURE: random name + allow-list\n val ext = file.getOriginalFilename.split("\\.").last\n if (Set("png","jpg").contains(ext)) Files.copy(file.getInputStream, Paths.get("uploads/" + UUID.randomUUID + "." + ext)) else throw new SecurityException("bad")\n'),
]
RUBY_SCALA += [
("Insecure Deserialization",
'def {fn}(data)\n # VULNERABLE: Marshal.load on untrusted input\n Marshal.load(Base64.decode64(data))\nend',
'def {fn}(data)\n # SECURE: parse only expected shape (JSON)\n JSON.parse(data)\nend',
'def {fn}(data: String): Any =\n // VULNERABLE: Java deserialization\n new ObjectInputStream(new ByteArrayInputStream(Base64.getDecoder.decode(data))).readObject\n',
'def {fn}(data: String): Any =\n // SECURE: JSON only\n jackson.readValue(data, classOf[Map[String,Any]])\n'),
("Open Redirect",
'def {fn}\n # VULNERABLE: arbitrary redirect\n redirect_to params[:url]\nend',
'def {fn}\n # SECURE: allow-list host\n uri = URI.parse(params[:url])\n raise "bad" unless uri.host == "app.example.com"\n redirect_to params[:url]\nend',
'def {fn}(url: String): String =\n // VULNERABLE: arbitrary redirect\n "redirect:" + url\n',
'def {fn}(url: String): String =\n // SECURE: host allow-list\n if (new URI(url).getHost == "app.example.com") "redirect:" + url else throw new SecurityException("bad")\n'),
("Race Condition",
'def {fn}\n # VULNERABLE: check-then-act\n if !$used[params[:id]]\n $used[params[:id]] = true\n end\nend',
'def {fn}\n # SECURE: atomic DB update\n User.update_all(["used = true WHERE id = ? AND used = false", params[:id]])\nend',
'def {fn}(id: String): Unit =\n // VULNERABLE: check-then-act\n if (!used.contains(id)) used.add(id)\n',
'def {fn}(id: String): Unit =\n // SECURE: atomic update\n jdbcTemplate.update("UPDATE t SET used=true WHERE id=? AND used=false", id)\n'),
("Insecure Cryptography",
'def {fn}(data)\n # VULNERABLE: MD5 digest for integrity\n Digest::MD5.hexdigest(data)\nend',
'def {fn}(data)\n # SECURE: HMAC-SHA256 with secret\n OpenSSL::HMAC.hexdigest("SHA256", SECRET, data)\nend',
'def {fn}(data: String): String =\n // VULNERABLE: MD5\n java.security.MessageDigest.getInstance("MD5").digest(data.getBytes).map("%02x".format(_)).mkString\n',
'def {fn}(data: String): String =\n // SECURE: HMAC-SHA256\n import javax.crypto.Mac\n val m = Mac.getInstance("HmacSHA256"); m.init(secret); m.doFinal(data.getBytes).map("%02x".format(_)).mkString\n'),
("Hardcoded Secrets",
'SECRET = "sk_live_9f8a7b6c5d4e3f2a"\n\n# VULNERABLE: hardcoded key\n def {fn}(data)\n OpenSSL::HMAC.hexdigest("SHA256", SECRET, data)\nend',
'require "rails/application"\n# SECURE: read from env / secret store\n def {fn}(data)\n OpenSSL::HMAC.hexdigest("SHA256", ENV["SECRET"], data)\nend',
'val SECRET = "sk_live_9f8a7b6c5d4e3f2a"\n// VULNERABLE: hardcoded key\n def {fn}(data: String): String =\n mac(SECRET, data)\n',
'// SECURE: from env / vault\n def {fn}(data: String): String =\n mac(sys.env.get("SECRET").get, data)\n'),
("Business Logic",
'def {fn}(cart)\n # VULNERABLE: negative quantity accepted\n cart.items.each { |i| charge(i.price * i.qty) }\nend',
'def {fn}(cart)\n # SECURE: reject non-positive qty\n raise "bad" if cart.items.any? { |i| i.qty <= 0 }\n cart.items.each { |i| charge(i.price * i.qty) }\nend',
'def {fn}(cart: Cart): Unit =\n // VULNERABLE: negative qty accepted\n cart.items.foreach(i => charge(i.price * i.qty))\n',
'def {fn}(cart: Cart): Unit =\n // SECURE: reject non-positive qty\n if (cart.items.exists(_.qty <= 0)) throw new IllegalArgumentException() else cart.items.foreach(i => charge(i.price * i.qty))\n'),
]
RUBY_SCALA += [
("Missing Rate Limiting",
'def {fn}\n # VULNERABLE: no throttle\n login(params[:user], params[:pw])\nend',
'def {fn}\n # SECURE: rack-attack / throttle\n throttle("logins/ip", limit: 5, period: 60) { login(params[:user], params[:pw]) }\nend',
'def {fn}(ip: String): Unit =\n // VULNERABLE: no throttle\n login(ip)\n',
'def {fn}(ip: String): Unit =\n // SECURE: bucket4j rate limit\n if (limiter.tryConsume(ip)) login(ip) else throw new RateLimitExceeded("429")\n'),
("Sensitive Data Logging",
'def {fn}\n # VULNERABLE: logs secret\n Rails.logger.info("token=#{params[:token]}")\nend',
'def {fn}\n # SECURE: redact\n Rails.logger.info("token=REDACTED")\nend',
'def {fn}(token: String): Unit =\n // VULNERABLE: logs secret\n logger.info(s"token=$token")\n',
'def {fn}(token: String): Unit =\n // SECURE: redact\n logger.info("token=REDACTED")\n'),
("Header Injection",
'def {fn}\n # VULNERABLE: user input into header\n response.headers["X-User"] = params[:user]\nend',
'def {fn}\n # SECURE: validate / strip CRLF\n v = params[:user].gsub(/[\\r\\n]/, "")\n response.headers["X-User"] = v\nend',
'def {fn}(user: String): Unit =\n // VULNERABLE: CRLF in header\n response.setHeader("X-User", user)\n',
'def {fn}(user: String): Unit =\n // SECURE: strip CRLF\n response.setHeader("X-User", user.replaceAll("[\\r\\n]", ""))\n'),
("Prompt Injection",
'def {fn}(msg)\n # VULNERABLE: untrusted text into system prompt\n call_llm("You are helpful. User: #{msg}")\nend',
'def {fn}(msg)\n # SECURE: separate system vs user, delimit\n call_llm(system: "You are helpful.", user: msg)\nend',
'def {fn}(msg: String): String =\n // VULNERABLE: concat into prompt\n llm(s"System: helpful. User: $msg")\n',
'def {fn}(msg: String): String =\n // SECURE: separated channels\n llm(system = "helpful", user = msg)\n'),
("RAG Security",
'def {fn}(q)\n # VULNERABLE: query into retrieval + prompt untrusted\n ctx = db.similarity_search(q)\n call_llm(ctx + q)\nend',
'def {fn}(q)\n # SECURE: sanitize query, scope context, delimit\n call_llm(system: "Answer from context only.", user: sanitize(q), context: scoped(ctx))\nend',
'def {fn}(q: String): String =\n // VULNERABLE: untrusted into RAG prompt\n llm(retrieve(q) + q)\n',
'def {fn}(q: String): String =\n // SECURE: scope + delimit\n llm(system = "context only", context = scoped(retrieve(sanitize(q))))\n'),
]
# Infra + API/RPC vulns for Ruby/Scala reuse the generic text builder below.
def generic_ruby_scala(vuln, language, framework, difficulty, rng):
"""Return (vuln_code, secure_code, exploit) for Ruby or Scala."""
ep = _pick(rng, ["/api/x", "/v1/x", "/x", "/act"])
p = _pick(rng, ["id", "q", "name", "token", "url", "file"])
tbl = _pick(rng, ["users", "orders", "docs"])
fn = _pick(rng, FUNCS)
for name, rv, rs, sv, ss in RUBY_SCALA:
if name == vuln:
comment = "# " if language == "Ruby" else "// "
if language == "Ruby":
v = rv.replace("{fn}", fn).replace("{p}", p).replace("{tbl}", tbl).replace("{ep}", ep).replace("{id}", p)
s = rs.replace("{fn}", fn).replace("{p}", p).replace("{tbl}", tbl).replace("{ep}", ep).replace("{id}", p)
else:
v = sv.replace("{fn}", fn).replace("{p}", p).replace("{tbl}", tbl).replace("{ep}", ep).replace("{id}", p)
s = ss.replace("{fn}", fn).replace("{p}", p).replace("{tbl}", tbl).replace("{ep}", ep).replace("{id}", p)
return v, s, f"Trigger via {ep}?{p}=<malicious>."
# Infra / API-RPC classes: produce a concise, valid snippet per language.
if language == "Ruby":
if vuln == "GraphQL Security":
v = 'def {fn}\n # VULNERABLE: introspection + batching open\n MySchema.execute(params[:query])\nend'.replace("{fn}", fn)
s = 'def {fn}\n # SECURE: disable introspection in prod, cap depth\n MySchema.execute(params[:query], max_depth: 8)\nend'.replace("{fn}", fn)
elif vuln == "REST API Security":
v = 'def {fn}\n # VULNERABLE: no auth on endpoint\n render json: User.all\nend'.replace("{fn}", fn)
s = 'def {fn}\n # SECURE: before_action auth\n before_action :authenticate!\n render json: current_user.records\nend'.replace("{fn}", fn)
elif vuln == "gRPC Security":
v = 'def {fn}(req, ctx)\n # VULNERABLE: no authz\n GrpcServer.new.delete(req.id)\nend'.replace("{fn}", fn)
s = 'def {fn}(req, ctx)\n # SECURE: interceptor authz\n raise "forbidden" unless admin?(ctx)\n GrpcServer.new.delete(req.id)\nend'.replace("{fn}", fn)
elif vuln in ("Cloud Misconfiguration", "Kubernetes Security", "Docker Security"):
v = "# VULNERABLE: overly permissive config\n" + ("bucket.acl = 'public-read'" if vuln == "Cloud Misconfiguration" else "privileged: true")
s = "# SECURE: least privilege\n" + ("bucket.acl = 'private'" if vuln == "Cloud Misconfiguration" else "privileged: false\nreadOnlyRootFilesystem: true")
else:
v = f"# {vuln}: vulnerable pattern (Ruby)\nputs params[:{p}]"
s = f"# {vuln}: secure pattern (Ruby)\nputs sanitize(params[:{p}])"
else: # Scala
if vuln == "GraphQL Security":
v = 'def {fn}(q: String): Any =\n // VULNERABLE: introspection open\n executor.execute(q)\n'.replace("{fn}", fn)
s = 'def {fn}(q: String): Any =\n // SECURE: disable introspection + depth limit\n executor.execute(q, maxDepth = 8)\n'.replace("{fn}", fn)
elif vuln == "REST API Security":
v = 'def {fn}(): List[User] =\n // VULNERABLE: no auth\n userRepo.findAll()\n'.replace("{fn}", fn)
s = 'def {fn}(): List[User] =\n // SECURE: auth gate\n if (auth.authenticated) userRepo.findByOwner(currentUser) else throw new SecurityException("no")\n'.replace("{fn}", fn)
elif vuln == "gRPC Security":
v = 'def {fn}(req: Id): Unit =\n // VULNERABLE: no authz\n grpcServer.delete(req.id)\n'.replace("{fn}", fn)
s = 'def {fn}(req: Id): Unit =\n // SECURE: interceptor authz\n if (authz.can(currentUser, "delete")) grpcServer.delete(req.id)\n'.replace("{fn}", fn)
elif vuln in ("Cloud Misconfiguration", "Kubernetes Security", "Docker Security"):
v = "// VULNERABLE: overly permissive config\n" + ("bucket.setAcl(PUBLIC_READ)" if vuln == "Cloud Misconfiguration" else "privileged = true")
s = "// SECURE: least privilege\n" + ("bucket.setAcl(PRIVATE)" if vuln == "Cloud Misconfiguration" else "privileged = false\nreadOnlyRootFilesystem = true")
else:
v = f"// {vuln}: vulnerable pattern (Scala)\nprintln({p})"
s = f"// {vuln}: secure pattern (Scala)\nsanitize({p})"
return v, s, f"Trigger via {ep}."
|