Skip to content

Patchwork PR: Autofix #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 38 additions & 20 deletions html.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import serialize from 'serialize-javascript'
import DOMPurify from 'dompurify'

// @twreporter
import webfonts from '@twreporter/react-components/lib/text/utils/webfonts'
Expand All @@ -26,6 +27,36 @@ export default class Html extends PureComponent {
styleElement: PropTypes.arrayOf(PropTypes.element).isRequired,
helmet: PropTypes.object.isRequired,
}

// Add script loading function that will be called from script tag
static loadTypekit() {
const config = {
kitId: 'vlk1qbe',
scriptTimeout: 3000,
async: true
};
const d = document;
const h = d.documentElement;
const t = setTimeout(() => {
h.className = h.className.replace(/\bwf-loading\b/g, "") + " wf-inactive";
}, config.scriptTimeout);
const tk = d.createElement("script");
let f = false;
const s = d.getElementsByTagName("script")[0];
h.className += " wf-loading";
tk.src = 'https://use.typekit.net/' + config.kitId + '.js';
tk.async = true;
tk.onload = tk.onreadystatechange = function() {
const a = this.readyState;
if (f || (a && a !== "complete" && a !== "loaded")) return;
f = true;
clearTimeout(t);
try {
Typekit.load(config);
} catch (e) {}
};
s.parentNode.insertBefore(tk, s);
}
render() {
const {
contentMarkup,
Expand Down Expand Up @@ -110,34 +141,21 @@ export default class Html extends PureComponent {
{styleElement}
</head>
<body>
<div id="root" dangerouslySetInnerHTML={{ __html: contentMarkup }} />
<div id="root" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(contentMarkup) }} />
<script
defer
src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.zh-Hant-TW"
/>
<script
dangerouslySetInnerHTML={{
__html: `window.__REDUX_STATE__=${serialize(store.getState())};`,
}}
charSet="UTF-8"
/>
<script
id="initial-state"
type="application/json"
>{serialize(store.getState(), { isJSON: true })}</script>
<script src="/static/init-state.js"></script>
{_.map(scripts, (script, key) => (
<script src={script} key={'scripts' + key} charSet="UTF-8" />
))}
{scriptElement}
<script
dangerouslySetInnerHTML={{
__html: `(function(d) {
var config = {
kitId: 'vlk1qbe',
scriptTimeout: 3000,
async: true
},
h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s)
})(document);
`,
}}
/>
<script defer>{`(${Html.loadTypekit.toString()})();`}</script>
</body>
</html>
)
Expand Down
39 changes: 33 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
import requests
import subprocess
import re
import logging

def func_calls():
formats.get_format()
algorithms.HMACAlgorithm.prepare_key()
cli.VerifyOperation.perform_operation()
sessions.SessionRedirectMixin.resolve_redirects()

def validate_hostname(hostname):
"""Validate hostname using regex pattern."""
pattern = r'^[a-zA-Z0-9.-]+$'
return bool(re.match(pattern, hostname))

def safe_ping(hostname):
"""Execute ping command safely with input validation."""
if not validate_hostname(hostname):
logging.warning(f"Invalid hostname attempted: {hostname}")
raise ValueError("Invalid hostname. Only alphanumeric characters, dots, and hyphens are allowed.")

try:
logging.info(f"Executing ping command for hostname: {hostname}")
result = subprocess.call(['ping', hostname], shell=False)
return result
except Exception as e:
logging.error(f"Error executing ping command: {str(e)}")
raise

if __name__ == '__main__':
# Set up logging
logging.basicConfig(level=logging.INFO)

session = requests.Session()
proxies = {
'http': 'http://test:pass@localhost:8080',
Expand All @@ -18,9 +42,12 @@ def func_calls():
prep = req.prepare()
session.rebuild_proxies(prep, proxies)

# Introduce a command injection vulnerability
user_input = input("Enter a command to execute: ")
command = "ping " + user_input
subprocess.call(command, shell=True)

print("Command executed!")
# Execute ping command safely
try:
user_input = input("Enter a hostname to ping: ")
safe_ping(user_input)
print("Command executed successfully!")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")