id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
12,700
test_favicon.py
buffer_thug/tests/functional/test_favicon.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestFavicon(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_ssl_verify() thug.set_json_logging() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_google(self, caplog): sample = os.path.join(self.misc_path, "testFavicon.html") expected = ["[Favicon] URL: https://www.google.com/favicon.ico"] self.do_perform_test(caplog, sample, expected)
976
Python
.py
25
30.84
72
0.630458
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,701
test_misc_ie60.py
buffer_thug/tests/functional/test_misc_ie60.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestMiscSamplesIE(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("winxpie60") thug.set_events("click") thug.set_connect_timeout(2) thug.disable_cert_logging() thug.set_features_logging() thug.set_ssl_verify() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_plugindetect1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, expected) def test_plugindetect2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html") expected = [ "AdobeReader version: 9,1,0,0", "Flash version: 10,0,64,0", "Java version: 1,6,0,32", "ActiveXObject: javawebstart.isinstalled.1.6.0.0", "ActiveXObject: javaplugin.160_32", ] self.do_perform_test(caplog, sample, expected) def test_test1(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected) def test_test2(self, caplog): sample = os.path.join(self.misc_path, "test2.html") expected = ["[Window] Alert Text: Java enabled: true"] self.do_perform_test(caplog, sample, expected) def test_test3(self, caplog): sample = os.path.join(self.misc_path, "test3.html") expected = ["[Window] Alert Text: foo"] self.do_perform_test(caplog, sample, expected) def test_testAppendChild(self, caplog): sample = os.path.join(self.misc_path, "testAppendChild.html") expected = [ "Don't care about me", "Just a sample", "Attempt to append a null element failed", "Attempt to append an invalid element failed", "Attempt to append a text element failed", "Attempt to append a read-only element failed", ] self.do_perform_test(caplog, sample, expected) def test_testClipboardData(self, caplog): sample = os.path.join(self.misc_path, "testClipboardData.html") expected = ["Test ClipboardData"] self.do_perform_test(caplog, sample, expected) def test_testCloneNode(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode.html") expected = [ '<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>' ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode2(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode2.html") expected = [ "[Window] Alert Text: [object HTMLButtonElement]", "[Window] Alert Text: Clone node", "[Window] Alert Text: None", "[Window] Alert Text: [object Attr]", "[Window] Alert Text: True", ] self.do_perform_test(caplog, sample, expected) def test_testCreateStyleSheet(self, caplog): sample = os.path.join(self.misc_path, "testCreateStyleSheet.html") expected = [ "[Window] Alert Text: style1.css", "[Window] Alert Text: style2.css", "[Window] Alert Text: style3.css", "[Window] Alert Text: style4.css", ] self.do_perform_test(caplog, sample, expected) def test_testCreateStyleSheetNoHead(self, caplog): sample = os.path.join(self.misc_path, "testCreateStyleSheetNoHead.html") expected = [ "[Window] Alert Text: [object HTMLStyleElement]", "[Window] Alert Text: [object HTMLLinkElement]", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentAll(self, caplog): sample = os.path.join(self.misc_path, "testDocumentAll.html") expected = ["http://www.google.com"] self.do_perform_test(caplog, sample, expected) def test_testDocumentWrite1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentWrite1.html") expected = [ "Foobar", "Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>", ] self.do_perform_test(caplog, sample, expected) def test_testInnerHTML(self, caplog): sample = os.path.join(self.misc_path, "testInnerHTML.html") expected = ["dude", "Fred Flinstone"] self.do_perform_test(caplog, sample, expected) def test_testInsertBefore(self, caplog): sample = os.path.join(self.misc_path, "testInsertBefore.html") expected = [ "<div>Just a sample</div><div>I'm your reference!</div></body></html>", "[ERROR] Attempting to insert null element", "[ERROR] Attempting to insert an invalid element", "[ERROR] Attempting to insert using an invalid reference element", "[ERROR] Attempting to insert a text node using an invalid reference element", ] self.do_perform_test(caplog, sample, expected) def test_testPlugins(self, caplog): sample = os.path.join(self.misc_path, "testPlugins.html") expected = [ "Shockwave Flash 10.0.64.0", "Windows Media Player 7", "Adobe Acrobat", ] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEdge(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEdge.html") expected = ["[Window] Alert Text: 7"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEmulateIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEmulateIE.html") expected = ["[Window] Alert Text: 7"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleIE.html") expected = ["[Window] Alert Text: 7"] self.do_perform_test(caplog, sample, expected) def test_testNode(self, caplog): sample = os.path.join(self.misc_path, "testNode.html") expected = ["thelink", "thediv"] self.do_perform_test(caplog, sample, expected) def test_testNode2(self, caplog): sample = os.path.join(self.misc_path, "testNode2.html") expected = ["thelink", "thediv2"] self.do_perform_test(caplog, sample, expected) def test_testScope(self, caplog): sample = os.path.join(self.misc_path, "testScope.html") expected = [ "foobar", "foo", "bar", "True", "3", "2012-10-07 11:13:00", "3.14159265359", "/foo/i", ] self.do_perform_test(caplog, sample, expected) def test_testSetInterval(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testText(self, caplog): sample = os.path.join(self.misc_path, "testText.html") expected = [ '<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>' ] self.do_perform_test(caplog, sample, expected) def test_testWindowOnload(self, caplog): sample = os.path.join(self.misc_path, "testWindowOnload.html") expected = ["[Window] Alert Text: Fired"] self.do_perform_test(caplog, sample, expected) def test_test_click(self, caplog): sample = os.path.join(self.misc_path, "test_click.html") expected = [ "[window open redirection] about:blank -> https://buffer.github.io/thug/" ] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML1(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html") expected = ['<div id="five">five</div><div id="one">one</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML2(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html") expected = ['<div id="two"><div id="six">six</div>two</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML3(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html") expected = ['<div id="three">three<div id="seven">seven</div></div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML4(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html") expected = ['<div id="four">four</div><div id="eight">eight</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML5(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html") expected = ["insertAdjacentHTML does not support notcorrect operation"] self.do_perform_test(caplog, sample, expected) def test_testCurrentScript(self, caplog): sample = os.path.join(self.misc_path, "testCurrentScript.html") expected = [ "[Window] Alert Text: This page has scripts", "[Window] Alert Text: text/javascript", "[Window] Alert Text: Just a useless script", ] self.do_perform_test(caplog, sample, expected) def test_testCCInterpreter(self, caplog): sample = os.path.join(self.misc_path, "testCCInterpreter.html") expected = [ "JavaScript version: 5.6", "Running on the 32-bit version of Windows", ] self.do_perform_test(caplog, sample, expected) def test_testTextNode(self, caplog): sample = os.path.join(self.misc_path, "testTextNode.html") expected = [ "nodeName: #text", "nodeType: 3", "Object: [object Text]", "nodeValue: Hello World", "Length: 11", "Substring(2,5): llo W", "New nodeValue (replace): HelloAWorld", "New nodeValue (delete 1): HelloWorld", "Index error (delete 2)", "New nodeValue (delete 3): Hello", "New nodeValue (append): Hello Test", "Index error (insert 1)", "New nodeValue (insert 2): Hello New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testCommentNode(self, caplog): sample = os.path.join(self.misc_path, "testCommentNode.html") expected = [ "nodeName: #comment", "nodeType: 8", "Object: [object Comment]", "nodeValue: <!--Hello World-->", "Length: 18", "Substring(2,5): --Hel", "New nodeValue (replace): <!--HAllo World-->", "New nodeValue (delete 1): <!--Hllo World-->", "Index error (delete 2)", "New nodeValue (delete 3): <!--H", "New nodeValue (append): <!--H Test", "Index error (insert 1)", "New nodeValue (insert 2): <!--H New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation.html") expected = [ "hasFeature('core'): true", ] self.do_perform_test(caplog, sample, expected) def test_testAttrNode(self, caplog): sample = os.path.join(self.misc_path, "testAttrNode.html") expected = [ "Object: [object Attr]", "nodeName: test", "nodeType: 2", "nodeValue: foo", "Length: undefined", "New nodeValue: test2", "Parent: null", "Owner: null", "Name: test", "Specified: true", "childNodes length: 0", ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild.html") expected = [ "firstChild: Old child", "lastChild: Old child", "innerText: Old child", "[ERROR] Attempting to replace with a null element", "[ERROR] Attempting to replace a null element", "[ERROR] Attempting to replace with an invalid element", "[ERROR] Attempting to replace an invalid element", "[ERROR] Attempting to replace on a read-only element failed", "Alert Text: New child", '<div id="foobar"><!--Just a comment--></div>', ] self.do_perform_test(caplog, sample, expected) def test_testCookie(self, caplog): sample = os.path.join(self.misc_path, "testCookie.html") expected = ["favorite_food=tripe", "name=oeschger"] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment1.html") expected = [ "<div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment2(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment2.html") expected = [ '<div id="foobar"><b>This is B</b></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentType(self, caplog): sample = os.path.join(self.misc_path, "testDocumentType.html") expected = [ "Doctype: [object DocumentType]", "Doctype name: html", "Doctype nodeName: html", "Doctype nodeType: 10", "Doctype nodeValue: null", "Doctype publicId: ", "Doctype systemId: ", "Doctype textContent: null", ] self.do_perform_test(caplog, sample, expected) def test_testRemoveChild(self, caplog): sample = os.path.join(self.misc_path, "testRemoveChild.html") expected = [ "<div>Don't care about me</div>", "[ERROR] Attempting to remove null element", "[ERROR] Attempting to remove an invalid element", "[ERROR] Attempting to remove a read-only element", "[ERROR] Attempting to remove an element not in the tree", "[ERROR] Attempting to remove from a read-only element", ] self.do_perform_test(caplog, sample, expected) def test_testNamedNodeMap(self, caplog): sample = os.path.join(self.misc_path, "testNamedNodeMap.html") expected = [ "hasAttributes (before removal): true", "hasAttribute('id'): true", "First test: id->p1", "Second test: id->p1", "Third test: id->p1", "Fourth test: id->p1", "Fifth test failed", "Not existing: null", "hasAttributes (after removal): false", "Sixth test: foo->bar", "Seventh test: foo->bar2", "Final attributes length: 1", ] self.do_perform_test(caplog, sample, expected) def test_testEntityReference(self, caplog): sample = os.path.join(self.misc_path, "testEntityReference.html") expected = [ "node: [object EntityReference]", "name: &", "nodeName: &", "nodeType: 5", "nodeValue: null", ] self.do_perform_test(caplog, sample, expected) def test_getElementsByTagName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByTagName.html") expected = [ "[object HTMLHtmlElement]", "[object HTMLHeadElement]", "[object HTMLBodyElement]", "[object HTMLParagraphElement]", "[object HTMLScriptElement]", ] self.do_perform_test(caplog, sample, expected) def test_createElement(self, caplog): sample = os.path.join(self.misc_path, "testCreateElement.html") expected = ["[object HTMLParagraphElement]"] self.do_perform_test(caplog, sample, expected) def test_testDocumentElement(self, caplog): sample = os.path.join(self.misc_path, "testDocumentElement.html") expected = ['<a href="http://www.google.com">Google</a>'] self.do_perform_test(caplog, sample, expected) def test_testGetAttribute2(self, caplog): sample = os.path.join(self.misc_path, "testGetAttribute2.html") expected = ["[Window] Alert Text: https://buffer.github.io/thug/notexists.html"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute1(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute1.html") expected = ["Attribute: bar", "Attribute (after removal): null"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute3(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute3.html") expected = [ "Alert Text: foo", "Alert Text: bar", "Alert Text: test", "Alert Text: foobar", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLCollection.html") expected = [ '<div id="odiv1">Page one</div>', '<div name="odiv2">Page two</div>', ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation2(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation2.html") expected = [ "Element #1: [object HTMLHeadElement]", "Element #2: [object HTMLLinkElement]", "Element #3: [object HTMLTitleElement]", "Element #4: [object HTMLMetaElement]", "Element #5: [object HTMLBaseElement]", "Element #6: [object HTMLIsIndexElement]", "Element #7: [object HTMLStyleElement]", "Element #8: [object HTMLFormElement]", "Element #9: [object HTMLSelectElement]", "Element #10: [object HTMLOptGroupElement]", "Element #11: [object HTMLOptionElement]", "Element #12: [object HTMLInputElement]", "Element #13: [object HTMLTextAreaElement]", "Element #14: [object HTMLButtonElement]", "Element #15: [object HTMLLabelElement]", "Element #16: [object HTMLFieldSetElement]", "Element #17: [object HTMLLegendElement]", "Element #18: [object HTMLUListElement]", "Element #19: [object HTMLOListElement]", "Element #20: [object HTMLDListElement]", "Element #21: [object HTMLDirectoryElement]", "Element #22: [object HTMLMenuElement]", "Element #23: [object HTMLLIElement]", "Element #24: [object HTMLDivElement]", "Element #25: [object HTMLParagraphElement]", "Element #26: [object HTMLHeadingElement]", "Element #27: [object HTMLHeadingElement]", "Element #28: [object HTMLHeadingElement]", "Element #29: [object HTMLHeadingElement]", "Element #30: [object HTMLHeadingElement]", "Element #31: [object HTMLHeadingElement]", "Element #32: [object HTMLQuoteElement]", "Element #33: [object HTMLQuoteElement]", "Element #34: [object HTMLSpanElement]", "Element #35: [object HTMLPreElement]", "Element #36: [object HTMLBRElement]", "Element #37: [object HTMLBaseFontElement]", "Element #38: [object HTMLFontElement]", "Element #39: [object HTMLHRElement]", "Element #40: [object HTMLModElement]", "Element #41: [object HTMLModElement]", "Element #42: [object HTMLAnchorElement]", "Element #43: [object HTMLObjectElement]", "Element #44: [object HTMLParamElement]", "Element #45: [object HTMLImageElement]", "Element #46: [object HTMLAppletElement]", "Element #47: [object HTMLScriptElement]", "Element #48: [object HTMLFrameSetElement]", "Element #49: [object HTMLFrameElement]", "Element #50: [object HTMLIFrameElement]", "Element #51: [object HTMLTableElement]", "Element #52: [object HTMLTableCaptionElement]", "Element #53: [object HTMLTableColElement]", "Element #54: [object HTMLTableColElement]", "Element #55: [object HTMLTableSectionElement]", "Element #56: [object HTMLTableSectionElement]", "Element #57: [object HTMLTableSectionElement]", "Element #58: [object HTMLTableRowElement]", "Element #59: [object HTMLTableCellElement]", "Element #60: [object HTMLTableCellElement]", "Element #61: [object HTMLMediaElement]", "Element #62: [object HTMLElement]", "Element #63: [object HTMLHtmlElement]", "Element #64: [object HTMLBodyElement]", ] self.do_perform_test(caplog, sample, expected) def test_testApplyElement(self, caplog): sample = os.path.join(self.misc_path, "testApplyElement.html") expected = [ '<div id="outer"><div id="test"><div>Just a sample</div></div></div>', '<div id="outer"><div>Just a div<div id="test"><div>Just a sample</div></div></div></div>', ] self.do_perform_test(caplog, sample, expected) def test_testWindow(self, caplog): sample = os.path.join(self.misc_path, "testWindow.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testObject1(self, caplog): sample = os.path.join(self.misc_path, "testObject1.html") expected = [ "[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf" ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild2(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild2.html") expected = ['<div id="foobar"><div id="test"></div></div>'] self.do_perform_test(caplog, sample, expected) def test_testNavigator(self, caplog): sample = os.path.join(self.misc_path, "testNavigator.html") expected = [ "window: [object Window]", "appCodeName: Mozilla", "appName: Microsoft Internet Explorer", "appVersion: 4.0 (Windows; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)", "cookieEnabled: true", "onLine: true", "platform: Win32", ] self.do_perform_test(caplog, sample, expected) def test_testAdodbStream(self, caplog): sample = os.path.join(self.misc_path, "testAdodbStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)", "[Window] Alert Text: Stream content: Test", "[Window] Alert Text: Stream content (first 2 chars): Te", "[Window] Alert Text: Stream size: 4", "[Adodb.Stream ActiveX] SaveToFile(test.txt, 2)", "[Adodb.Stream ActiveX] LoadFromFile(test1234.txt)", "[Window] Alert Text: Attempting to load from a not existing file", "[Adodb.Stream ActiveX] LoadFromFile(test.txt)", "[Window] Alert Text: ReadText: Test", "[Window] Alert Text: ReadText(3): Tes", "[Window] Alert Text: ReadText(10): Test", "[Adodb.Stream ActiveX] Changed position in fileobject to: (2)", "[Window] Alert Text: stTest2", "[Adodb.Stream ActiveX] Close", ] self.do_perform_test(caplog, sample, expected) def test_testScriptingFileSystemObject(self, caplog): sample = os.path.join(self.misc_path, "testScriptingFileSystemObject.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS for GetSpecialFolder("0")', '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS\\system32 for GetSpecialFolder("1")', '[WScript.Shell ActiveX] Expanding environment string "%TEMP%"', "[Window] Alert Text: FolderExists('C:\\Windows\\System32'): true", "[Window] Alert Text: FileExists(''): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\drivers\\etc\\hosts'): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", '[Window] Alert Text: GetExtensionName("C:\\Windows\\System32\\test.txt"): .txt', "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", "[Window] Alert Text: [After CopyFile] FileExists('C:\\Windows\\System32\\test2.txt'): true", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test2.txt'): false", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test3.txt'): true", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLOptionsCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html") expected = [ "length: 4", "item(0): Volvo", "namedItem('audi'): Audi", "namedItem('mercedes').value: mercedes", "[After remove] item(0): Saab", "[After first add] length: 4", "[After first add] item(3): foobar", "[After second add] length: 5", "[After second add] item(3): test1234", "Not found error", ] self.do_perform_test(caplog, sample, expected) def test_testTextStream(self, caplog): sample = os.path.join(self.misc_path, "testTextStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] CreateTextFile("test.txt", "False", "False")', "[After first write] ReadAll: foobar", "[After first write] Line: 1", "[After first write] Column: 7", "[After first write] AtEndOfLine: true", "[After first write] AtEndOfStream: true", "[After second write] Line: 2", "[After second write] Column: 1", "[After second write] AtEndOfLine: false", "[After second write] AtEndOfStream: false", "[After third write] Line: 5", "[After third write] Column: 16", "[After third write] AtEndOfLine: false", "[After third write] AtEndOfStream: false", "[After fourth write] Line: 6", "[After fourth write] Column: 1", "[After fourth write] AtEndOfLine: false", "[After fourth write] AtEndOfStream: false", "[After fourth write] First char: s", "[After fourth write] Second char: o", "[After fourth write] Third char: m", "[After fourth write] Line: some other textnext line", "[After skip] Read(5): ttest", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAnchorElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html") expected = [ "a.protocol: https:", "a.host: www.example.com:1234", "a.hostname: www.example.com", "a.port: 1234", "b.protocol: :", "b.host: ", "b.hostname: ", "b.port: ", "c.protocol: https:", "c.host: www.example.com", "c.hostname: www.example.com", "c.port: ", "e.pathname: /foo/index.html", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLTableElement3(self, caplog): sample = os.path.join(self.misc_path, "testHTMLTableElement3.html") expected = [ "tHead: [object HTMLTableSectionElement]", "tFoot: [object HTMLTableSectionElement]", "caption: [object HTMLTableCaptionElement]", "row: [object HTMLTableRowElement]", "tBodies: [object HTMLCollection]", "cell: [object HTMLTableCellElement]", "cell.innerHTML: New cell 1", "row.deleteCell(10) failed", "row.deleteCell(20) failed", ] self.do_perform_test(caplog, sample, expected) def test_testTextArea(self, caplog): sample = os.path.join(self.misc_path, "testTextArea.html") expected = ["type: textarea", "cols: 100", "rows: 25"] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocument.html") expected = [ "document.title: Test", "document.title: Foobar", "anchors: [object HTMLCollection]", "anchors length: 1", "anchors[0].name: foobar", "applets: [object HTMLCollection]", "applets length: 2", "applets[0].code: HelloWorld.class", "links: [object HTMLCollection]", "links length: 1", "links[0].href: https://github.com/buffer/thug/", "images: [object HTMLCollection]", "images length: 1", "images[0].href: test.jpg", "disabled: false", "head: [object HTMLHeadElement]", "referrer: ", "URL: about:blank", "Alert Text: Hello, world", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLFormElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLFormElement.html") expected = [ "[object HTMLFormElement]", "f.elements: [object HTMLFormControlsCollection]", "f.length: 4", "f.name: [object HTMLFormControlsCollection]", "f.acceptCharset: ", "f.action: /cgi-bin/test", "f.enctype: application/x-www-form-urlencoded", "f.encoding: application/x-www-form-urlencoded", "f.method: POST", "f.target: ", ] self.do_perform_test(caplog, sample, expected) def test_testFile(self, caplog): sample = os.path.join(self.misc_path, "testFile.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] GetFile("D:\\ Program Files\\ Common Files\\test.txt")', "[File ActiveX] Path = D:\\ Program Files\\ Common Files\\test.txt, Attributes = 32", "Drive (test.txt): D:", "ShortPath (test.txt): D:\\\\ Progr~1\\\\ Commo~1\\\\test.txt", "ShortName (test.txt): test.txt", "Attributes: 1", '[Scripting.FileSystemObject ActiveX] GetFile("test2.txt")', "[File ActiveX] Path = test2.txt, Attributes = 32", "Drive (test2.txt): C:", "ShortPath (test2.txt): test2.txt", "ShortName (test2.txt): test2.txt", "Copy(test3.txt, True)", "Move(test4.txt)", "Delete(False)", "OpenAsTextStream(ForReading, 0)", ] self.do_perform_test(caplog, sample, expected) def test_testWScriptNetwork(self, caplog): sample = os.path.join(self.misc_path, "testWScriptNetwork.html") expected = [ "[WScript.Network ActiveX] Got request to PrinterConnections", "[WScript.Network ActiveX] Got request to EnumNetworkDrives", '[WScript.Shell ActiveX] Expanding environment string "%USERDOMAIN%"', '[WScript.Shell ActiveX] Expanding environment string "%USERNAME%"', '[WScript.Shell ActiveX] Expanding environment string "%COMPUTERNAME%"', ] self.do_perform_test(caplog, sample, expected) def test_testApplet(self, caplog): sample = os.path.join(self.misc_path, "testApplet.html") expected = ["[applet redirection]"] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement.html") expected = [ "src (before changes): test.jpg", "src (after first change): test2.jpg", "onerror handler fired", ] self.do_perform_test(caplog, sample, expected) def test_testTitle(self, caplog): sample = os.path.join(self.misc_path, "testTitle.html") expected = ["New title: Foobar"] self.do_perform_test(caplog, sample, expected) def test_UserProfile(self, caplog): sample = os.path.join(self.misc_path, "testUserProfile.html") expected = ["Test 1", "Test 2"] self.do_perform_test(caplog, sample, expected) def test_testCSSStyleDeclaration(self, caplog): sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html") expected = [ "style: [object CSSStyleDeclaration]", "length: 1", "cssText: color: blue;", "color: blue", "item(0): color", "item(100):", "getPropertyValue('color'): blue", "length (after removeProperty): 0", "cssText: foo: bar;", ] self.do_perform_test(caplog, sample, expected) def test_testFormProperty(self, caplog): sample = os.path.join(self.misc_path, "testFormProperty.html") expected = ["[object HTMLFormElement]", "formA"] self.do_perform_test(caplog, sample, expected) def test_testVBScript(self, caplog): sample = os.path.join(self.misc_path, "testVBScript.html") expected = ["[VBS embedded URL redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule1(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule1.html") expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule2(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule2.html") expected = [ "[font face redirection]", "https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf", ] self.do_perform_test(caplog, sample, expected) def test_testSilverLight(self, caplog): sample = os.path.join(self.misc_path, "testSilverLight.html") expected = [ "[SilverLight] isVersionSupported('4.0')", "Version 4.0 supported: true", ] self.do_perform_test(caplog, sample, expected) def test_testMSXML2Document(self, caplog): sample = os.path.join(self.misc_path, "testMSXML2Document.html") expected = [ "[MSXML2.DOMDocument] Microsoft XML Core Services MSXML Uninitialized Memory Corruption", "CVE-2012-1889", ] self.do_perform_test(caplog, sample, expected) def test_testExternal(self, caplog): sample = os.path.join(self.misc_path, "testExternal.html") expected = [] self.do_perform_test(caplog, sample, expected) def test_testClearTimeout2(self, caplog): sample = os.path.join(self.misc_path, "testClearTimeout2.html") expected = ["Alert Text: 0"] self.do_perform_test(caplog, sample, expected) def test_testGetElementById(self, caplog): sample = os.path.join(self.misc_path, "testGetElementById.html") expected = ["[object HTMLDivElement]"] self.do_perform_test(caplog, sample, expected)
37,508
Python
.py
782
37.297954
153
0.600602
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,702
test_webtracking.py
buffer_thug/tests/functional/test_webtracking.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestWebTracking(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, url, expected, type_="remote"): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.set_web_tracking() thug.enable_cert_logging() thug.set_features_logging() thug.set_log_verbose() thug.set_ssl_verify() thug.log_init(url) m = getattr(thug, "run_{}".format(type_)) m(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_sessionstorage(self, caplog): expected = [ "[TRACKING] [[object Storage] setItem] key1 = value1", "[TRACKING] [[object Storage] setItem] key2 = value2", "[TRACKING] [[object Storage] setItem] key2 = value3", "[TRACKING] [[object Storage] clear]", "[TRACKING] [[object Storage] setItem] key123 = value123", "[TRACKING] [[object Storage] removeItem] key123", ] sample = os.path.join(self.misc_path, "testSessionStorage.html") self.do_perform_test(caplog, sample, expected, "local") def test_cookie_1(self, caplog): expected = ["Domain starting with initial dot: .youtube.com", "Secure flag set"] self.do_perform_test(caplog, "https://www.youtube.com", expected) def test_cookie_2(self, caplog): expected = [] self.do_perform_test(caplog, "http://www.antifork.org", expected)
1,871
Python
.py
43
34.534884
88
0.612796
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,703
test_pyhooks.py
buffer_thug/tests/functional/test_pyhooks.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestPyHooks(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") exploits_path = os.path.join(cwd_path, os.pardir, "samples/exploits") signatures_path = os.path.join(cwd_path, os.pardir, "signatures") def do_handle_params_hook(self, params): for name, value in params.items(): log.warning("name = %s", name) log.warning("value = %s", value) def log_classifier_hook(self, classifier, url, rule, tags, meta): log.warning("Greetings from the hook") log.warning("classifier = %s", classifier) log.warning("url = %s", url) log.warning("rule = %s", rule) log.warning("tags = %s", tags) log.warning("meta = %s", meta) def do_perform_test(self, caplog, url, expected, type_="local"): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_features_logging() thug.set_ssl_verify() thug.set_connect_timeout(1) thug.add_urlclassifier( os.path.join(self.signatures_path, "url_signature_13.yar") ) thug.register_pyhook("DFT", "do_handle_params", self.do_handle_params_hook) thug.register_pyhook("ThugLogging", "log_classifier", self.log_classifier_hook) thug.log_init(url) m = getattr(thug, "run_{}".format(type_)) m(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_hook_1(self, caplog): expected = ["name = codebase", "value = /external/examples/common/java/"] sample = os.path.join(self.misc_path, "testObject2.html") self.do_perform_test(caplog, sample, expected, "local") def test_hook_2(self, caplog): expected = [ "Greetings from the hook", "classifier = exploit", "rule = CVE-2007-0018", ] sample = os.path.join(self.exploits_path, "22196.html") self.do_perform_test(caplog, sample, expected, "local") def test_hook_3(self, caplog): expected = [ "Greetings from the hook", "classifier = url", "url = https://buffer.antifork.org", "rule = url_signature_13", ] url = "https://buffer.antifork.org" self.do_perform_test(caplog, url, expected, "remote")
2,647
Python
.py
62
33.645161
87
0.601715
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,704
test_misc_ie90.py
buffer_thug/tests/functional/test_misc_ie90.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestMiscSamplesIE(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected, nofetch=False): xmlhttp = getattr(log, "XMLHTTP", None) if xmlhttp: delattr(log, "XMLHTTP") thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.set_connect_timeout(2) thug.disable_cert_logging() thug.set_ssl_verify() thug.set_features_logging() if nofetch: thug.set_no_fetch() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_plugindetect1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, expected) def test_plugindetect2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html") expected = [ "AdobeReader version: 9,1,0,0", "Flash version: 10,0,64,0", "Java version: 1,6,0,32", "ActiveXObject: javawebstart.isinstalled.1.6.0.0", "ActiveXObject: javaplugin.160_32", ] self.do_perform_test(caplog, sample, expected) def test_test1(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected) def test_test2(self, caplog): sample = os.path.join(self.misc_path, "test2.html") expected = ["[Window] Alert Text: Java enabled: true"] self.do_perform_test(caplog, sample, expected) def test_test3(self, caplog): sample = os.path.join(self.misc_path, "test3.html") expected = ["[Window] Alert Text: foo"] self.do_perform_test(caplog, sample, expected) def test_test4(self, caplog): sample = os.path.join(self.misc_path, "test4.js") expected = ["[Window] Alert Text: Test"] self.do_perform_test(caplog, sample, expected) def test_testAppendChild(self, caplog): sample = os.path.join(self.misc_path, "testAppendChild.html") expected = [ "Don't care about me", "Just a sample", "Attempt to append a null element failed", "Attempt to append an invalid element failed", "Attempt to append a text element failed", "Attempt to append a read-only element failed", ] self.do_perform_test(caplog, sample, expected) def test_testClipboardData(self, caplog): sample = os.path.join(self.misc_path, "testClipboardData.html") expected = ["Test ClipboardData"] self.do_perform_test(caplog, sample, expected) def test_testCloneNode(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode.html") expected = [ '<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>' ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode2(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode2.html") expected = [ "[Window] Alert Text: [object HTMLButtonElement]", "[Window] Alert Text: Clone node", "[Window] Alert Text: None", "[Window] Alert Text: [object Attr]", "[Window] Alert Text: True", ] self.do_perform_test(caplog, sample, expected) def test_testCreateHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html") expected = [ "[object HTMLDocument]", "[object HTMLBodyElement]", "<p>This is a new paragraph.</p>", ] self.do_perform_test(caplog, sample, expected) def test_testCreateStyleSheet(self, caplog): sample = os.path.join(self.misc_path, "testCreateStyleSheet.html") expected = [ "[Window] Alert Text: style1.css", "[Window] Alert Text: style2.css", "[Window] Alert Text: style3.css", "[Window] Alert Text: style4.css", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentAll(self, caplog): sample = os.path.join(self.misc_path, "testDocumentAll.html") expected = ["http://www.google.com"] self.do_perform_test(caplog, sample, expected) def test_testDocumentWrite1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentWrite1.html") expected = [ "Foobar", "Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>", ] self.do_perform_test(caplog, sample, expected) def test_testExternalSidebar(self, caplog): sample = os.path.join(self.misc_path, "testExternalSidebar.html") expected = ["[Window] Alert Text: Internet Explorer >= 7.0 or Chrome"] self.do_perform_test(caplog, sample, expected) def test_testGetElementsByClassName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByClassName.html") expected = ["First", "Hello World!", "Second"] self.do_perform_test(caplog, sample, expected) def test_testInnerHTML(self, caplog): sample = os.path.join(self.misc_path, "testInnerHTML.html") expected = ["dude", "Fred Flinstone"] self.do_perform_test(caplog, sample, expected) def test_testInsertBefore(self, caplog): sample = os.path.join(self.misc_path, "testInsertBefore.html") expected = [ "<div>Just a sample</div><div>I'm your reference!</div></body></html>", "[ERROR] Attempting to insert null element", "[ERROR] Attempting to insert an invalid element", "[ERROR] Attempting to insert using an invalid reference element", "[ERROR] Attempting to insert a text node using an invalid reference element", ] self.do_perform_test(caplog, sample, expected) def test_testLocalStorage(self, caplog): sample = os.path.join(self.misc_path, "testLocalStorage.html") expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"] self.do_perform_test(caplog, sample, expected) def test_testPlugins(self, caplog): sample = os.path.join(self.misc_path, "testPlugins.html") expected = [ "Shockwave Flash 10.0.64.0", "Windows Media Player 7", "Adobe Acrobat", ] self.do_perform_test(caplog, sample, expected) def test_testLocation1(self, caplog): sample = os.path.join(self.misc_path, "testLocation1.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation1_nofetch(self, caplog): sample = os.path.join(self.misc_path, "testLocation1.html") expected = [ "Content-Location: about:blank --> Location: https://buffer.github.io/thug/" ] self.do_perform_test(caplog, sample, expected, nofetch=True) def test_testLocation2(self, caplog): sample = os.path.join(self.misc_path, "testLocation2.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation3(self, caplog): sample = os.path.join(self.misc_path, "testLocation3.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation4(self, caplog): sample = os.path.join(self.misc_path, "testLocation4.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation5(self, caplog): sample = os.path.join(self.misc_path, "testLocation5.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation6(self, caplog): sample = os.path.join(self.misc_path, "testLocation6.html") expected = [ "[HREF Redirection (document.location)]", "Content-Location: about:blank --> Location: https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testLocation7(self, caplog): sample = os.path.join(self.misc_path, "testLocation7.html") expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org" ] self.do_perform_test(caplog, sample, expected) def test_testLocation8(self, caplog): sample = os.path.join(self.misc_path, "testLocation8.html") expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org" ] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEdge(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEdge.html") expected = ["[Window] Alert Text: 9"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEmulateIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEmulateIE.html") expected = ["[Window] Alert Text: 8"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleIE.html") expected = ["[Window] Alert Text: 9"] self.do_perform_test(caplog, sample, expected) def test_testNode(self, caplog): sample = os.path.join(self.misc_path, "testNode.html") expected = ["thelink", "thediv"] self.do_perform_test(caplog, sample, expected) def test_testNode2(self, caplog): sample = os.path.join(self.misc_path, "testNode2.html") expected = ["thelink", "thediv2"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector.html") expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector2(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector2.html") expected = ["CoursesWeb.net", "MarPlo.net", "php.net"] self.do_perform_test(caplog, sample, expected) def test_testScope(self, caplog): sample = os.path.join(self.misc_path, "testScope.html") expected = [ "foobar", "foo", "bar", "True", "3", "2012-10-07 11:13:00", "3.14159265359", "/foo/i", ] self.do_perform_test(caplog, sample, expected) def test_testSessionStorage(self, caplog): sample = os.path.join(self.misc_path, "testSessionStorage.html") expected = ["key1", "key2", "value1", "value3"] self.do_perform_test(caplog, sample, expected) def test_testSetInterval(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testSetInterval2(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval2.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testText(self, caplog): sample = os.path.join(self.misc_path, "testText.html") expected = [ '<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>' ] self.do_perform_test(caplog, sample, expected) def test_testWindowOnload(self, caplog): sample = os.path.join(self.misc_path, "testWindowOnload.html") expected = ["[Window] Alert Text: Fired"] self.do_perform_test(caplog, sample, expected) def test_test_click(self, caplog): sample = os.path.join(self.misc_path, "test_click.html") expected = [ "[window open redirection] about:blank -> https://buffer.github.io/thug/" ] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML1(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html") expected = ['<div id="five">five</div><div id="one">one</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML2(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html") expected = ['<div id="two"><div id="six">six</div>two</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML3(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html") expected = ['<div id="three">three<div id="seven">seven</div></div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML4(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html") expected = ['<div id="four">four</div><div id="eight">eight</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML5(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html") expected = ["insertAdjacentHTML does not support notcorrect operation"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent1(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent1.html") expected = ["[Window] Alert Text: Request completed"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent2(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent2.html") expected = ["[Window] Alert Text: Request completed"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent3(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent3.html") expected = [ "LoadLibraryA", "URLDownloadToFile", "http://www.360.cn.sxxsnp2.cn/d5.css", "WinExec", "U.exe", "ExitProcess", ] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent4(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent4.html") expected = [ "[Microsoft XMLHTTP ActiveX] open('POST', 'http://192.168.1.100', True, 'foo', 'bar')", "[Microsoft XMLHTTP ActiveX] send('TEST')", ] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent5(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent5.html") expected = ["[Window] Alert Text: Request completed", "[JNLP Detected]"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent6(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent6.html") expected = ["[Window] Alert Text: Request completed", "[JSON redirection]"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent7(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent7.html") expected = ["[Window] Alert Text: Request completed"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent8(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent8.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent9(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent9.html") expected = ["[Window] Alert Text: Request completed"] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLHTTPEvent10(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLHTTPEvent10.html") expected = ["<title>Antifork Research, Inc.</title>"] self.do_perform_test(caplog, sample, expected) def test_testCurrentScript(self, caplog): sample = os.path.join(self.misc_path, "testCurrentScript.html") expected = [ "[Window] Alert Text: This page has scripts", "[Window] Alert Text: text/javascript", "[Window] Alert Text: Just a useless script", ] self.do_perform_test(caplog, sample, expected) def test_testFormSubmit(self, caplog): sample = os.path.join(self.misc_path, "testFormSubmit.html") expected = ["[form redirection] about:blank -> https://www.antifork.org"] self.do_perform_test(caplog, sample, expected) def test_testCCInterpreter(self, caplog): sample = os.path.join(self.misc_path, "testCCInterpreter.html") expected = ["JavaScript version: 9", "Running on the 32-bit version of Windows"] self.do_perform_test(caplog, sample, expected) def test_testTextNode(self, caplog): sample = os.path.join(self.misc_path, "testTextNode.html") expected = [ "nodeName: #text", "nodeType: 3", "Object: [object Text]", "nodeValue: Hello World", "Length: 11", "Substring(2,5): llo W", "New nodeValue (replace): HelloAWorld", "New nodeValue (delete 1): HelloWorld", "Index error (delete 2)", "New nodeValue (delete 3): Hello", "New nodeValue (append): Hello Test", "Index error (insert 1)", "New nodeValue (insert 2): Hello New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testCommentNode(self, caplog): sample = os.path.join(self.misc_path, "testCommentNode.html") expected = [ "nodeName: #comment", "nodeType: 8", "Object: [object Comment]", "nodeValue: <!--Hello World-->", "Length: 18", "Substring(2,5): --Hel", "New nodeValue (replace): <!--HAllo World-->", "New nodeValue (delete 1): <!--Hllo World-->", "Index error (delete 2)", "New nodeValue (delete 3): <!--H", "New nodeValue (append): <!--H Test", "Index error (insert 1)", "New nodeValue (insert 2): <!--H New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation.html") expected = [ "hasFeature('core'): true", ] self.do_perform_test(caplog, sample, expected) def test_testAttrNode(self, caplog): sample = os.path.join(self.misc_path, "testAttrNode.html") expected = [ "Object: [object Attr]", "nodeName: test", "nodeType: 2", "nodeValue: foo", "Length: undefined", "New nodeValue: test2", "Parent: null", "Owner: null", "Name: test", "Specified: true", "childNodes length: 0", ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild.html") expected = [ "firstChild: Old child", "lastChild: Old child", "innerText: Old child", "[ERROR] Attempting to replace with a null element", "[ERROR] Attempting to replace a null element", "[ERROR] Attempting to replace with an invalid element", "[ERROR] Attempting to replace an invalid element", "[ERROR] Attempting to replace on a read-only element failed", "Alert Text: New child", '<div id="foobar"><!--Just a comment--></div>', ] self.do_perform_test(caplog, sample, expected) def test_testCookie(self, caplog): sample = os.path.join(self.misc_path, "testCookie.html") expected = ["favorite_food=tripe", "name=oeschger"] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment1.html") expected = [ "<div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment2(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment2.html") expected = [ '<div id="foobar"><b>This is B</b></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment3(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment3.html") expected = [ "foo:bar", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment4(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment4.html") expected = [ '<div><p>Test2</p></div><div><p>Test</p></div><div id="test1"><p>Test 1</p></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment5(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment5.html") expected = [ "Trying to replace a node not in the tree", "<div><p>Test2</p></div><div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentType(self, caplog): sample = os.path.join(self.misc_path, "testDocumentType.html") expected = [ "Doctype: [object DocumentType]", "Doctype name: html", "Doctype nodeName: html", "Doctype nodeType: 10", "Doctype nodeValue: null", "Doctype publicId: ", "Doctype systemId: ", "Doctype textContent: null", ] self.do_perform_test(caplog, sample, expected) def test_testRemoveChild(self, caplog): sample = os.path.join(self.misc_path, "testRemoveChild.html") expected = [ "<div>Don't care about me</div>", "[ERROR] Attempting to remove null element", "[ERROR] Attempting to remove an invalid element", "[ERROR] Attempting to remove a read-only element", "[ERROR] Attempting to remove an element not in the tree", "[ERROR] Attempting to remove from a read-only element", ] self.do_perform_test(caplog, sample, expected) def test_testNamedNodeMap(self, caplog): sample = os.path.join(self.misc_path, "testNamedNodeMap.html") expected = [ "hasAttributes (before removal): true", "hasAttribute('id'): true", "First test: id->p1", "Second test: id->p1", "Third test: id->p1", "Fourth test: id->p1", "Fifth test failed", "Not existing: null", "hasAttributes (after removal): false", "Sixth test: foo->bar", "Seventh test: foo->bar2", "Final attributes length: 1", ] self.do_perform_test(caplog, sample, expected) def test_testEntityReference(self, caplog): sample = os.path.join(self.misc_path, "testEntityReference.html") expected = [ "node: [object EntityReference]", "name: &", "nodeName: &", "nodeType: 5", "nodeValue: null", ] self.do_perform_test(caplog, sample, expected) def test_getElementsByTagName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByTagName.html") expected = [ "[object HTMLHtmlElement]", "[object HTMLHeadElement]", "[object HTMLBodyElement]", "[object HTMLParagraphElement]", "[object HTMLScriptElement]", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentElement(self, caplog): sample = os.path.join(self.misc_path, "testDocumentElement.html") expected = ['<a href="http://www.google.com">Google</a>'] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute1(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute1.html") expected = ["Attribute: bar", "Attribute (after removal): null"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute2(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute2.html") expected = [ "[element workaround redirection] about:blank -> https://buffer.github.io/thug/notexists.html", "[element workaround redirection] about:blank -> https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute3(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute3.html") expected = [ "Alert Text: foo", "Alert Text: bar", "Alert Text: test", "Alert Text: foobar", ] self.do_perform_test(caplog, sample, expected) def test_testCDATASection(self, caplog): sample = os.path.join(self.misc_path, "testCDATASection.html") expected = [ "nodeName: #cdata-section", "nodeType: 4", "<xml>&lt;![CDATA[Some &lt;CDATA&gt; data &amp; then some]]&gt;</xml>", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLCollection.html") expected = [ '<div id="odiv1">Page one</div>', '<div name="odiv2">Page two</div>', ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation2(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation2.html") expected = [ "Element #1: [object HTMLHeadElement]", "Element #2: [object HTMLLinkElement]", "Element #3: [object HTMLTitleElement]", "Element #4: [object HTMLMetaElement]", "Element #5: [object HTMLBaseElement]", "Element #6: [object HTMLIsIndexElement]", "Element #7: [object HTMLStyleElement]", "Element #8: [object HTMLFormElement]", "Element #9: [object HTMLSelectElement]", "Element #10: [object HTMLOptGroupElement]", "Element #11: [object HTMLOptionElement]", "Element #12: [object HTMLInputElement]", "Element #13: [object HTMLTextAreaElement]", "Element #14: [object HTMLButtonElement]", "Element #15: [object HTMLLabelElement]", "Element #16: [object HTMLFieldSetElement]", "Element #17: [object HTMLLegendElement]", "Element #18: [object HTMLUListElement]", "Element #19: [object HTMLOListElement]", "Element #20: [object HTMLDListElement]", "Element #21: [object HTMLDirectoryElement]", "Element #22: [object HTMLMenuElement]", "Element #23: [object HTMLLIElement]", "Element #24: [object HTMLDivElement]", "Element #25: [object HTMLParagraphElement]", "Element #26: [object HTMLHeadingElement]", "Element #27: [object HTMLHeadingElement]", "Element #28: [object HTMLHeadingElement]", "Element #29: [object HTMLHeadingElement]", "Element #30: [object HTMLHeadingElement]", "Element #31: [object HTMLHeadingElement]", "Element #32: [object HTMLQuoteElement]", "Element #33: [object HTMLQuoteElement]", "Element #34: [object HTMLSpanElement]", "Element #35: [object HTMLPreElement]", "Element #36: [object HTMLBRElement]", "Element #37: [object HTMLBaseFontElement]", "Element #38: [object HTMLFontElement]", "Element #39: [object HTMLHRElement]", "Element #40: [object HTMLModElement]", "Element #41: [object HTMLModElement]", "Element #42: [object HTMLAnchorElement]", "Element #43: [object HTMLObjectElement]", "Element #44: [object HTMLParamElement]", "Element #45: [object HTMLImageElement]", "Element #46: [object HTMLAppletElement]", "Element #47: [object HTMLScriptElement]", "Element #48: [object HTMLFrameSetElement]", "Element #49: [object HTMLFrameElement]", "Element #50: [object HTMLIFrameElement]", "Element #51: [object HTMLTableElement]", "Element #52: [object HTMLTableCaptionElement]", "Element #53: [object HTMLTableColElement]", "Element #54: [object HTMLTableColElement]", "Element #55: [object HTMLTableSectionElement]", "Element #56: [object HTMLTableSectionElement]", "Element #57: [object HTMLTableSectionElement]", "Element #58: [object HTMLTableRowElement]", "Element #59: [object HTMLTableCellElement]", "Element #60: [object HTMLTableCellElement]", "Element #61: [object HTMLMediaElement]", "Element #62: [object HTMLAudioElement]", "Element #63: [object HTMLHtmlElement]", "Element #64: [object HTMLBodyElement]", ] self.do_perform_test(caplog, sample, expected) def test_testApplyElement(self, caplog): sample = os.path.join(self.misc_path, "testApplyElement.html") expected = [ '<div id="outer"><div id="test"><div>Just a sample</div></div></div>', '<div id="outer"><div>Just a div<div id="test"><div>Just a sample</div></div></div></div>', ] self.do_perform_test(caplog, sample, expected) def test_testProcessingInstruction(self, caplog): sample = os.path.join(self.misc_path, "testProcessingInstruction.html") expected = [ "[object ProcessingInstruction]", "nodeName: xml-stylesheet", "nodeType: 7", 'nodeValue: href="mycss.css" type="text/css"', "target: xml-stylesheet", ] self.do_perform_test(caplog, sample, expected) def test_testWindow(self, caplog): sample = os.path.join(self.misc_path, "testWindow.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testObject1(self, caplog): sample = os.path.join(self.misc_path, "testObject1.html") expected = [ "[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf" ] self.do_perform_test(caplog, sample, expected) def test_testObject2(self, caplog): sample = os.path.join(self.misc_path, "testObject2.html") expected = [ "[params redirection] about:blank -> http://192.168.1.100/data", "[params redirection] about:blank -> http://192.168.1.100/source", "[params redirection] about:blank -> http://192.168.1.100/archive", ] self.do_perform_test(caplog, sample, expected) def test_testObject3(self, caplog): sample = os.path.join(self.misc_path, "testObject3.html") expected = [ "[params redirection] about:blank -> http://192.168.1.100/movie.swf" ] self.do_perform_test(caplog, sample, expected) def test_testObject4(self, caplog): sample = os.path.join(self.misc_path, "testObject4.html") expected = ["[params redirection] about:blank -> http://192.168.1.100/archive"] self.do_perform_test(caplog, sample, expected) def test_testObject5(self, caplog): sample = os.path.join(self.misc_path, "testObject5.html") expected = [ "[params redirection] about:blank -> http://192.168.1.100/data", "[params redirection] about:blank -> http://192.168.1.100/source", "[params redirection] about:blank -> http://192.168.1.100/archive", ] self.do_perform_test(caplog, sample, expected) def test_testObject7(self, caplog): sample = os.path.join(self.misc_path, "testObject7.html") expected = ["width: 400", "foo: undefined", "foo: bar"] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild2(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild2.html") expected = ['<div id="foobar"><div id="test"></div></div>'] self.do_perform_test(caplog, sample, expected) def test_testNavigator(self, caplog): sample = os.path.join(self.misc_path, "testNavigator.html") expected = [ "window: [object Window]", "appCodeName: Mozilla", "appName: Microsoft Internet Explorer", "appVersion: 5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; rv:9.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2; BOIE9;ENUS)", "cookieEnabled: true", "onLine: true", "platform: Win32", ] self.do_perform_test(caplog, sample, expected) def test_testWScriptShell(self, caplog): sample = os.path.join(self.misc_path, "testWScriptShell.html") expected = [ "ActiveXObject: wscript.shell", "valueOf: Windows Script Host", "toString: Windows Script Host", "[WScript.Shell ActiveX] Sleep(1)", '[WScript.Shell ActiveX] Environment("System")', '[WScript.Shell ActiveX] Expanding environment string "Windows is installed in %WinDir%"', '[WScript.Shell ActiveX] Expanded environment string to "Windows is installed in C:\\Windows"', '[WScript.Shell ActiveX] Expanding environment string "Username: %USERNAME%"', '[WScript.Shell ActiveX] Expanding environment string "Computer name: %COMPUTERNAME%"', '[WScript.Shell ActiveX] Expanding environment string "OS: %OS%"', '[WScript.Shell ActiveX] Expanded environment string to "OS: WINDOWS_NT"', '[WScript.Shell ActiveX] Expanding environment string "CommonProgramFiles: %CommonProgramFiles%"', '[WScript.Shell ActiveX] Expanded environment string to "CommonProgramFiles: C:\\Program Files\\Common Files"', "[WScript.Shell ActiveX] Echo(Echo test)", '[WScript.Shell ActiveX] Received call to SpecialFolders property "AllUsersDesktop"', '[WScript.Shell ActiveX] Expanding environment string "%PUBLIC%\\Desktop"', '[WScript.Shell ActiveX] Expanded environment string to "C:\\Users\\Public\\Desktop"', '[WScript.Shell ActiveX] Received call to SpecialFolders property "AllUsersStartMenu"', '[WScript.Shell ActiveX] Expanding environment string "%ALLUSERSPROFILE%\\Microsoft\\Windows\\Start Menu"', '[WScript.Shell ActiveX] Expanded environment string to "C:\\ProgramData\\Microsoft\\Windows\\Start Menu"', '[WScript.Shell ActiveX] RegRead("HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Systemroot") = "C:\\Windows"', '[WScript.Shell ActiveX] RegWrite("HKCU\\MyNewKey\\", "1", "REG_DWORD")', '[WScript.Shell ActiveX] RegRead("HKCU\\MyNewKey\\") = "1"', '[WScript.Shell ActiveX] RegRead("HKLM\\Not Existing\\") = NOT FOUND', '[WScript.Shell ActiveX] RegRead("HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\ProgramFilesDir") = "C:\\Program Files"', '[WScript.Shell ActiveX] CreateShortcut "C:\\Program Files\\notepad.lnk"', "[WScript.Shell ActiveX] CreateObject (wscript.shortcut)", "ActiveXObject: wscript.shortcut", "[WScript.Shortcut ActiveX] Saving link object 'C:\\Program Files\\notepad.lnk' with target 'notepad.exe'", "[WScript.Shell ActiveX] Quit(1)", ] self.do_perform_test(caplog, sample, expected) def test_testAdodbStream(self, caplog): sample = os.path.join(self.misc_path, "testAdodbStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)", "[Window] Alert Text: Stream content: Test", "[Window] Alert Text: Stream content (first 2 chars): Te", "[Window] Alert Text: Stream size: 4", "[Adodb.Stream ActiveX] SaveToFile(test.txt, 2)", "[Adodb.Stream ActiveX] LoadFromFile(test1234.txt)", "[Window] Alert Text: Attempting to load from a not existing file", "[Adodb.Stream ActiveX] LoadFromFile(test.txt)", "[Window] Alert Text: ReadText: Test", "[Window] Alert Text: ReadText(3): Tes", "[Window] Alert Text: ReadText(10): Test", "[Adodb.Stream ActiveX] Changed position in fileobject to: (2)", "[Window] Alert Text: stTest2", "[Adodb.Stream ActiveX] Close", ] self.do_perform_test(caplog, sample, expected) def test_testScriptingFileSystemObject(self, caplog): sample = os.path.join(self.misc_path, "testScriptingFileSystemObject.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS for GetSpecialFolder("0")', '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS\\system32 for GetSpecialFolder("1")', '[WScript.Shell ActiveX] Expanding environment string "%TEMP%"', "[Window] Alert Text: FolderExists('C:\\Windows\\System32'): true", "[Window] Alert Text: FileExists(''): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\drivers\\etc\\hosts'): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", '[Window] Alert Text: GetExtensionName("C:\\Windows\\System32\\test.txt"): .txt', "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", "[Window] Alert Text: [After CopyFile] FileExists('C:\\Windows\\System32\\test2.txt'): true", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test2.txt'): false", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test3.txt'): true", ] self.do_perform_test(caplog, sample, expected) def test_testScriptingEncoder(self, caplog): sample = os.path.join(self.misc_path, "testScriptingEncoder.html") expected = [ '[Scripting.Encoder ActiveX] EncodeScriptFile(".js", "alert("test");", 0, ""', ] self.do_perform_test(caplog, sample, expected) def test_testHTMLOptionsCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html") expected = [ "length: 4", "item(0): Volvo", "namedItem('audi'): Audi", "namedItem('mercedes').value: mercedes", "[After remove] item(0): Saab", "[After first add] length: 4", "[After first add] item(3): foobar", "[After second add] length: 5", "[After second add] item(3): test1234", "Not found error", ] self.do_perform_test(caplog, sample, expected) def test_testTextStream(self, caplog): sample = os.path.join(self.misc_path, "testTextStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] CreateTextFile("test.txt", "False", "False")', "[After first write] ReadAll: foobar", "[After first write] Line: 1", "[After first write] Column: 7", "[After first write] AtEndOfLine: true", "[After first write] AtEndOfStream: true", "[After second write] Line: 2", "[After second write] Column: 1", "[After second write] AtEndOfLine: false", "[After second write] AtEndOfStream: false", "[After third write] Line: 5", "[After third write] Column: 16", "[After third write] AtEndOfLine: false", "[After third write] AtEndOfStream: false", "[After fourth write] Line: 6", "[After fourth write] Column: 1", "[After fourth write] AtEndOfLine: false", "[After fourth write] AtEndOfStream: false", "[After fourth write] First char: s", "[After fourth write] Second char: o", "[After fourth write] Third char: m", "[After fourth write] Line: some other textnext line", "[After skip] Read(5): ttest", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAnchorElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html") expected = [ "a.protocol: https:", "a.host: www.example.com:1234", "a.hostname: www.example.com", "a.port: 1234", "b.protocol: :", "b.host: ", "b.hostname: ", "b.port: ", "c.protocol: https:", "c.host: www.example.com", "c.hostname: www.example.com", "c.port: ", "e.pathname: /foo/index.html", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLTableElement3(self, caplog): sample = os.path.join(self.misc_path, "testHTMLTableElement3.html") expected = [ "tHead: [object HTMLTableSectionElement]", "tHead row 0 sectionRowIndex: 0", "tFoot: [object HTMLTableSectionElement]", "caption: [object HTMLTableCaptionElement]", "Row 0 rowIndex = 0", "Row 1 rowIndex = 1", "row: [object HTMLTableRowElement]", "tBodies: [object HTMLCollection]", "cell: [object HTMLTableCellElement]", "cell.innerHTML: New cell 1", "row.deleteCell(10) failed", "row.deleteCell(20) failed", ] self.do_perform_test(caplog, sample, expected) def test_testTextArea(self, caplog): sample = os.path.join(self.misc_path, "testTextArea.html") expected = ["type: textarea", "cols: 100", "rows: 25"] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocument.html") expected = [ "document.title: Test", "document.title: Foobar", "anchors: [object HTMLCollection]", "anchors length: 1", "anchors[0].name: foobar", "applets: [object HTMLCollection]", "applets length: 2", "applets[0].code: HelloWorld.class", "links: [object HTMLCollection]", "links length: 1", "links[0].href: https://github.com/buffer/thug/", "images: [object HTMLCollection]", "images length: 1", "images[0].href: test.jpg", "disabled: false", "head: [object HTMLHeadElement]", "referrer: ", "URL: about:blank", "Alert Text: Hello, world", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLFormElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLFormElement.html") expected = [ "[object HTMLFormElement]", "f.elements: [object HTMLFormControlsCollection]", "f.length: 4", "f.name: [object HTMLFormControlsCollection]", "f.acceptCharset: ", "f.action: /cgi-bin/test", "f.enctype: application/x-www-form-urlencoded", "f.encoding: application/x-www-form-urlencoded", "f.method: POST", "f.target: ", ] self.do_perform_test(caplog, sample, expected) def test_testFile(self, caplog): sample = os.path.join(self.misc_path, "testFile.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] GetFile("D:\\ Program Files\\ Common Files\\test.txt")', "[File ActiveX] Path = D:\\ Program Files\\ Common Files\\test.txt, Attributes = 32", "Drive (test.txt): D:", "ShortPath (test.txt): D:\\\\ Progr~1\\\\ Commo~1\\\\test.txt", "ShortName (test.txt): test.txt", "Attributes: 1", '[Scripting.FileSystemObject ActiveX] GetFile("test2.txt")', "[File ActiveX] Path = test2.txt, Attributes = 32", "Drive (test2.txt): C:", "ShortPath (test2.txt): test2.txt", "ShortName (test2.txt): test2.txt", "Copy(test3.txt, True)", "Move(test4.txt)", "Delete(False)", "OpenAsTextStream(ForReading, 0)", ] self.do_perform_test(caplog, sample, expected) def test_testFolder(self, caplog): sample = os.path.join(self.misc_path, "testFolder.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] CreateFolder("D:\\Program Files\\Test")', "[Folder ActiveX] Path = D:\\Program Files\\Test, Attributes = 16", "Drive: D:", "ShortPath: D:\\\\Progra~1\\\\Test", "ShortName: Test", "Copy(D:\\Program Files\\Test2, True)", "Move(D:\\Program Files\\Test3)", "Delete(False)", ] self.do_perform_test(caplog, sample, expected) def test_testWScriptNetwork(self, caplog): sample = os.path.join(self.misc_path, "testWScriptNetwork.html") expected = [ "[WScript.Network ActiveX] Got request to PrinterConnections", "[WScript.Network ActiveX] Got request to EnumNetworkDrives", '[WScript.Shell ActiveX] Expanding environment string "%USERDOMAIN%"', '[WScript.Shell ActiveX] Expanding environment string "%USERNAME%"', '[WScript.Shell ActiveX] Expanding environment string "%COMPUTERNAME%"', ] self.do_perform_test(caplog, sample, expected) def test_testApplet(self, caplog): sample = os.path.join(self.misc_path, "testApplet.html") expected = ["[applet redirection]"] self.do_perform_test(caplog, sample, expected) def test_testFrame(self, caplog): sample = os.path.join(self.misc_path, "testFrame.html") expected = [ "[frame redirection]", "Alert Text: https://buffer.github.io/thug/", "Alert Text: data:text/html,<script>alert('Hello world');</script>", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAudioElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAudioElement.html") expected = [ "[object HTMLAudioElement]", "src: https://buffer.github.io/thug/", "controller: null", "crossOrigin: null", "currentSrc: https://buffer.github.io/thug/", "initialTime: 0", "currentTime: 0", "muted: false", "defaultMuted: false", "readyState: 4", "srcObject: null", "playbackRate: 1", "defaultPlaybackRate: 1", "disableRemotePlayback: false", "duration: 0", "ended: false", "error: null", "mediaKeys: null", "networkState: 1", "audioTracks length: 0", "textTracks length: 0", "sinkId:", "buffered length: 0", "paused: true", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLVideoElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLVideoElement.html") expected = [ "width: 800", "height: 600", "videoWidth: 800", "videoHeight: 600", "poster:", "playsInline: true", ] self.do_perform_test(caplog, sample, expected) def test_testIFrame(self, caplog): sample = os.path.join(self.misc_path, "testIFrame.html") expected = ["[iframe redirection]", "width: 3", "height: 4"] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement.html") expected = [ "src (before changes): test.jpg", "src (after first change): test2.jpg", "onerror handler fired", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement2(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement2.html") expected = [ "Alert Text: Inside onerror handler", "[ERROR][_handle_onerror] ReferenceError: foobar is not defined", ] self.do_perform_test(caplog, sample, expected) def test_testTitle(self, caplog): sample = os.path.join(self.misc_path, "testTitle.html") expected = ["New title: Foobar"] self.do_perform_test(caplog, sample, expected) def test_testHTMLMetaElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLMetaElement.html") expected = [ "utf-8", ] self.do_perform_test(caplog, sample, expected) def test_testScreen(self, caplog): sample = os.path.join(self.misc_path, "testScreen.html") expected = [ "window: [object Window]", "screen: [object Screen]", "availHeight: 600", "availWidth: 800", "colorDepth: 32", "width: 800", "bufferDepth: 24", ] self.do_perform_test(caplog, sample, expected) def test_testAcroPDF(self, caplog): sample = os.path.join(self.misc_path, "testAcroPDF.html") expected = [ "$version: 9.1.0", ] self.do_perform_test(caplog, sample, expected) def test_testCSSStyleDeclaration(self, caplog): sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html") expected = [ "style: [object CSSStyleDeclaration]", "length: 1", "cssText: color: blue;", "color: blue", "item(0): color", "item(100):", "getPropertyValue('color'): blue", "length (after removeProperty): 0", "cssText: foo: bar;", ] self.do_perform_test(caplog, sample, expected) def test_testFormProperty(self, caplog): sample = os.path.join(self.misc_path, "testFormProperty.html") expected = ["[object HTMLFormElement]", "formA"] self.do_perform_test(caplog, sample, expected) def test_testVBScript(self, caplog): sample = os.path.join(self.misc_path, "testVBScript.html") expected = ["[VBS embedded URL redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule1(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule1.html") expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule2(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule2.html") expected = [ "[font face redirection]", "https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf", ] self.do_perform_test(caplog, sample, expected) def test_testSilverLight(self, caplog): sample = os.path.join(self.misc_path, "testSilverLight.html") expected = [ "[SilverLight] isVersionSupported('4.0')", "Version 4.0 supported: true", ] self.do_perform_test(caplog, sample, expected) def test_testHistory(self, caplog): sample = os.path.join(self.misc_path, "testHistory.html") expected = [ "history: [object History]", "window: [object Window]", "navigationMode (before change): automatic", "navigationMode (after change): fast", ] self.do_perform_test(caplog, sample, expected) def test_testMSXML2Document(self, caplog): sample = os.path.join(self.misc_path, "testMSXML2Document.html") expected = [ "[MSXML2.DOMDocument] Microsoft XML Core Services MSXML Uninitialized Memory Corruption", "CVE-2012-1889", ] self.do_perform_test(caplog, sample, expected) def test_testMicrosoftXMLDOM(self, caplog): sample = os.path.join(self.misc_path, "testMicrosoftXMLDOM.html") expected = [ "[Microsoft XMLDOM ActiveX] Creating element TEST", "bin.base64", "foobar3: foobar3", "bin.hex", "foobar4: foobar4", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocumentCompatibleInfo(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocumentCompatibleInfo.html") expected = [ "This document is in IE 8 mode", "compatMode = CSS1Compat", "document.compatible.length = 1", "userAgent = IE", "version = 8", ] self.do_perform_test(caplog, sample, expected) def test_testEmbed(self, caplog): sample = os.path.join(self.misc_path, "testEmbed.html") expected = [ "[embed redirection]", ] self.do_perform_test(caplog, sample, expected) def test_testWinNTSystemInfo(self, caplog): sample = os.path.join(self.misc_path, "testWinNTSystemInfo.html") expected = [ "[WScript.Shell ActiveX] CreateObject (WinNTSystemInfo)", "[WinNTSystemInfo ActiveX] Getting ComputerName", "[WinNTSystemInfo ActiveX] Getting DomainName", "[WinNTSystemInfo ActiveX] Getting PDC (Primary Domain Controller)", "[WinNTSystemInfo ActiveX] Getting UserName", ] self.do_perform_test(caplog, sample, expected) def test_testDump(self, caplog): sample = os.path.join(self.misc_path, "testDump.html") expected = [ "[eval] Deobfuscated argument: eval", "[document.write] Deobfuscated argument: FOOBAR", ] self.do_perform_test(caplog, sample, expected) def test_testTimers(self, caplog): sample = os.path.join(self.misc_path, "testTimers.html") expected = ["setTimeout null expression", "setInterval null expression"] self.do_perform_test(caplog, sample, expected) def test_testPlayStateChange(self, caplog): sample = os.path.join(self.misc_path, "testPlayStateChange.html") expected = ["Undefined state"] self.do_perform_test(caplog, sample, expected) def test_testAtob(self, caplog): sample = os.path.join(self.misc_path, "testAtob.html") expected = [ "Encoded String: SGVsbG8gV29ybGQ=", "Decoded String: Hello World", ] self.do_perform_test(caplog, sample, expected) def test_testExternal(self, caplog): sample = os.path.join(self.misc_path, "testExternal.html") expected = [] self.do_perform_test(caplog, sample, expected) def test_testAdodbRecordset(self, caplog): sample = os.path.join(self.misc_path, "testAdodbRecordset.html") expected = ["ActiveXObject: adodb.recordset"] self.do_perform_test(caplog, sample, expected) def test_testPrototype(self, caplog): sample = os.path.join(self.misc_path, "testPrototype.html") expected = [ "window.constructor: function Window()", "window.prototype.__proto__: [object Object]", "window.prototype.constructor: function Window()", "window.prototype.name: Window", "window.toLocaleString(): [object Window]", "Greetings from get_var1", "Greetings from set_var2", "o.anotherValue = 5", "isPrototypeOf (test 1): true", "isPrototypeOf (test 2): true", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLBodyElement1(self, caplog): sample = os.path.join(self.misc_path, "testHTMLBodyElement1.html") expected = ["It works"] self.do_perform_test(caplog, sample, expected) def test_testHTMLBodyElement2(self, caplog): sample = os.path.join(self.misc_path, "testHTMLBodyElement2.html") expected = [] self.do_perform_test(caplog, sample, expected) def test_testAsync(self, caplog): sample = os.path.join(self.misc_path, "testAsync.html") expected = ["async: true", "defer: false"] self.do_perform_test(caplog, sample, expected) def test_testDefer(self, caplog): sample = os.path.join(self.misc_path, "testDefer.html") expected = ["async: false", "defer: true"] self.do_perform_test(caplog, sample, expected) def test_testScriptSrc(self, caplog): sample = os.path.join(self.misc_path, "testScriptSrc.html") expected = ["Alert Text: #foo"] self.do_perform_test(caplog, sample, expected) def test_testClearTimeout(self, caplog): sample = os.path.join(self.misc_path, "testClearTimeout.html") expected = ["Alert Text: 1", "Alert Text: 2"] self.do_perform_test(caplog, sample, expected) def test_testExecScript(self, caplog): sample = os.path.join(self.misc_path, "testExecScript.html") expected = ["Alert Text: execScript"] self.do_perform_test(caplog, sample, expected) def test_testDecodeURIComponent(self, caplog): sample = os.path.join(self.misc_path, "testDecodeURIComponent.html") expected = ["Alert Text: ~!@#$%^&*()=+[]{}\\;:'\",/?"] self.do_perform_test(caplog, sample, expected) def test_testGetComputedStyle(self, caplog): sample = os.path.join(self.misc_path, "testGetComputedStyle.html") expected = ["lightblue"] self.do_perform_test(caplog, sample, expected) def test_testHTMLSelectElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLSelectElement.html") expected = ["True"] self.do_perform_test(caplog, sample, expected) def test_meta_refresh(self, caplog): sample = os.path.join(self.misc_path, "meta_refresh.html") expected = ["[meta redirection] about:blank -> https://buffer.github.io/thug/"] self.do_perform_test(caplog, sample, expected) def test_js_data_src(self, caplog): sample = os.path.join(self.misc_path, "testJSDataSrc.html") expected = [ "[Window] Alert Text: Hello world", "[Window] Alert Text: Hello world", ] self.do_perform_test(caplog, sample, expected) def test_iframe_srcdoc(self, caplog): sample = os.path.join(self.misc_path, "testIFrameSrcdoc.html") expected = ["[Window] Alert Text: Hello World"] self.do_perform_test(caplog, sample, expected) def test_jscript(self, caplog): sample = os.path.join(self.misc_path, "testJScript.html") expected = [ "Rule: IE=EmulateIE8", "Rule: JScript.Compact", "Rule: JScript.Encode", ] self.do_perform_test(caplog, sample, expected) def test_testExecCommand(self, caplog): sample = os.path.join(self.misc_path, "testExecCommand.html") expected = [] self.do_perform_test(caplog, sample, expected) def test_testGetElementById(self, caplog): sample = os.path.join(self.misc_path, "testGetElementById.html") expected = ["[object HTMLDivElement]"] self.do_perform_test(caplog, sample, expected) def test_testDomain(self, caplog): sample = os.path.join(self.misc_path, "testDomain.html") expected = ["document.domain = github.com"] self.do_perform_test(caplog, sample, expected) def test_testJScriptEncode(self, caplog): sample = os.path.join(self.misc_path, "testJScriptEncode.html") expected = [ "this code should bE kept secret!!!!", ] self.do_perform_test(caplog, sample, expected) def test_testIEVisibility(self, caplog): sample = os.path.join(self.misc_path, "testIEVisibility.html") expected = [ "[Window] Alert Text: document.msHidden: false", "[Window] Alert Text: document.msVisibilityState: visible", ] self.do_perform_test(caplog, sample, expected) def test_testSplitText(self, caplog): sample = os.path.join(self.misc_path, "testSplitText.html") expected = [ "p.childNodes.length before splitText: 1", "foobar value after splitText: foo", "bar value: bar", "p.childNodes.length after splitText: 2", ] self.do_perform_test(caplog, sample, expected) def test_testNormalize(self, caplog): sample = os.path.join(self.misc_path, "testNormalize.html") expected = [ "[Before normalize] wrapper.childNodes.length: 6", "[After normalize] wrapper.childNodes.length: 3", "[After normalize] wrapper.childNodes[0].textContent: Part 1 Part 2 Part 3", "[After normalize] wrapper.childNodes[2].textContent: Part 4 Part 5", ] self.do_perform_test(caplog, sample, expected) def test_testClearAttributes(self, caplog): sample = os.path.join(self.misc_path, "testClearAttributes.html") expected = ["id: myMarquee", "style: border:2px solid blue", "bgcolor: null"] self.do_perform_test(caplog, sample, expected) def test_testScriptingDictionary(self, caplog): sample = os.path.join(self.misc_path, "testScriptingDictionary.html") expected = [ '[Scripting.Dictionary ActiveX] Add("0", "1")', '[Scripting.Dictionary ActiveX] Add("1", "2")', "[Window] Alert Text: Count before removal: 2", "[Window] Alert Text: Key 0 exists before removal: true", "[Window] Alert Text: Key 1000 exists before removal: false", '[Scripting.Dictionary ActiveX] Remove("0")', '[Scripting.Dictionary ActiveX] Remove("1000")', "[Window] Alert Text: Count after removal: 1", "[Window] Alert Text: Key 0 exists after removal: false", "[Window] Alert Text: Key 1000 exists after removal: false", "[Scripting.Dictionary ActiveX] RemoveAll()", "[Window] Alert Text: Count after RemoveAll: 0", ] self.do_perform_test(caplog, sample, expected)
66,213
Python
.py
1,351
38.569948
229
0.610621
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,705
test_loop_detection.py
buffer_thug/tests/functional/test_loop_detection.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestLoopDetection(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_loop_detection_1(self, caplog): sample = os.path.join(self.misc_path, "testLoopDetection1.html") expected = [ "[WARNING] document.write loop detected", ] self.do_perform_test(caplog, sample, expected)
950
Python
.py
25
29.6
72
0.629386
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,706
test_misc_safari.py
buffer_thug/tests/functional/test_misc_safari.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestMiscSamplesSafari(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected, useragent="osx10safari5"): thug = ThugAPI() thug.set_useragent(useragent) thug.set_events("click,storage") thug.set_connect_timeout(2) thug.disable_cert_logging() thug.set_features_logging() thug.set_ssl_verify() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_plugindetect1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, expected) def test_plugindetect2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html") expected = [ "AdobeReader version: 9,1,0,0", "Flash version: 10,0,64,0", "Java version: 1,6,0,32", ] self.do_perform_test(caplog, sample, expected) def test_test1a(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected, useragent="ipadsafari9") def test_test1b(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected, useragent="osx11safari14") def test_test2(self, caplog): sample = os.path.join(self.misc_path, "test2.html") expected = ["[Window] Alert Text: Java enabled: true"] self.do_perform_test(caplog, sample, expected) def test_test3(self, caplog): sample = os.path.join(self.misc_path, "test3.html") expected = ["[Window] Alert Text: foo"] self.do_perform_test(caplog, sample, expected) def test_testAppendChild(self, caplog): sample = os.path.join(self.misc_path, "testAppendChild.html") expected = [ "Don't care about me", "Just a sample", "Attempt to append a null element failed", "Attempt to append an invalid element failed", "Attempt to append a text element failed", "Attempt to append a read-only element failed", ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode.html") expected = [ '<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>' ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode2(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode2.html") expected = [ "[Window] Alert Text: [object HTMLButtonElement]", "[Window] Alert Text: Clone node", "[Window] Alert Text: None", "[Window] Alert Text: [object Attr]", "[Window] Alert Text: True", ] self.do_perform_test(caplog, sample, expected) def test_testCreateHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html") expected = [ "[object HTMLDocument]", "[object HTMLBodyElement]", "<p>This is a new paragraph.</p>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentAll(self, caplog): sample = os.path.join(self.misc_path, "testDocumentAll.html") expected = ["http://www.google.com"] self.do_perform_test(caplog, sample, expected) def test_testDocumentWrite1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentWrite1.html") expected = [ "Foobar", "Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>", ] self.do_perform_test(caplog, sample, expected) def test_testGetElementsByClassName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByClassName.html") expected = ["First", "Hello World!", "Second"] self.do_perform_test(caplog, sample, expected) def test_testInnerHTML(self, caplog): sample = os.path.join(self.misc_path, "testInnerHTML.html") expected = ["dude", "Fred Flinstone"] self.do_perform_test(caplog, sample, expected) def test_testInsertBefore(self, caplog): sample = os.path.join(self.misc_path, "testInsertBefore.html") expected = [ "<div>Just a sample</div><div>I'm your reference!</div></body></html>", "[ERROR] Attempting to insert null element", "[ERROR] Attempting to insert an invalid element", "[ERROR] Attempting to insert using an invalid reference element", "[ERROR] Attempting to insert a text node using an invalid reference element", ] self.do_perform_test(caplog, sample, expected) def test_testLocalStorage(self, caplog): sample = os.path.join(self.misc_path, "testLocalStorage.html") expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"] self.do_perform_test(caplog, sample, expected) def test_testPlugins(self, caplog): sample = os.path.join(self.misc_path, "testPlugins.html") expected = [ "Shockwave Flash 10.0.64.0", "Windows Media Player 7", "Adobe Acrobat", ] self.do_perform_test(caplog, sample, expected) def test_testNode(self, caplog): sample = os.path.join(self.misc_path, "testNode.html") expected = ["thelink", "thediv"] self.do_perform_test(caplog, sample, expected) def test_testNode2(self, caplog): sample = os.path.join(self.misc_path, "testNode2.html") expected = ["thelink", "thediv2"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector.html") expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector2(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector2.html") expected = ["CoursesWeb.net", "MarPlo.net", "php.net"] self.do_perform_test(caplog, sample, expected) def test_testScope(self, caplog): sample = os.path.join(self.misc_path, "testScope.html") expected = [ "foobar", "foo", "bar", "True", "3", "2012-10-07 11:13:00", "3.14159265359", "/foo/i", ] self.do_perform_test(caplog, sample, expected) def test_testSessionStorage(self, caplog): sample = os.path.join(self.misc_path, "testSessionStorage.html") expected = ["key1", "key2", "value1", "value3"] self.do_perform_test(caplog, sample, expected) def test_testSetInterval(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testText(self, caplog): sample = os.path.join(self.misc_path, "testText.html") expected = [ '<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>' ] self.do_perform_test(caplog, sample, expected) def test_testWindowOnload(self, caplog): sample = os.path.join(self.misc_path, "testWindowOnload.html") expected = ["[Window] Alert Text: Fired"] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML1(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html") expected = ['<div id="five">five</div><div id="one">one</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML2(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html") expected = ['<div id="two"><div id="six">six</div>two</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML3(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html") expected = ['<div id="three">three<div id="seven">seven</div></div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML4(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html") expected = ['<div id="four">four</div><div id="eight">eight</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML5(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html") expected = ["insertAdjacentHTML does not support notcorrect operation"] self.do_perform_test(caplog, sample, expected) def test_testCurrentScript(self, caplog): sample = os.path.join(self.misc_path, "testCurrentScript.html") expected = [ "[Window] Alert Text: This page has scripts", "[Window] Alert Text: text/javascript", "[Window] Alert Text: Just a useless script", ] self.do_perform_test(caplog, sample, expected) def test_testTextNode(self, caplog): sample = os.path.join(self.misc_path, "testTextNode.html") expected = [ "nodeName: #text", "nodeType: 3", "Object: [object Text]", "nodeValue: Hello World", "Length: 11", "Substring(2,5): llo W", "New nodeValue (replace): HelloAWorld", "New nodeValue (delete 1): HelloWorld", "Index error (delete 2)", "New nodeValue (delete 3): Hello", "New nodeValue (append): Hello Test", "Index error (insert 1)", "New nodeValue (insert 2): Hello New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testCommentNode(self, caplog): sample = os.path.join(self.misc_path, "testCommentNode.html") expected = [ "nodeName: #comment", "nodeType: 8", "Object: [object Comment]", "nodeValue: <!--Hello World-->", "Length: 18", "Substring(2,5): --Hel", "New nodeValue (replace): <!--HAllo World-->", "New nodeValue (delete 1): <!--Hllo World-->", "Index error (delete 2)", "New nodeValue (delete 3): <!--H", "New nodeValue (append): <!--H Test", "Index error (insert 1)", "New nodeValue (insert 2): <!--H New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation.html") expected = [ "hasFeature('core'): true", ] self.do_perform_test(caplog, sample, expected) def test_testAttrNode(self, caplog): sample = os.path.join(self.misc_path, "testAttrNode.html") expected = [ "Object: [object Attr]", "nodeName: test", "nodeType: 2", "nodeValue: foo", "Length: undefined", "New nodeValue: test2", "Parent: null", "Owner: null", "Name: test", "Specified: true", "childNodes length: 0", ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild.html") expected = [ "firstChild: Old child", "lastChild: Old child", "innerText: Old child", "[ERROR] Attempting to replace with a null element", "[ERROR] Attempting to replace a null element", "[ERROR] Attempting to replace with an invalid element", "[ERROR] Attempting to replace an invalid element", "[ERROR] Attempting to replace on a read-only element failed", "Alert Text: New child", '<div id="foobar"><!--Just a comment--></div>', ] self.do_perform_test(caplog, sample, expected) def test_testCookie(self, caplog): sample = os.path.join(self.misc_path, "testCookie.html") expected = ["favorite_food=tripe", "name=oeschger"] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment1.html") expected = [ "<div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment2(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment2.html") expected = [ '<div id="foobar"><b>This is B</b></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment3(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment3.html") expected = [ "foo:bar", ] self.do_perform_test(caplog, sample, expected) def test_testClassList3(self, caplog): sample = os.path.join(self.misc_path, "testClassList3.html") expected = [ '[Initial value] <div class="foo"></div>', '[After remove and add] <div class="anotherclass"></div>', "[Item] anotherclass", "[Empty item] null", "[Toggle visible] true", '[After multiple adds] <div class="anotherclass visible foo bar baz"></div>', '[After multiple removes] <div class="anotherclass visible"></div>', '[After toggle] <div class="anotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testClassList4(self, caplog): sample = os.path.join(self.misc_path, "testClassList4.html") expected = [ '[After remove and add] <div class="anotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentType(self, caplog): sample = os.path.join(self.misc_path, "testDocumentType.html") expected = [ "Doctype: [object DocumentType]", "Doctype name: html", "Doctype nodeName: html", "Doctype nodeType: 10", "Doctype nodeValue: null", "Doctype publicId: ", "Doctype systemId: ", "Doctype textContent: null", ] self.do_perform_test(caplog, sample, expected) def test_testRemoveChild(self, caplog): sample = os.path.join(self.misc_path, "testRemoveChild.html") expected = [ "<div>Don't care about me</div>", "[ERROR] Attempting to remove null element", "[ERROR] Attempting to remove an invalid element", "[ERROR] Attempting to remove a read-only element", "[ERROR] Attempting to remove an element not in the tree", "[ERROR] Attempting to remove from a read-only element", ] self.do_perform_test(caplog, sample, expected) def test_testNamedNodeMap(self, caplog): sample = os.path.join(self.misc_path, "testNamedNodeMap.html") expected = [ "hasAttributes (before removal): true", "hasAttribute('id'): true", "First test: id->p1", "Second test: id->p1", "Third test: id->p1", "Fourth test: id->p1", "Fifth test failed", "Not existing: null", "hasAttributes (after removal): false", "Sixth test: foo->bar", "Seventh test: foo->bar2", "Final attributes length: 1", ] self.do_perform_test(caplog, sample, expected) def test_testEntityReference(self, caplog): sample = os.path.join(self.misc_path, "testEntityReference.html") expected = [ "node: [object EntityReference]", "name: &", "nodeName: &", "nodeType: 5", "nodeValue: null", ] self.do_perform_test(caplog, sample, expected) def test_getElementsByTagName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByTagName.html") expected = [ "[object HTMLHtmlElement]", "[object HTMLHeadElement]", "[object HTMLBodyElement]", "[object HTMLParagraphElement]", "[object HTMLScriptElement]", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentElement(self, caplog): sample = os.path.join(self.misc_path, "testDocumentElement.html") expected = ['<a href="http://www.google.com">Google</a>'] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute1(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute1.html") expected = ["Attribute: bar", "Attribute (after removal): null"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute2(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute2.html") expected = [ "[element workaround redirection] about:blank -> https://buffer.github.io/thug/notexists.html", "[element workaround redirection] about:blank -> https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute3(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute3.html") expected = [ "Alert Text: foo", "Alert Text: bar", "Alert Text: test", "Alert Text: foobar", ] self.do_perform_test(caplog, sample, expected) def test_testCDATASection(self, caplog): sample = os.path.join(self.misc_path, "testCDATASection.html") expected = [ "nodeName: #cdata-section", "nodeType: 4", "<xml>&lt;![CDATA[Some &lt;CDATA&gt; data &amp; then some]]&gt;</xml>", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLCollection.html") expected = [ '<div id="odiv1">Page one</div>', '<div name="odiv2">Page two</div>', ] self.do_perform_test(caplog, sample, expected) def test_testProcessingInstruction(self, caplog): sample = os.path.join(self.misc_path, "testProcessingInstruction.html") expected = [ "[object ProcessingInstruction]", "nodeName: xml-stylesheet", "nodeType: 7", 'nodeValue: href="mycss.css" type="text/css"', "target: xml-stylesheet", ] self.do_perform_test(caplog, sample, expected) def test_testWindow(self, caplog): sample = os.path.join(self.misc_path, "testWindow.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testObject1(self, caplog): sample = os.path.join(self.misc_path, "testObject1.html") expected = [ "[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf" ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild2(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild2.html") expected = ['<div id="foobar"><div id="test"></div></div>'] self.do_perform_test(caplog, sample, expected) def test_testNavigator(self, caplog): sample = os.path.join(self.misc_path, "testNavigator.html") expected = [ "window: [object Window]", "appCodeName: Mozilla", "appName: Netscape", "appVersion: 5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/534.51.22 (KHTML, like Gecko) Version/5.1.1 Safari/534.51.22", "cookieEnabled: true", "onLine: true", "platform: MacIntel", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLOptionsCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html") expected = [ "length: 4", "item(0): Volvo", "namedItem('audi'): Audi", "namedItem('mercedes').value: mercedes", "[After remove] item(0): Saab", "[After first add] length: 4", "[After first add] item(3): foobar", "[After second add] length: 5", "[After second add] item(3): test1234", "Not found error", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAnchorElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html") expected = [ "a.protocol: https:", "a.host: www.example.com:1234", "a.hostname: www.example.com", "a.port: 1234", "b.protocol: :", "b.host: ", "b.hostname: ", "b.port: ", "c.protocol: https:", "c.host: www.example.com", "c.hostname: www.example.com", "c.port: ", "e.pathname: /foo/index.html", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLTableElement3(self, caplog): sample = os.path.join(self.misc_path, "testHTMLTableElement3.html") expected = [ "tHead: [object HTMLTableSectionElement]", "tFoot: [object HTMLTableSectionElement]", "caption: [object HTMLTableCaptionElement]", "row: [object HTMLTableRowElement]", "tBodies: [object HTMLCollection]", "cell: [object HTMLTableCellElement]", "cell.innerHTML: New cell 1", "row.deleteCell(10) failed", "row.deleteCell(20) failed", ] self.do_perform_test(caplog, sample, expected) def test_testTextArea(self, caplog): sample = os.path.join(self.misc_path, "testTextArea.html") expected = ["type: textarea", "cols: 100", "rows: 25"] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocument.html") expected = [ "document.title: Test", "document.title: Foobar", "anchors: [object HTMLCollection]", "anchors length: 1", "anchors[0].name: foobar", "applets: [object HTMLCollection]", "applets length: 2", "applets[0].code: HelloWorld.class", "links: [object HTMLCollection]", "links length: 1", "links[0].href: https://github.com/buffer/thug/", "images: [object HTMLCollection]", "images length: 1", "images[0].href: test.jpg", "disabled: false", "head: [object HTMLHeadElement]", "referrer: ", "URL: about:blank", "Alert Text: Hello, world", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLFormElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLFormElement.html") expected = [ "[object HTMLFormElement]", "f.elements: [object HTMLFormControlsCollection]", "f.length: 4", "f.name: [object HTMLFormControlsCollection]", "f.acceptCharset: ", "f.action: /cgi-bin/test", "f.enctype: application/x-www-form-urlencoded", "f.encoding: application/x-www-form-urlencoded", "f.method: POST", "f.target: ", ] self.do_perform_test(caplog, sample, expected) def test_testApplet(self, caplog): sample = os.path.join(self.misc_path, "testApplet.html") expected = ["[applet redirection]"] self.do_perform_test(caplog, sample, expected) def test_testFrame(self, caplog): sample = os.path.join(self.misc_path, "testFrame.html") expected = [ "[frame redirection]", "Alert Text: https://buffer.github.io/thug/", "Alert Text: data:text/html,<script>alert('Hello world');</script>", ] self.do_perform_test(caplog, sample, expected) def test_testIFrame(self, caplog): sample = os.path.join(self.misc_path, "testIFrame.html") expected = ["[iframe redirection]", "width: 3", "height: 4"] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement.html") expected = [ "src (before changes): test.jpg", "src (after first change): test2.jpg", "onerror handler fired", ] self.do_perform_test(caplog, sample, expected) def test_testTitle(self, caplog): sample = os.path.join(self.misc_path, "testTitle.html") expected = ["New title: Foobar"] self.do_perform_test(caplog, sample, expected) def test_testCSSStyleDeclaration(self, caplog): sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html") expected = [ "style: [object CSSStyleDeclaration]", "length: 1", "cssText: color: blue;", "color: blue", "item(0): color", "item(100):", "getPropertyValue('color'): blue", "length (after removeProperty): 0", "cssText: foo: bar;", ] self.do_perform_test(caplog, sample, expected) def test_testFormProperty(self, caplog): sample = os.path.join(self.misc_path, "testFormProperty.html") expected = ["[object HTMLFormElement]", "formA"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule1(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule1.html") expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule2(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule2.html") expected = [ "[font face redirection]", "https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf", ] self.do_perform_test(caplog, sample, expected) def test_testHistory(self, caplog): sample = os.path.join(self.misc_path, "testHistory.html") expected = [ "history: [object History]", "window: [object Window]", "navigationMode (before change): automatic", "navigationMode (after change): fast", ] self.do_perform_test(caplog, sample, expected) def test_testConsole(self, caplog): sample = os.path.join(self.misc_path, "testConsole.html") expected = [ "[object Console]", "[Console] assert(True, 'Test assert')", "[Console] count() = 1", "[Console] count('foobar') = 1", "[Console] count('foobar') = 2", "[Console] error('Test error')", "[Console] log('Hello world!')", "[Console] group()", "[Console] log('Hello again, this time inside a group!')", "[Console] groupEnd()", "[Console] groupCollapsed()", "[Console] info('Hello again')", "[Console] warn('Hello again')", ] self.do_perform_test(caplog, sample, expected)
29,110
Python
.py
641
35.046802
153
0.594254
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,707
test_misc_ie100.py
buffer_thug/tests/functional/test_misc_ie100.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestMiscSamplesIE(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7ie100") thug.set_events("click,storage") thug.set_connect_timeout(2) thug.disable_cert_logging() thug.set_file_logging() thug.set_features_logging() thug.set_ssl_verify() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_plugindetect1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, expected) def test_plugindetect2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html") expected = [ "AdobeReader version: 9,1,0,0", "Flash version: 10,0,64,0", "Java version: 1,6,0,32", "ActiveXObject: javawebstart.isinstalled.1.6.0.0", "ActiveXObject: javaplugin.160_32", ] self.do_perform_test(caplog, sample, expected) def test_test1(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected) def test_test2(self, caplog): sample = os.path.join(self.misc_path, "test2.html") expected = ["[Window] Alert Text: Java enabled: true"] self.do_perform_test(caplog, sample, expected) def test_test3(self, caplog): sample = os.path.join(self.misc_path, "test3.html") expected = ["[Window] Alert Text: foo"] self.do_perform_test(caplog, sample, expected) def test_testAppendChild(self, caplog): sample = os.path.join(self.misc_path, "testAppendChild.html") expected = [ "Don't care about me", "Just a sample", "Attempt to append a null element failed", "Attempt to append an invalid element failed", "Attempt to append a text element failed", "Attempt to append a read-only element failed", ] self.do_perform_test(caplog, sample, expected) def test_testClipboardData(self, caplog): sample = os.path.join(self.misc_path, "testClipboardData.html") expected = ["Test ClipboardData"] self.do_perform_test(caplog, sample, expected) def test_testCloneNode(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode.html") expected = [ '<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>' ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode2(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode2.html") expected = [ "[Window] Alert Text: [object HTMLButtonElement]", "[Window] Alert Text: Clone node", "[Window] Alert Text: None", "[Window] Alert Text: [object Attr]", "[Window] Alert Text: True", ] self.do_perform_test(caplog, sample, expected) def test_testCreateHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html") expected = [ "[object HTMLDocument]", "[object HTMLBodyElement]", "<p>This is a new paragraph.</p>", ] self.do_perform_test(caplog, sample, expected) def test_testCreateStyleSheet(self, caplog): sample = os.path.join(self.misc_path, "testCreateStyleSheet.html") expected = [ "[Window] Alert Text: style1.css", "[Window] Alert Text: style2.css", "[Window] Alert Text: style3.css", "[Window] Alert Text: style4.css", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentAll(self, caplog): sample = os.path.join(self.misc_path, "testDocumentAll.html") expected = ["http://www.google.com"] self.do_perform_test(caplog, sample, expected) def test_testDocumentWrite1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentWrite1.html") expected = [ "Foobar", "Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>", ] self.do_perform_test(caplog, sample, expected) def test_testExternalSidebar(self, caplog): sample = os.path.join(self.misc_path, "testExternalSidebar.html") expected = ["[Window] Alert Text: Internet Explorer >= 7.0 or Chrome"] self.do_perform_test(caplog, sample, expected) def test_testGetElementsByClassName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByClassName.html") expected = ["First", "Hello World!", "Second"] self.do_perform_test(caplog, sample, expected) def test_testInnerHTML(self, caplog): sample = os.path.join(self.misc_path, "testInnerHTML.html") expected = ["dude", "Fred Flinstone"] self.do_perform_test(caplog, sample, expected) def test_testInsertBefore(self, caplog): sample = os.path.join(self.misc_path, "testInsertBefore.html") expected = [ "<div>Just a sample</div><div>I'm your reference!</div></body></html>", "[ERROR] Attempting to insert null element", "[ERROR] Attempting to insert an invalid element", "[ERROR] Attempting to insert using an invalid reference element", "[ERROR] Attempting to insert a text node using an invalid reference element", ] self.do_perform_test(caplog, sample, expected) def test_testLocalStorage(self, caplog): sample = os.path.join(self.misc_path, "testLocalStorage.html") expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"] self.do_perform_test(caplog, sample, expected) def test_testPlugins(self, caplog): sample = os.path.join(self.misc_path, "testPlugins.html") expected = [ "Shockwave Flash 10.0.64.0", "Windows Media Player 7", "Adobe Acrobat", ] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEdge(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEdge.html") expected = ["[Window] Alert Text: 10"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleEmulateIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleEmulateIE.html") expected = ["[Window] Alert Text: 8"] self.do_perform_test(caplog, sample, expected) def test_testMetaXUACompatibleIE(self, caplog): sample = os.path.join(self.misc_path, "testMetaXUACompatibleIE.html") expected = ["[Window] Alert Text: 10"] self.do_perform_test(caplog, sample, expected) def test_testNode(self, caplog): sample = os.path.join(self.misc_path, "testNode.html") expected = ["thelink", "thediv"] self.do_perform_test(caplog, sample, expected) def test_testNode2(self, caplog): sample = os.path.join(self.misc_path, "testNode2.html") expected = ["thelink", "thediv2"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector.html") expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector2(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector2.html") expected = ["CoursesWeb.net", "MarPlo.net", "php.net"] self.do_perform_test(caplog, sample, expected) def test_testScope(self, caplog): sample = os.path.join(self.misc_path, "testScope.html") expected = [ "foobar", "foo", "bar", "True", "3", "2012-10-07 11:13:00", "3.14159265359", "/foo/i", ] self.do_perform_test(caplog, sample, expected) def test_testSessionStorage(self, caplog): sample = os.path.join(self.misc_path, "testSessionStorage.html") expected = ["key1", "key2", "value1", "value3"] self.do_perform_test(caplog, sample, expected) def test_testSetInterval(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testText(self, caplog): sample = os.path.join(self.misc_path, "testText.html") expected = [ '<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>' ] self.do_perform_test(caplog, sample, expected) def test_testWindowOnload(self, caplog): sample = os.path.join(self.misc_path, "testWindowOnload.html") expected = ["[Window] Alert Text: Fired"] self.do_perform_test(caplog, sample, expected) def test_test_click(self, caplog): sample = os.path.join(self.misc_path, "test_click.html") expected = [ "[window open redirection] about:blank -> https://buffer.github.io/thug/" ] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML1(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html") expected = ['<div id="five">five</div><div id="one">one</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML2(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html") expected = ['<div id="two"><div id="six">six</div>two</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML3(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html") expected = ['<div id="three">three<div id="seven">seven</div></div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML4(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html") expected = ['<div id="four">four</div><div id="eight">eight</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML5(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html") expected = ["insertAdjacentHTML does not support notcorrect operation"] self.do_perform_test(caplog, sample, expected) def test_testCurrentScript(self, caplog): sample = os.path.join(self.misc_path, "testCurrentScript.html") expected = [ "[Window] Alert Text: This page has scripts", "[Window] Alert Text: text/javascript", "[Window] Alert Text: Just a useless script", ] self.do_perform_test(caplog, sample, expected) def test_testCCInterpreter(self, caplog): sample = os.path.join(self.misc_path, "testCCInterpreter.html") expected = [ "JavaScript version: 10", "Running on the 32-bit version of Windows", ] self.do_perform_test(caplog, sample, expected) def test_testTextNode(self, caplog): sample = os.path.join(self.misc_path, "testTextNode.html") expected = [ "nodeName: #text", "nodeType: 3", "Object: [object Text]", "nodeValue: Hello World", "Length: 11", "Substring(2,5): llo W", "New nodeValue (replace): HelloAWorld", "New nodeValue (delete 1): HelloWorld", "Index error (delete 2)", "New nodeValue (delete 3): Hello", "New nodeValue (append): Hello Test", "Index error (insert 1)", "New nodeValue (insert 2): Hello New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testCommentNode(self, caplog): sample = os.path.join(self.misc_path, "testCommentNode.html") expected = [ "nodeName: #comment", "nodeType: 8", "Object: [object Comment]", "nodeValue: <!--Hello World-->", "Length: 18", "Substring(2,5): --Hel", "New nodeValue (replace): <!--HAllo World-->", "New nodeValue (delete 1): <!--Hllo World-->", "Index error (delete 2)", "New nodeValue (delete 3): <!--H", "New nodeValue (append): <!--H Test", "Index error (insert 1)", "New nodeValue (insert 2): <!--H New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation.html") expected = [ "hasFeature('core'): true", ] self.do_perform_test(caplog, sample, expected) def test_testAttrNode(self, caplog): sample = os.path.join(self.misc_path, "testAttrNode.html") expected = [ "Object: [object Attr]", "nodeName: test", "nodeType: 2", "nodeValue: foo", "Length: undefined", "New nodeValue: test2", "Parent: null", "Owner: null", "Name: test", "Specified: true", "childNodes length: 0", ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild.html") expected = [ "firstChild: Old child", "lastChild: Old child", "innerText: Old child", "[ERROR] Attempting to replace with a null element", "[ERROR] Attempting to replace a null element", "[ERROR] Attempting to replace with an invalid element", "[ERROR] Attempting to replace an invalid element", "[ERROR] Attempting to replace on a read-only element failed", "Alert Text: New child", '<div id="foobar"><!--Just a comment--></div>', ] self.do_perform_test(caplog, sample, expected) def test_testCookie(self, caplog): sample = os.path.join(self.misc_path, "testCookie.html") expected = ["favorite_food=tripe", "name=oeschger"] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment1.html") expected = [ "<div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment2(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment2.html") expected = [ '<div id="foobar"><b>This is B</b></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment3(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment3.html") expected = [ "foo:bar", ] self.do_perform_test(caplog, sample, expected) def test_testClassList1(self, caplog): sample = os.path.join(self.misc_path, "testClassList1.html") expected = [ '[Initial value] <div class="foo"></div>', '[After remove and add] <div class="anotherclass"></div>', "[Item] anotherclass", "[Empty item] null", "[Toggle visible] true", '[After toggle] <div class="anotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testClassList4(self, caplog): sample = os.path.join(self.misc_path, "testClassList4.html") expected = [ '[After remove and add] <div class="anotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentType(self, caplog): sample = os.path.join(self.misc_path, "testDocumentType.html") expected = [ "Doctype: [object DocumentType]", "Doctype name: html", "Doctype nodeName: html", "Doctype nodeType: 10", "Doctype nodeValue: null", "Doctype publicId: ", "Doctype systemId: ", "Doctype textContent: null", ] self.do_perform_test(caplog, sample, expected) def test_testRemoveChild(self, caplog): sample = os.path.join(self.misc_path, "testRemoveChild.html") expected = [ "<div>Don't care about me</div>", "[ERROR] Attempting to remove null element", "[ERROR] Attempting to remove an invalid element", "[ERROR] Attempting to remove a read-only element", "[ERROR] Attempting to remove an element not in the tree", "[ERROR] Attempting to remove from a read-only element", ] self.do_perform_test(caplog, sample, expected) def test_testNamedNodeMap(self, caplog): sample = os.path.join(self.misc_path, "testNamedNodeMap.html") expected = [ "hasAttributes (before removal): true", "hasAttribute('id'): true", "First test: id->p1", "Second test: id->p1", "Third test: id->p1", "Fourth test: id->p1", "Fifth test failed", "Not existing: null", "hasAttributes (after removal): false", "Sixth test: foo->bar", "Seventh test: foo->bar2", "Final attributes length: 1", ] self.do_perform_test(caplog, sample, expected) def test_testEntityReference(self, caplog): sample = os.path.join(self.misc_path, "testEntityReference.html") expected = [ "node: [object EntityReference]", "name: &", "nodeName: &", "nodeType: 5", "nodeValue: null", ] self.do_perform_test(caplog, sample, expected) def test_getElementsByTagName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByTagName.html") expected = [ "[object HTMLHtmlElement]", "[object HTMLHeadElement]", "[object HTMLBodyElement]", "[object HTMLParagraphElement]", "[object HTMLScriptElement]", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentElement(self, caplog): sample = os.path.join(self.misc_path, "testDocumentElement.html") expected = ['<a href="http://www.google.com">Google</a>'] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute1(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute1.html") expected = ["Attribute: bar", "Attribute (after removal): null"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute3(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute3.html") expected = [ "Alert Text: foo", "Alert Text: bar", "Alert Text: test", "Alert Text: foobar", ] self.do_perform_test(caplog, sample, expected) def test_testCDATASection(self, caplog): sample = os.path.join(self.misc_path, "testCDATASection.html") expected = [ "nodeName: #cdata-section", "nodeType: 4", "<xml>&lt;![CDATA[Some &lt;CDATA&gt; data &amp; then some]]&gt;</xml>", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLCollection.html") expected = [ '<div id="odiv1">Page one</div>', '<div name="odiv2">Page two</div>', ] self.do_perform_test(caplog, sample, expected) def test_testApplyElement(self, caplog): sample = os.path.join(self.misc_path, "testApplyElement.html") expected = [ '<div id="outer"><div id="test"><div>Just a sample</div></div></div>', '<div id="outer"><div>Just a div<div id="test"><div>Just a sample</div></div></div></div>', ] self.do_perform_test(caplog, sample, expected) def test_testProcessingInstruction(self, caplog): sample = os.path.join(self.misc_path, "testProcessingInstruction.html") expected = [ "[object ProcessingInstruction]", "nodeName: xml-stylesheet", "nodeType: 7", 'nodeValue: href="mycss.css" type="text/css"', "target: xml-stylesheet", ] self.do_perform_test(caplog, sample, expected) def test_testWindow(self, caplog): sample = os.path.join(self.misc_path, "testWindow.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testObject1(self, caplog): sample = os.path.join(self.misc_path, "testObject1.html") expected = [ "[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf" ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild2(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild2.html") expected = ['<div id="foobar"><div id="test"></div></div>'] self.do_perform_test(caplog, sample, expected) def test_testNavigator(self, caplog): sample = os.path.join(self.misc_path, "testNavigator.html") expected = [ "window: [object Window]", "appCodeName: Mozilla", "appName: Microsoft Internet Explorer", "appVersion: 5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0; rv: 10.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)", "cookieEnabled: true", "onLine: true", "platform: Win32", ] self.do_perform_test(caplog, sample, expected) def test_testAdodbStream(self, caplog): sample = os.path.join(self.misc_path, "testAdodbStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Adodb.Stream)", "[Window] Alert Text: Stream content: Test", "[Window] Alert Text: Stream content (first 2 chars): Te", "[Window] Alert Text: Stream size: 4", "[Adodb.Stream ActiveX] SaveToFile(test.txt, 2)", "[Adodb.Stream ActiveX] LoadFromFile(test1234.txt)", "[Window] Alert Text: Attempting to load from a not existing file", "[Adodb.Stream ActiveX] LoadFromFile(test.txt)", "[Window] Alert Text: ReadText: Test", "[Window] Alert Text: ReadText(3): Tes", "[Window] Alert Text: ReadText(10): Test", "[Adodb.Stream ActiveX] Changed position in fileobject to: (2)", "[Window] Alert Text: stTest2", "[Adodb.Stream ActiveX] Close", ] self.do_perform_test(caplog, sample, expected) def test_testScriptingFileSystemObject(self, caplog): sample = os.path.join(self.misc_path, "testScriptingFileSystemObject.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS for GetSpecialFolder("0")', '[Scripting.FileSystemObject ActiveX] Returning C:\\WINDOWS\\system32 for GetSpecialFolder("1")', '[WScript.Shell ActiveX] Expanding environment string "%TEMP%"', "[Window] Alert Text: FolderExists('C:\\Windows\\System32'): true", "[Window] Alert Text: FileExists(''): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\drivers\\etc\\hosts'): true", "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", '[Window] Alert Text: GetExtensionName("C:\\Windows\\System32\\test.txt"): .txt', "[Window] Alert Text: FileExists('C:\\Windows\\System32\\test.txt'): true", "[Window] Alert Text: [After CopyFile] FileExists('C:\\Windows\\System32\\test2.txt'): true", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test2.txt'): false", "[Window] Alert Text: [After MoveFile] FileExists('C:\\Windows\\System32\\test3.txt'): true", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLOptionsCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html") expected = [ "length: 4", "item(0): Volvo", "namedItem('audi'): Audi", "namedItem('mercedes').value: mercedes", "[After remove] item(0): Saab", "[After first add] length: 4", "[After first add] item(3): foobar", "[After second add] length: 5", "[After second add] item(3): test1234", "Not found error", ] self.do_perform_test(caplog, sample, expected) def test_testTextStream(self, caplog): sample = os.path.join(self.misc_path, "testTextStream.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] CreateTextFile("test.txt", "False", "False")', "[After first write] ReadAll: foobar", "[After first write] Line: 1", "[After first write] Column: 7", "[After first write] AtEndOfLine: true", "[After first write] AtEndOfStream: true", "[After second write] Line: 2", "[After second write] Column: 1", "[After second write] AtEndOfLine: false", "[After second write] AtEndOfStream: false", "[After third write] Line: 5", "[After third write] Column: 16", "[After third write] AtEndOfLine: false", "[After third write] AtEndOfStream: false", "[After fourth write] Line: 6", "[After fourth write] Column: 1", "[After fourth write] AtEndOfLine: false", "[After fourth write] AtEndOfStream: false", "[After fourth write] First char: s", "[After fourth write] Second char: o", "[After fourth write] Third char: m", "[After fourth write] Line: some other textnext line", "[After skip] Read(5): ttest", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAnchorElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html") expected = [ "a.protocol: https:", "a.host: www.example.com:1234", "a.hostname: www.example.com", "a.port: 1234", "b.protocol: :", "b.host: ", "b.hostname: ", "b.port: ", "c.protocol: https:", "c.host: www.example.com", "c.hostname: www.example.com", "c.port: ", "e.pathname: /foo/index.html", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLTableElement3(self, caplog): sample = os.path.join(self.misc_path, "testHTMLTableElement3.html") expected = [ "tHead: [object HTMLTableSectionElement]", "tFoot: [object HTMLTableSectionElement]", "caption: [object HTMLTableCaptionElement]", "row: [object HTMLTableRowElement]", "tBodies: [object HTMLCollection]", "cell: [object HTMLTableCellElement]", "cell.innerHTML: New cell 1", "row.deleteCell(10) failed", "row.deleteCell(20) failed", ] self.do_perform_test(caplog, sample, expected) def test_testTextArea(self, caplog): sample = os.path.join(self.misc_path, "testTextArea.html") expected = ["type: textarea", "cols: 100", "rows: 25"] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocument.html") expected = [ "document.title: Test", "document.title: Foobar", "anchors: [object HTMLCollection]", "anchors length: 1", "anchors[0].name: foobar", "applets: [object HTMLCollection]", "applets length: 2", "applets[0].code: HelloWorld.class", "links: [object HTMLCollection]", "links length: 1", "links[0].href: https://github.com/buffer/thug/", "images: [object HTMLCollection]", "images length: 1", "images[0].href: test.jpg", "disabled: false", "head: [object HTMLHeadElement]", "referrer: ", "URL: about:blank", "Alert Text: Hello, world", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLFormElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLFormElement.html") expected = [ "[object HTMLFormElement]", "f.elements: [object HTMLFormControlsCollection]", "f.length: 4", "f.name: [object HTMLFormControlsCollection]", "f.acceptCharset: ", "f.action: /cgi-bin/test", "f.enctype: application/x-www-form-urlencoded", "f.encoding: application/x-www-form-urlencoded", "f.method: POST", "f.target: ", ] self.do_perform_test(caplog, sample, expected) def test_testFile(self, caplog): sample = os.path.join(self.misc_path, "testFile.html") expected = [ "[Microsoft MDAC RDS.Dataspace ActiveX] CreateObject (Scripting.FileSystemObject)", '[Scripting.FileSystemObject ActiveX] GetFile("D:\\ Program Files\\ Common Files\\test.txt")', "[File ActiveX] Path = D:\\ Program Files\\ Common Files\\test.txt, Attributes = 32", "Drive (test.txt): D:", "ShortPath (test.txt): D:\\\\ Progr~1\\\\ Commo~1\\\\test.txt", "ShortName (test.txt): test.txt", "Attributes: 1", '[Scripting.FileSystemObject ActiveX] GetFile("test2.txt")', "[File ActiveX] Path = test2.txt, Attributes = 32", "Drive (test2.txt): C:", "ShortPath (test2.txt): test2.txt", "ShortName (test2.txt): test2.txt", "Copy(test3.txt, True)", "Move(test4.txt)", "Delete(False)", "OpenAsTextStream(ForReading, 0)", ] self.do_perform_test(caplog, sample, expected) def test_testWScriptNetwork(self, caplog): sample = os.path.join(self.misc_path, "testWScriptNetwork.html") expected = [ "[WScript.Network ActiveX] Got request to PrinterConnections", "[WScript.Network ActiveX] Got request to EnumNetworkDrives", '[WScript.Shell ActiveX] Expanding environment string "%USERDOMAIN%"', '[WScript.Shell ActiveX] Expanding environment string "%USERNAME%"', '[WScript.Shell ActiveX] Expanding environment string "%COMPUTERNAME%"', ] self.do_perform_test(caplog, sample, expected) def test_testApplet(self, caplog): sample = os.path.join(self.misc_path, "testApplet.html") expected = ["[applet redirection]"] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement.html") expected = [ "src (before changes): test.jpg", "src (after first change): test2.jpg", "onerror handler fired", ] self.do_perform_test(caplog, sample, expected) def test_testTitle(self, caplog): sample = os.path.join(self.misc_path, "testTitle.html") expected = ["New title: Foobar"] self.do_perform_test(caplog, sample, expected) def test_testCSSStyleDeclaration(self, caplog): sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html") expected = [ "style: [object CSSStyleDeclaration]", "length: 1", "cssText: color: blue;", "color: blue", "item(0): color", "item(100):", "getPropertyValue('color'): blue", "length (after removeProperty): 0", "cssText: foo: bar;", ] self.do_perform_test(caplog, sample, expected) def test_testFormProperty(self, caplog): sample = os.path.join(self.misc_path, "testFormProperty.html") expected = ["[object HTMLFormElement]", "formA"] self.do_perform_test(caplog, sample, expected) def test_testVBScript(self, caplog): sample = os.path.join(self.misc_path, "testVBScript.html") expected = ["[VBS embedded URL redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule1(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule1.html") expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule2(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule2.html") expected = [ "[font face redirection]", "https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf", ] self.do_perform_test(caplog, sample, expected) def test_testSilverLight(self, caplog): sample = os.path.join(self.misc_path, "testSilverLight.html") expected = [ "[SilverLight] isVersionSupported('4.0')", "Version 4.0 supported: true", ] self.do_perform_test(caplog, sample, expected) def test_testMSXML2Document(self, caplog): sample = os.path.join(self.misc_path, "testMSXML2Document.html") expected = [ "[MSXML2.DOMDocument] Microsoft XML Core Services MSXML Uninitialized Memory Corruption", "CVE-2012-1889", ] self.do_perform_test(caplog, sample, expected)
35,870
Python
.py
756
36.992063
201
0.600881
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,708
test_disabled_activex.py
buffer_thug/tests/functional/test_disabled_activex.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestDisabledActiveX(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.disable_acropdf() thug.disable_shockwave_flash() thug.disable_javaplugin() thug.disable_silverlight() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_disable_1(self, caplog): sample = os.path.join(self.misc_path, "testObject6.html") expected = [ "Unknown ActiveX Object: CA8A9780-280D-11CF-A24D-444553540000", "Unknown ActiveX Object: 233C1507-6A77-46A4-9443-F871F945D258", "Unknown ActiveX Object: CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA", "Unknown ActiveX object: 1234", ] self.do_perform_test(caplog, sample, expected) def test_disable_2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.9.1.html") expected = [ "Unknown ActiveX Object: CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA", "Unknown ActiveX Object: 5852F5ED-8BF4-11D4-A245-0080C6F74284", ] self.do_perform_test(caplog, sample, expected)
1,646
Python
.py
39
33.128205
75
0.639447
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,709
test_image_processing.py
buffer_thug/tests/functional/test_image_processing.py
import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestImageProcessing(object): def do_perform_test(self, caplog, url, expected, type_="remote"): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_ssl_verify() thug.reset_image_processing() thug.set_image_processing() thug.get_image_processing() thug.register_pyhook("MIMEHandler", "handle_image", self.handle_image_hook) thug.set_json_logging() thug.log_init(url) m = getattr(thug, "run_{}".format(type_)) m(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def handle_image_hook(self, args): log.warning("Inside hook") def test_antifork(self, caplog): expected = ["Antifork", "HACKERS RESEARCH VIRTUAL LAB", "Inside hook"] self.do_perform_test(caplog, "https://www.antifork.org", expected)
1,124
Python
.py
28
31.392857
83
0.624192
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,710
test_file_api.py
buffer_thug/tests/functional/test_file_api.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestFileAPI(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("osx10chrome97") thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_blob(self, caplog): sample = os.path.join(self.misc_path, "testFileAPIBlob.html") expected = [ "BLOB 1 type: application/json", "BLOB 1 size: 22", "BLOB 2 type: text/plain", "BLOB 2 size: 5", "BLOB 3 size: 18", "BLOB 2 text: hello", 'BLOB 3 text: "hello": "world"', "BLOB1 typeof(result): object", "BLOB 4 text: abc", ] self.do_perform_test(caplog, sample, expected) def test_file(self, caplog): sample = os.path.join(self.misc_path, "testFileAPIFile.html") expected = ["File name: sample.zip", "File type: application/zip"] self.do_perform_test(caplog, sample, expected)
1,445
Python
.py
37
29.675676
74
0.58967
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,711
test_silverlight.py
buffer_thug/tests/functional/test_silverlight.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestSilverLight(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, silverlight, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.disable_cert_logging() thug.set_features_logging() if silverlight in ("disable",): thug.disable_silverlight() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_silverlight1(self, caplog): sample = os.path.join(self.misc_path, "testSilverLight.html") expected = [ "Unknown ActiveX Object: agcontrol.agcontrol", ] self.do_perform_test(caplog, sample, "disable", expected)
1,163
Python
.py
30
30.1
69
0.629133
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,712
test_adobereader.py
buffer_thug/tests/functional/test_adobereader.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestAdobeReader(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, adobe, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.disable_cert_logging() thug.set_features_logging() if adobe in ("disable",): thug.disable_acropdf() else: thug.set_acropdf_pdf(adobe) thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_adobe1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, "9.1.0.0", expected) def test_adobe2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 10.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, "10.1.0.0", expected) def test_adobe3(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = [ "Flash version: 10.0.64.0", ] self.do_perform_test(caplog, sample, "disable", expected)
1,693
Python
.py
40
33.575
80
0.616514
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,713
test_extensive.py
buffer_thug/tests/functional/test_extensive.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestExtensive(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.set_extensive() thug.disable_cert_logging() thug.set_file_logging() thug.set_json_logging() thug.set_features_logging() thug.set_ssl_verify() thug.set_threshold(3) thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_Anchor1(self, caplog): sample = os.path.join(self.misc_path, "testAnchor1.html") expected = [ "[anchor redirection]", ] self.do_perform_test(caplog, sample, expected) def test_Anchor2(self, caplog): sample = os.path.join(self.misc_path, "testAnchor2.html") expected = [ "[anchor redirection]", ] self.do_perform_test(caplog, sample, expected) def test_Anchor3(self, caplog): sample = os.path.join(self.misc_path, "testAnchor3.html") expected = [ "Hello world", ] self.do_perform_test(caplog, sample, expected) def test_Anchor4(self, caplog): sample = os.path.join(self.misc_path, "testAnchor4.html") expected = [ "Hello world", ] self.do_perform_test(caplog, sample, expected) def test_Anchor5(self, caplog): sample = os.path.join(self.misc_path, "testAnchor5.html") expected = [ "testAnchor5 success", ] self.do_perform_test(caplog, sample, expected) def test_Anchor6(self, caplog): sample = os.path.join(self.misc_path, "testAnchor6.html") expected = [ "testAnchor5 success", ] self.do_perform_test(caplog, sample, expected) def test_Anchor7(self, caplog): sample = os.path.join(self.misc_path, "testAnchor7.html") expected = [ "[MIMEHandler] Unknown MIME Type: application/font-woff2", ] self.do_perform_test(caplog, sample, expected) def test_Anchors1(self, caplog): sample = os.path.join(self.misc_path, "testAnchors1.html") expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org/westwood/westwood.html", '[document.write] Deobfuscated argument: <a href="https://buffer.antifork.org/westwood/westwood.html">Antifork Research</a>', ] self.do_perform_test(caplog, sample, expected) def test_Anchors2(self, caplog): sample = os.path.join(self.misc_path, "testAnchors2.html") expected = [ "[document.write] Deobfuscated argument: <a>Google</a>", ] self.do_perform_test(caplog, sample, expected) def test_Anchors3(self, caplog): sample = os.path.join(self.misc_path, "testAnchors3.html") expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org/westwood/westwood.html", ] self.do_perform_test(caplog, sample, expected)
3,545
Python
.py
88
31.215909
137
0.616282
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,714
test_brokenurl.py
buffer_thug/tests/functional/test_brokenurl.py
import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestBrokenURL(object): def do_perform_test(self, caplog, url, expected): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_broken_url() thug.set_ssl_verify() thug.log_init(url) thug.run_remote(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_broken_1(self, caplog): url = "https:/buffer.antifork.org" expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org", ] self.do_perform_test(caplog, url, expected) def test_broken_2(self, caplog): url = "https://buffer.antifork.org" expected = [ "[window open redirection] about:blank -> https://buffer.antifork.org", ] self.do_perform_test(caplog, url, expected)
1,101
Python
.py
30
27.633333
83
0.599811
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,715
test_mimehandler.py
buffer_thug/tests/functional/test_mimehandler.py
import os from thug.ThugAPI.ThugAPI import ThugAPI class TestMIMEHandler(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, url, expected, type_="remote"): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_features_logging() thug.set_ssl_verify() thug.disable_download_prevent() thug.log_init(url) m = getattr(thug, "run_{}".format(type_)) m(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_zip_handler(self, caplog): expected = ["[Window] Alert Text: Foobar"] self.do_perform_test( caplog, "https://github.com/buffer/thug/raw/master/tests/test_files/test.js.zip", expected, ) def test_svg_xml_handler(self, caplog): sample = os.path.join(self.misc_path, "testSVGXMLHandler.html") expected = ["[Window] Alert Text: Hello from SVG Javascript"] self.do_perform_test(caplog, sample, expected, "local")
1,302
Python
.py
32
31.53125
85
0.609387
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,716
test_asyncprefetch.py
buffer_thug/tests/functional/test_asyncprefetch.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestAsyncPrefetch: cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, url, expected, type_="remote"): thug = ThugAPI() thug.set_useragent("win7ie90") thug.set_events("click,storage") thug.set_web_tracking() thug.enable_cert_logging() thug.enable_download_prevent() thug.set_features_logging() thug.set_log_verbose() thug.set_ssl_verify() thug.get_async_prefetch() thug.reset_async_prefetch() thug.get_async_prefetch() thug.set_async_prefetch() thug.log_init(url) m = getattr(thug, f"run_{type_}") m(url) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_async_prefetch_1(self, caplog): expected = [ "PREFETCHING", ] self.do_perform_test(caplog, "https://buffer.antifork.org", expected)
1,282
Python
.py
36
27.055556
77
0.606969
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,717
test_features.py
buffer_thug/tests/functional/test_features.py
import os import json import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestFeatures(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) features_path = os.path.join(cwd_path, os.pardir, "samples/features") expected_path = os.path.join(cwd_path, "features.json") with open(expected_path) as fd: expected = json.load(fd) def do_perform_test(self, caplog, sample): thug = ThugAPI() thug.log_init(sample) thug.set_useragent("win7ie90") thug.set_verbose() thug.set_json_logging() thug.reset_features_logging() assert thug.get_features_logging() is False thug.set_features_logging() assert thug.get_features_logging() is True thug.log_init(sample) thug.run_local(sample) thug.log_event() for r in caplog.records: try: features = json.dumps(r) except Exception: continue if not isinstance(features, dict): continue if "html_count" not in features: continue for url in self.expected: if not url.endswith(sample): continue for key in features: assert features[key] == self.expected[url][key] def test_test1(self, caplog): sample = os.path.join(self.features_path, "test1.html") self.do_perform_test(caplog, sample) def test_test2(self, caplog): sample = os.path.join(self.features_path, "test2.html") self.do_perform_test(caplog, sample) def test_test3(self, caplog): sample = os.path.join(self.features_path, "test3.html") self.do_perform_test(caplog, sample) def test_test4(self, caplog): sample = os.path.join(self.features_path, "test4.html") self.do_perform_test(caplog, sample) def test_test5(self, caplog): sample = os.path.join(self.features_path, "test5.html") self.do_perform_test(caplog, sample) def test_test6(self, caplog): sample = os.path.join(self.features_path, "test6.html") self.do_perform_test(caplog, sample) def test_test7(self, caplog): sample = os.path.join(self.features_path, "test7.html") self.do_perform_test(caplog, sample) def test_test8(self, caplog): sample = os.path.join(self.features_path, "test8.html") self.do_perform_test(caplog, sample) def test_test9(self, caplog): sample = os.path.join(self.features_path, "test9.html") self.do_perform_test(caplog, sample) def test_test10(self, caplog): sample = os.path.join(self.features_path, "test10.html") self.do_perform_test(caplog, sample) def test_test11(self, caplog): sample = os.path.join(self.features_path, "test11.html") self.do_perform_test(caplog, sample) def test_test12(self, caplog): sample = os.path.join(self.features_path, "test12.html") self.do_perform_test(caplog, sample) def test_test13(self, caplog): sample = os.path.join(self.features_path, "test13.html") self.do_perform_test(caplog, sample) def test_test14(self, caplog): sample = os.path.join(self.features_path, "test14.html") self.do_perform_test(caplog, sample) def test_test15(self, caplog): sample = os.path.join(self.features_path, "test15.html") self.do_perform_test(caplog, sample) def test_test16(self, caplog): sample = os.path.join(self.features_path, "test16.html") self.do_perform_test(caplog, sample) def test_test17(self, caplog): sample = os.path.join(self.features_path, "test17.html") self.do_perform_test(caplog, sample) def test_test18(self, caplog): sample = os.path.join(self.features_path, "test18.html") self.do_perform_test(caplog, sample)
3,994
Python
.py
92
34.565217
73
0.638056
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,718
test_misc_chrome.py
buffer_thug/tests/functional/test_misc_chrome.py
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestMiscSamplesChrome(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.set_useragent("win7chrome49") thug.set_events("click,storage") thug.set_connect_timeout(2) thug.disable_cert_logging() thug.set_features_logging() thug.set_ssl_verify() thug.log_init(sample) thug.run_local(sample) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_plugindetect1(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.6.html") expected = ["AdobeReader version: 9.1.0.0", "Flash version: 10.0.64.0"] self.do_perform_test(caplog, sample, expected) def test_plugindetect2(self, caplog): sample = os.path.join(self.misc_path, "PluginDetect-0.7.8.html") expected = [ "AdobeReader version: 9,1,0,0", "Flash version: 10,0,64,0", "Java version: 1,6,0,32", ] self.do_perform_test(caplog, sample, expected) def test_test1(self, caplog): sample = os.path.join(self.misc_path, "test1.html") expected = ["[Window] Alert Text: one"] self.do_perform_test(caplog, sample, expected) def test_test2(self, caplog): sample = os.path.join(self.misc_path, "test2.html") expected = ["[Window] Alert Text: Java enabled: true"] self.do_perform_test(caplog, sample, expected) def test_test3(self, caplog): sample = os.path.join(self.misc_path, "test3.html") expected = ["[Window] Alert Text: foo"] self.do_perform_test(caplog, sample, expected) def test_testAppendChild(self, caplog): sample = os.path.join(self.misc_path, "testAppendChild.html") expected = [ "Don't care about me", "Just a sample", "Attempt to append a null element failed", "Attempt to append an invalid element failed", "Attempt to append a text element failed", "Attempt to append a read-only element failed", ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode.html") expected = [ '<div id="cloned"><q>Can you copy <em>everything</em> I say?</q></div>' ] self.do_perform_test(caplog, sample, expected) def test_testCloneNode2(self, caplog): sample = os.path.join(self.misc_path, "testCloneNode2.html") expected = [ "[Window] Alert Text: [object HTMLButtonElement]", "[Window] Alert Text: Clone node", "[Window] Alert Text: None", "[Window] Alert Text: [object Attr]", "[Window] Alert Text: True", ] self.do_perform_test(caplog, sample, expected) def test_testCreateHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testCreateHTMLDocument.html") expected = [ "[object HTMLDocument]", "[object HTMLBodyElement]", "<p>This is a new paragraph.</p>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentAll(self, caplog): sample = os.path.join(self.misc_path, "testDocumentAll.html") expected = ["http://www.google.com"] self.do_perform_test(caplog, sample, expected) def test_testDocumentWrite1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentWrite1.html") expected = [ "Foobar", "Google</a><script>alert('foobar');</script><script language=\"VBScript\">alert('Gnam');</script><script>alert('Aieeeeee');</script></body>", ] self.do_perform_test(caplog, sample, expected) def test_testExternalSidebar(self, caplog): sample = os.path.join(self.misc_path, "testExternalSidebar.html") expected = ["[Window] Alert Text: Internet Explorer >= 7.0 or Chrome"] self.do_perform_test(caplog, sample, expected) def test_testGetElementsByClassName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByClassName.html") expected = ["First", "Hello World!", "Second"] self.do_perform_test(caplog, sample, expected) def test_testInnerHTML(self, caplog): sample = os.path.join(self.misc_path, "testInnerHTML.html") expected = ["dude", "Fred Flinstone"] self.do_perform_test(caplog, sample, expected) def test_testInsertBefore(self, caplog): sample = os.path.join(self.misc_path, "testInsertBefore.html") expected = [ "<div>Just a sample</div><div>I'm your reference!</div></body></html>", "[ERROR] Attempting to insert null element", "[ERROR] Attempting to insert an invalid element", "[ERROR] Attempting to insert using an invalid reference element", "[ERROR] Attempting to insert a text node using an invalid reference element", ] self.do_perform_test(caplog, sample, expected) def test_testLocalStorage(self, caplog): sample = os.path.join(self.misc_path, "testLocalStorage.html") expected = ["Alert Text: Fired", "Alert Text: bar", "Alert Text: south"] self.do_perform_test(caplog, sample, expected) def test_testPlugins(self, caplog): sample = os.path.join(self.misc_path, "testPlugins.html") expected = [ "Shockwave Flash 10.0.64.0", "Windows Media Player 7", "Adobe Acrobat", ] self.do_perform_test(caplog, sample, expected) def test_testNode(self, caplog): sample = os.path.join(self.misc_path, "testNode.html") expected = ["thelink", "thediv"] self.do_perform_test(caplog, sample, expected) def test_testNode2(self, caplog): sample = os.path.join(self.misc_path, "testNode2.html") expected = ["thelink", "thediv2"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector.html") expected = ["Alert Text: Have a Good life.", "CoursesWeb.net"] self.do_perform_test(caplog, sample, expected) def test_testQuerySelector2(self, caplog): sample = os.path.join(self.misc_path, "testQuerySelector2.html") expected = ["CoursesWeb.net", "MarPlo.net", "php.net"] self.do_perform_test(caplog, sample, expected) def test_testScope(self, caplog): sample = os.path.join(self.misc_path, "testScope.html") expected = [ "foobar", "foo", "bar", "True", "3", "2012-10-07 11:13:00", "3.14159265359", "/foo/i", ] self.do_perform_test(caplog, sample, expected) def test_testSessionStorage(self, caplog): sample = os.path.join(self.misc_path, "testSessionStorage.html") expected = ["key1", "key2", "value1", "value3"] self.do_perform_test(caplog, sample, expected) def test_testSetInterval(self, caplog): sample = os.path.join(self.misc_path, "testSetInterval.html") expected = ["[Window] Alert Text: Hello"] self.do_perform_test(caplog, sample, expected) def test_testText(self, caplog): sample = os.path.join(self.misc_path, "testText.html") expected = [ '<p id="p1">First line of paragraph.<br/> Some text added dynamically. </p>' ] self.do_perform_test(caplog, sample, expected) def test_testWindowOnload(self, caplog): sample = os.path.join(self.misc_path, "testWindowOnload.html") expected = ["[Window] Alert Text: Fired"] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML1(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML1.html") expected = ['<div id="five">five</div><div id="one">one</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML2(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML2.html") expected = ['<div id="two"><div id="six">six</div>two</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML3(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML3.html") expected = ['<div id="three">three<div id="seven">seven</div></div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML4(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML4.html") expected = ['<div id="four">four</div><div id="eight">eight</div>'] self.do_perform_test(caplog, sample, expected) def test_testInsertAdjacentHTML5(self, caplog): sample = os.path.join(self.misc_path, "testInsertAdjacentHTML5.html") expected = ["insertAdjacentHTML does not support notcorrect operation"] self.do_perform_test(caplog, sample, expected) def test_testCurrentScript(self, caplog): sample = os.path.join(self.misc_path, "testCurrentScript.html") expected = [ "[Window] Alert Text: This page has scripts", "[Window] Alert Text: text/javascript", "[Window] Alert Text: Just a useless script", ] self.do_perform_test(caplog, sample, expected) def test_testChrome(self, caplog): sample = os.path.join(self.misc_path, "testChrome.html") expected = [ "[Window] Alert Text: [object Object]", ] self.do_perform_test(caplog, sample, expected) def test_testTextNode(self, caplog): sample = os.path.join(self.misc_path, "testTextNode.html") expected = [ "nodeName: #text", "nodeType: 3", "Object: [object Text]", "nodeValue: Hello World", "Length: 11", "Substring(2,5): llo W", "New nodeValue (replace): HelloAWorld", "New nodeValue (delete 1): HelloWorld", "Index error (delete 2)", "New nodeValue (delete 3): Hello", "New nodeValue (append): Hello Test", "Index error (insert 1)", "New nodeValue (insert 2): Hello New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testCommentNode(self, caplog): sample = os.path.join(self.misc_path, "testCommentNode.html") expected = [ "nodeName: #comment", "nodeType: 8", "Object: [object Comment]", "nodeValue: <!--Hello World-->", "Length: 18", "Substring(2,5): --Hel", "New nodeValue (replace): <!--HAllo World-->", "New nodeValue (delete 1): <!--Hllo World-->", "Index error (delete 2)", "New nodeValue (delete 3): <!--H", "New nodeValue (append): <!--H Test", "Index error (insert 1)", "New nodeValue (insert 2): <!--H New Test", "New nodeValue (reset): Reset", ] self.do_perform_test(caplog, sample, expected) def test_testDOMImplementation(self, caplog): sample = os.path.join(self.misc_path, "testDOMImplementation.html") expected = [ "hasFeature('core'): true", ] self.do_perform_test(caplog, sample, expected) def test_testAttrNode(self, caplog): sample = os.path.join(self.misc_path, "testAttrNode.html") expected = [ "Object: [object Attr]", "nodeName: test", "nodeType: 2", "nodeValue: foo", "Length: undefined", "New nodeValue: test2", "Parent: null", "Owner: null", "Name: test", "Specified: true", "childNodes length: 0", ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild.html") expected = [ "innerText: Old child", "[ERROR] Attempting to replace with a null element", "[ERROR] Attempting to replace a null element", "[ERROR] Attempting to replace with an invalid element", "[ERROR] Attempting to replace an invalid element", "[ERROR] Attempting to replace on a read-only element failed", "Alert Text: New child", '<div id="foobar"><!--Just a comment--></div>', ] self.do_perform_test(caplog, sample, expected) def test_testCookie(self, caplog): sample = os.path.join(self.misc_path, "testCookie.html") expected = ["favorite_food=tripe", "name=oeschger"] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment1(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment1.html") expected = [ "<div><p>Test</p></div>", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment2(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment2.html") expected = [ '<div id="foobar"><b>This is B</b></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentFragment3(self, caplog): sample = os.path.join(self.misc_path, "testDocumentFragment3.html") expected = [ "foo:bar", ] self.do_perform_test(caplog, sample, expected) def test_testClassList2(self, caplog): sample = os.path.join(self.misc_path, "testClassList2.html") expected = [ '[Initial value] <div class="foo"></div>', '[After remove and add] <div class="anotherclass"></div>', "[Item] anotherclass", "[Empty item] null", "[Toggle visible] true", '[After multiple adds] <div class="anotherclass visible foo bar baz"></div>', '[After multiple removes] <div class="anotherclass visible"></div>', '[After replace] <div class="visible justanotherclass"></div>', '[After toggle] <div class="justanotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testClassList4(self, caplog): sample = os.path.join(self.misc_path, "testClassList4.html") expected = [ '[After remove and add] <div class="anotherclass"></div>', ] self.do_perform_test(caplog, sample, expected) def test_testDocumentType(self, caplog): sample = os.path.join(self.misc_path, "testDocumentType.html") expected = [ "Doctype: [object DocumentType]", "Doctype name: html", "Doctype nodeName: html", "Doctype nodeType: 10", "Doctype nodeValue: null", "Doctype publicId: ", "Doctype systemId: ", "Doctype textContent: null", ] self.do_perform_test(caplog, sample, expected) def test_testRemoveChild(self, caplog): sample = os.path.join(self.misc_path, "testRemoveChild.html") expected = [ "<div>Don't care about me</div>", "[ERROR] Attempting to remove null element", "[ERROR] Attempting to remove an invalid element", "[ERROR] Attempting to remove a read-only element", "[ERROR] Attempting to remove an element not in the tree", "[ERROR] Attempting to remove from a read-only element", ] self.do_perform_test(caplog, sample, expected) def test_testNamedNodeMap(self, caplog): sample = os.path.join(self.misc_path, "testNamedNodeMap.html") expected = [ "hasAttributes (before removal): true", "hasAttribute('id'): true", "First test: id->p1", "Second test: id->p1", "Third test: id->p1", "Fourth test: id->p1", "Fifth test failed", "Not existing: null", "hasAttributes (after removal): false", "Sixth test: foo->bar", "Seventh test: foo->bar2", "Final attributes length: 1", ] self.do_perform_test(caplog, sample, expected) def test_testEntityReference(self, caplog): sample = os.path.join(self.misc_path, "testEntityReference.html") expected = [ "node: [object EntityReference]", "name: &", "nodeName: &", "nodeType: 5", "nodeValue: null", ] self.do_perform_test(caplog, sample, expected) def test_getElementsByTagName(self, caplog): sample = os.path.join(self.misc_path, "testGetElementsByTagName.html") expected = [ "[object HTMLHtmlElement]", "[object HTMLHeadElement]", "[object HTMLBodyElement]", "[object HTMLParagraphElement]", "[object HTMLScriptElement]", ] self.do_perform_test(caplog, sample, expected) def test_testDocumentElement(self, caplog): sample = os.path.join(self.misc_path, "testDocumentElement.html") expected = ['<a href="http://www.google.com">Google</a>'] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute1(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute1.html") expected = ["Attribute: bar", "Attribute (after removal): null"] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute2(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute2.html") expected = [ "[element workaround redirection] about:blank -> https://buffer.github.io/thug/notexists.html", "[element workaround redirection] about:blank -> https://buffer.github.io/thug/", ] self.do_perform_test(caplog, sample, expected) def test_testSetAttribute3(self, caplog): sample = os.path.join(self.misc_path, "testSetAttribute3.html") expected = [ "Alert Text: foo", "Alert Text: bar", "Alert Text: test", "Alert Text: foobar", ] self.do_perform_test(caplog, sample, expected) def test_testCDATASection(self, caplog): sample = os.path.join(self.misc_path, "testCDATASection.html") expected = [ "nodeName: #cdata-section", "nodeType: 4", "<xml>&lt;![CDATA[Some &lt;CDATA&gt; data &amp; then some]]&gt;</xml>", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLCollection.html") expected = [ '<div id="odiv1">Page one</div>', '<div name="odiv2">Page two</div>', ] self.do_perform_test(caplog, sample, expected) def test_testProcessingInstruction(self, caplog): sample = os.path.join(self.misc_path, "testProcessingInstruction.html") expected = [ "[object ProcessingInstruction]", "nodeName: xml-stylesheet", "nodeType: 7", 'nodeValue: href="mycss.css" type="text/css"', "target: xml-stylesheet", ] self.do_perform_test(caplog, sample, expected) def test_testWindow(self, caplog): sample = os.path.join(self.misc_path, "testWindow.html") expected = [ "window: [object Window]", "self: [object Window]", "top: [object Window]", "length: 0", "history: [object History]", "pageXOffset: 0", "pageYOffset: 0", "screen: [object Screen]", "screenLeft: 0", "screenX: 0", "confirm: true", ] self.do_perform_test(caplog, sample, expected) def test_testObject1(self, caplog): sample = os.path.join(self.misc_path, "testObject1.html") expected = [ "[object data redirection] about:blank -> https://github.com/buffer/thug/raw/master/tests/test_files/sample.swf" ] self.do_perform_test(caplog, sample, expected) def test_testReplaceChild2(self, caplog): sample = os.path.join(self.misc_path, "testReplaceChild2.html") expected = ['<div id="foobar"><div id="test"></div></div>'] self.do_perform_test(caplog, sample, expected) def test_testNavigator(self, caplog): sample = os.path.join(self.misc_path, "testNavigator.html") expected = [ "window: [object Window]", "appCodeName: Mozilla", "appName: Netscape", "appVersion: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36", "cookieEnabled: true", "onLine: true", "platform: Win32", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLOptionsCollection(self, caplog): sample = os.path.join(self.misc_path, "testHTMLOptionsCollection.html") expected = [ "length: 4", "item(0): Volvo", "namedItem('audi'): Audi", "namedItem('mercedes').value: mercedes", "[After remove] item(0): Saab", "[After first add] length: 4", "[After first add] item(3): foobar", "[After second add] length: 5", "[After second add] item(3): test1234", "Not found error", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLAnchorElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLAnchorElement.html") expected = [ "a.protocol: https:", "a.host: www.example.com:1234", "a.hostname: www.example.com", "a.port: 1234", "b.protocol: :", "b.host: ", "b.hostname: ", "b.port: ", "c.protocol: https:", "c.host: www.example.com", "c.hostname: www.example.com", "c.port: ", "e.pathname: /foo/index.html", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLTableElement3(self, caplog): sample = os.path.join(self.misc_path, "testHTMLTableElement3.html") expected = [ "tHead: [object HTMLTableSectionElement]", "tFoot: [object HTMLTableSectionElement]", "caption: [object HTMLTableCaptionElement]", "row: [object HTMLTableRowElement]", "tBodies: [object HTMLCollection]", "cell: [object HTMLTableCellElement]", "cell.innerHTML: New cell 1", "row.deleteCell(10) failed", "row.deleteCell(20) failed", ] self.do_perform_test(caplog, sample, expected) def test_testTextArea(self, caplog): sample = os.path.join(self.misc_path, "testTextArea.html") expected = ["type: textarea", "cols: 100", "rows: 25"] self.do_perform_test(caplog, sample, expected) def test_testHTMLDocument(self, caplog): sample = os.path.join(self.misc_path, "testHTMLDocument.html") expected = [ "document.title: Test", "document.title: Foobar", "anchors: [object HTMLCollection]", "anchors length: 1", "anchors[0].name: foobar", "applets: [object HTMLCollection]", "applets length: 2", "applets[0].code: HelloWorld.class", "links: [object HTMLCollection]", "links length: 1", "links[0].href: https://github.com/buffer/thug/", "images: [object HTMLCollection]", "images length: 1", "images[0].href: test.jpg", "disabled: false", "head: [object HTMLHeadElement]", "referrer: ", "URL: about:blank", "Alert Text: Hello, world", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLFormElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLFormElement.html") expected = [ "[object HTMLFormElement]", "f.elements: [object HTMLFormControlsCollection]", "f.length: 4", "f.name: [object HTMLFormControlsCollection]", "f.acceptCharset: ", "f.action: /cgi-bin/test", "f.enctype: application/x-www-form-urlencoded", "f.encoding: application/x-www-form-urlencoded", "f.method: POST", "f.target: ", ] self.do_perform_test(caplog, sample, expected) def test_testApplet(self, caplog): sample = os.path.join(self.misc_path, "testApplet.html") expected = ["[applet redirection]"] self.do_perform_test(caplog, sample, expected) def test_testFrame(self, caplog): sample = os.path.join(self.misc_path, "testFrame.html") expected = [ "[frame redirection]", "Alert Text: https://buffer.github.io/thug/" "Alert Text: data:text/html,<script>alert('Hello world');</script>", ] self.do_perform_test(caplog, sample, expected) def test_testIFrame(self, caplog): sample = os.path.join(self.misc_path, "testIFrame.html") expected = ["[iframe redirection]", "width: 3", "height: 4"] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement.html") expected = [ "src (before changes): test.jpg", "src (after first change): test2.jpg", "onerror handler fired", ] self.do_perform_test(caplog, sample, expected) def test_testHTMLImageElement2(self, caplog): sample = os.path.join(self.misc_path, "testHTMLImageElement2.html") expected = [ "Alert Text: Inside onerror handler", "[ERROR][_handle_onerror] ReferenceError: foobar is not defined", ] self.do_perform_test(caplog, sample, expected) def test_testTitle(self, caplog): sample = os.path.join(self.misc_path, "testTitle.html") expected = ["New title: Foobar"] self.do_perform_test(caplog, sample, expected) def test_testCSSStyleDeclaration(self, caplog): sample = os.path.join(self.misc_path, "testCSSStyleDeclaration.html") expected = [ "style: [object CSSStyleDeclaration]", "length: 1", "cssText: color: blue;", "color: blue", "item(0): color", "item(100):", "getPropertyValue('color'): blue", "length (after removeProperty): 0", "cssText: foo: bar;", ] self.do_perform_test(caplog, sample, expected) def test_testFormProperty(self, caplog): sample = os.path.join(self.misc_path, "testFormProperty.html") expected = ["[object HTMLFormElement]", "formA"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule1(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule1.html") expected = ["[font face redirection]", "http://192.168.1.100/putty.exe"] self.do_perform_test(caplog, sample, expected) def test_testFontFaceRule2(self, caplog): sample = os.path.join(self.misc_path, "testFontFaceRule2.html") expected = [ "[font face redirection]", "https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf", ] self.do_perform_test(caplog, sample, expected) def test_testHistory(self, caplog): sample = os.path.join(self.misc_path, "testHistory.html") expected = [ "history: [object History]", "window: [object Window]", "navigationMode (before change): automatic", "navigationMode (after change): fast", ] self.do_perform_test(caplog, sample, expected) def test_testConsole(self, caplog): sample = os.path.join(self.misc_path, "testConsole.html") expected = [ "[object Console]", "[Console] assert(True, 'Test assert')", "[Console] count() = 1", "[Console] count('foobar') = 1", "[Console] count('foobar') = 2", "[Console] error('Test error')", "[Console] log('Hello world!')", "[Console] group()", "[Console] log('Hello again, this time inside a group!')", "[Console] groupEnd()", "[Console] groupCollapsed()", "[Console] info('Hello again')", "[Console] warn('Hello again')", ] self.do_perform_test(caplog, sample, expected) def test_testDataset(self, caplog): sample = os.path.join(self.misc_path, "testDataset.html") expected = [ "el.id: user", "el.dataset.id: 1234567890", "el.dataset.user: carinaanand", "el.dataset.dateOfBirth: 1960-10-03", ] self.do_perform_test(caplog, sample, expected)
30,026
Python
.py
662
35.009063
153
0.594854
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,719
test_Encoding.py
buffer_thug/tests/Encoding/test_Encoding.py
# coding=utf-8 from thug.Encoding.Encoding import Encoding encoding = Encoding() class TestEncoding: def test_string(self): result = encoding.detect("sample-content") assert result["encoding"] in ("ascii",) def test_unicode(self): result = encoding.detect("sample-content") assert result["encoding"] in ("ascii",) def test_utf8_bom(self): result = encoding.detect(b"\xef\xbb\xbf") assert result["encoding"] in ("UTF-8-SIG",) def test_unicode_utf8(self): result = encoding.detect("函数") assert result["encoding"] in ("utf-8",)
616
Python
.py
16
31.8125
51
0.650255
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,720
test_BaseLogging.py
buffer_thug/tests/Logging/test_BaseLogging.py
import os import shutil import logging import configparser import pytest import thug from thug.Logging.BaseLogging import BaseLogging from thug.ThugAPI.ThugOpts import ThugOpts configuration_path = thug.__configuration_path__ config = configparser.ConfigParser() conf_file = os.path.join(configuration_path, "thug.conf") config.read(conf_file) log = logging.getLogger("Thug") log.personalities_path = thug.__personalities_path__ if configuration_path else None log.ThugOpts = ThugOpts() base_logging = BaseLogging() class TestBaseLogging: def test_set_basedir(self): url = "/path/to/example" base_logging.set_basedir(url) assert not os.path.isdir(base_logging.baseDir) base_logging.baseDir = "" log.ThugOpts.file_logging = True base_logging.set_basedir(url) log_path = os.path.dirname( os.path.dirname(base_logging.baseDir) ) # TODO: Make this neat assert os.path.isdir(base_logging.baseDir) # Testing the self.baseDir variable base_logging.set_basedir(url) # Testing the thug_csv base_logging.baseDir = "" base_logging.set_basedir(url) assert os.path.isdir(base_logging.baseDir) base_logging.set_basedir("/path/to/example1") shutil.rmtree(log_path) assert not os.path.isdir(base_logging.baseDir) def test_set_absbasedir(self): url = "../example" base_logging.set_absbasedir(url) assert os.path.isdir(url) with pytest.raises(OSError): base_logging.set_absbasedir("/etc/perm-den") # Testing the try-except clause base_logging.set_absbasedir(url) shutil.rmtree(url) log.ThugOpts.file_logging = False base_logging.set_absbasedir(url) assert not os.path.isdir(url) def test_json_module(self): log.ThugOpts.json_logging = True assert base_logging.check_module("json", config) log.ThugOpts.json_logging = False assert not base_logging.check_module("json", config) def test_mongodb_module(self): assert not base_logging.check_module("mongodb", config) def test_elasticsearch_module(self): assert not base_logging.check_module("elasticsearch", config)
2,280
Python
.py
58
32.534483
84
0.692238
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,721
test_LoggingModules.py
buffer_thug/tests/Logging/test_LoggingModules.py
import thug.Logging.LoggingModules as log_modules class TestLoggingModules: def test_json(self): assert log_modules.LoggingModules["json"] is log_modules.JSON.JSON def test_mongodb(self): assert log_modules.LoggingModules["mongodb"] is log_modules.MongoDB.MongoDB def test_elasticsearch(self): assert ( log_modules.LoggingModules["elasticsearch"] is log_modules.ElasticSearch.ElasticSearch )
464
Python
.py
11
34.636364
83
0.714922
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,722
test_ThugLogging.py
buffer_thug/tests/Logging/test_ThugLogging.py
import os import logging import thug from thug.ThugAPI.ThugOpts import ThugOpts from thug.DOM.HTTPSession import HTTPSession from thug.Logging.ThugLogging import ThugLogging from thug.Classifier.URLClassifier import URLClassifier from thug.Classifier.SampleClassifier import SampleClassifier configuration_path = thug.__configuration_path__ log = logging.getLogger("Thug") log.configuration_path = configuration_path log.personalities_path = thug.__personalities_path__ if configuration_path else None log.PyHooks = dict() log.ThugOpts = ThugOpts() log.HTTPSession = HTTPSession() log.URLClassifier = URLClassifier() log.SampleClassifier = SampleClassifier() thug_logging = ThugLogging() class TestThugLogging: js = "var i = 0;" cert = "sample-certificate" content = b"sample, content" cwd_path = os.path.dirname(os.path.realpath(__file__)) jar_path = os.path.join(cwd_path, os.pardir, "test_files/sample.jar") sample = { "sha1": "b13d13733c4c9406fd0e01485bc4a34170b7d326", "ssdeep": "24:9EGtDqSyDVHNkCq4LOmvmuS+MfTAPxokCOB:97tG5DjQ4LDs+sTAPxLT", "sha256": "459bf0aeda19633c8e757c05ee06b8121a51217cea69ce60819bb34092a296a0", "type": "JAR", "md5": "d4be8fbeb3a219ec8c6c26ffe4033a16", } def test_set_url(self): thug_logging.set_url("https://www.example.com") assert thug_logging.url in ("https://www.example.com",) def test_add_code_snippet(self): log.ThugOpts.code_logging = False tag_hex = thug_logging.add_code_snippet( self.js, "Javascript", "Contained_Inside" ) assert not tag_hex log.ThugOpts.code_logging = True assert not thug_logging.add_code_snippet( "var", "Javascript", "Contained", check=True ) tag_hex = thug_logging.add_code_snippet( self.js, "Javascript", "Contained_Inside" ) assert tag_hex def test_add_shellcode_snippet(self): tag_hex = thug_logging.add_shellcode_snippet( "sample", "Assembly", "Shellcode", "Static Analysis" ) assert tag_hex def test_log_file(self): sample = thug_logging.log_file(data="") assert not sample data = open(self.jar_path, "rb").read() sample = thug_logging.log_file(data=data, url=self.jar_path, sampletype="JAR") assert sample["sha1"] in ("b13d13733c4c9406fd0e01485bc4a34170b7d326",) def test_log_event(self, caplog): caplog.clear() log.ThugOpts.file_logging = True thug_logging.log_event() assert "Thug analysis logs saved" in caplog.text log.ThugOpts.file_logging = False def test_log_connection(self): thug_logging.log_connection("referer", "url", "href") def test_log_location(self): thug_logging.log_location("https://example.com", None) def test_log_exploit_event(self, caplog): caplog.clear() thug_logging.log_exploit_event( "https://www.example.com", "module", "sample-description" ) assert "[module] sample-description" in caplog.text def test_log_classifier(self, caplog): caplog.clear() thug_logging.log_classifier("sample", self.jar_path, "N/A", None) assert "[SAMPLE Classifier]" in caplog.text assert "(Rule: N/A, Classification: None)" in caplog.text def test_log_screenshot(self, caplog): caplog.clear() thug_logging.set_basedir("url") thug_logging.log_screenshot("url", self.content) def test_log_redirect(self, caplog): pass def test_log_href_direct(self, caplog): caplog.clear() thug_logging.log_href_redirect("referer", "url") assert "[HREF Redirection (document.location)]" in caplog.text assert "Content-Location: referer --> Location: url" in caplog.text def test_log_certificate(self, caplog): caplog.clear() log.ThugOpts.cert_logging = False log.ThugOpts.verbose = True thug_logging.log_certificate("url", self.cert) assert "[Certificate]" not in caplog.text log.ThugOpts.cert_logging = True thug_logging.log_certificate("url", self.cert) assert "%s" % (self.cert,) in caplog.text log.ThugOpts.verbose = False def test_log_honeyagent(self): log.ThugOpts.file_logging = True path = "%s.json" % (self.sample["md5"],) thug_logging.log_honeyagent(os.getcwd(), self.sample, self.content) assert self.content in open(path, "rb").read() os.remove(path) log.ThugOpts.file_logging = False def test_store_content(self): log.ThugOpts.file_logging = True fname = thug_logging.store_content(os.getcwd(), "sample.csv", self.content) path = os.path.join(os.getcwd(), "sample.csv") assert fname == path assert self.content in open(path, "rb").read() os.remove(path) log.ThugOpts.file_logging = False fname = thug_logging.store_content(os.getcwd(), "sample.csv", self.content) assert not fname
5,111
Python
.py
118
35.872881
86
0.667743
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,723
test_SampleLogging.py
buffer_thug/tests/Logging/test_SampleLogging.py
import os from thug.Logging.SampleLogging import SampleLogging sample_logging = SampleLogging() class TestSampleLogging: cwd_path = os.path.dirname(os.path.realpath(__file__)) samples_path = os.path.join(cwd_path, os.pardir, os.pardir, "tests/test_files") pe_path = os.path.join(samples_path, "sample.exe") pdf_path = os.path.join(samples_path, "sample.pdf") jar_path = os.path.join(samples_path, "sample.jar") swf_path = os.path.join(samples_path, "sample.swf") doc_path = os.path.join(samples_path, "sample.doc") rtf_path = os.path.join(samples_path, "sample.rtf") elf_path = os.path.join(samples_path, "sample.elf") def test_get_none(self): assert not sample_logging.get_sample_type("") def test_get_pe(self): file_type = sample_logging.get_sample_type(open(self.pe_path, "rb").read()) assert file_type in ("PE",) def test_get_pdf(self): file_type = sample_logging.get_sample_type(open(self.pdf_path, "rb").read(1024)) assert file_type in ("PDF",) def test_get_jar(self): file_type = sample_logging.get_sample_type(open(self.jar_path, "rb").read()) assert file_type in ("JAR",) def test_get_swf(self): file_type = sample_logging.get_sample_type(open(self.swf_path, "rb").read()) assert file_type in ("SWF",) def test_get_doc(self): file_type = sample_logging.get_sample_type(open(self.doc_path, "rb").read()) assert file_type in ("DOC",) def test_get_rtf(self): file_type = sample_logging.get_sample_type(open(self.rtf_path, "rb").read()) assert file_type in ("RTF",) def test_get_elf(self): file_type = sample_logging.get_sample_type(open(self.elf_path, "rb").read()) assert file_type in ("ELF",) def test_get_imphash(self): imphash = sample_logging.get_imphash(open(self.pe_path, "rb").read()) assert imphash in ("5ef204cfbc53779500a050c36dea14fc",) imphash = sample_logging.get_imphash(open(self.doc_path, "rb").read()) assert not imphash def test_build_sample(self): data = open(self.pe_path, "rb").read() build = sample_logging.build_sample( data=data, url=self.pe_path, sampletype="PE" ) assert build build = sample_logging.build_sample(data=data, url=self.pe_path) assert build build = sample_logging.build_sample(data=b"") assert not build build = sample_logging.build_sample(data=b"not_valid") assert not build
2,562
Python
.py
53
40.943396
88
0.649398
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,724
test_Mapper.py
buffer_thug/tests/Logging/modules/test_Mapper.py
import os import json from thug.Logging.modules.Mapper import DictDiffer from thug.Logging.modules.Mapper import Mapper class TestDictDiffer: """ Unittests for the methods of class DictDiffer @curr_dict: 1) Value for k1 key is changed from v2 to v1 2) k3 key is added 3) k5 key is removed """ curr_dict = {"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"} past_dict = {"k1": "v2", "k2": "v2", "k4": "v4", "k5": "v5"} dict_differ = DictDiffer(curr_dict, past_dict) def test_added(self): added_keys = self.dict_differ.added() assert added_keys in ({"k3"},) def test_removed(self): removed_keys = self.dict_differ.removed() assert removed_keys in ({"k5"},) def test_changed(self): changed_keys = self.dict_differ.changed() assert changed_keys in ({"k1"},) def test_unchanged(self): unchanged_keys = self.dict_differ.unchanged() assert unchanged_keys in ({"k2", "k4"},) def test_anychange(self): assert self.dict_differ.anychange() assert not DictDiffer(self.curr_dict, self.curr_dict).anychange() class TestMapper: cwd_path = os.path.dirname(os.path.realpath(__file__)) json_path = os.path.join(cwd_path, os.pardir, os.pardir, "test_files/Mapper") data_file = os.path.join(json_path, "test_data.json") error_file = os.path.join(json_path, "test_error.json") data = json.load(open(data_file, "r")) image_loc = data["locations"][0] markup_loc = data["locations"][1] exec_loc = data["locations"][2] unknown_loc = data["locations"][3] iframe_con = data["connections"][0] link_con = data["connections"][1] mapper = Mapper("sample-mapper-dir", simplify=True) def test_get_shape(self): shape = self.mapper.get_shape(self.markup_loc) assert shape in ("box",) shape = self.mapper.get_shape(self.image_loc) assert shape in ("oval",) shape = self.mapper.get_shape(self.exec_loc) assert shape in ("hexagon",) assert not self.mapper.get_shape(self.unknown_loc) def test_get_fillcolor(self): fillcolor = self.mapper.get_fillcolor(self.image_loc) assert fillcolor in ("orange",) fillcolor = self.mapper.get_fillcolor(self.markup_loc) assert not fillcolor def test_get_color(self): color = self.mapper.get_color(self.iframe_con) assert color in ("orange",) color = self.mapper.get_color(self.link_con) assert not color def test_normalize_url(self): sample_url = self.image_loc["url"] assert self.mapper.normalize_url(sample_url + "/") in (sample_url,) assert self.mapper.normalize_url(sample_url) in (sample_url,) def test_add_weak_location(self): self.mapper.add_weak_location("https://www.ex.com") assert len(self.mapper.data["locations"]) in (1,) def test_add_file(self): self.mapper.add_file(self.data_file) assert len(self.mapper.data["locations"]) in (5,) assert len(self.mapper.data["connections"]) in (2,) # Testing for ValueError because of malformed JSON self.mapper.add_file(self.error_file) assert len(self.mapper.data["locations"]) in (5,) assert len(self.mapper.data["connections"]) in (2,) def test_write_text(self): con1_string = "www.example.com -- iframe --> www.example2.com \n" con2_string = "www.example.com -- link --> www.example1.com \n" res = con1_string + con2_string assert self.mapper.write_text() in (res,) def test_write_svg(self): self.mapper.write_svg() assert os.path.isfile("graph.svg") os.remove("graph.svg") assert not os.path.isfile("graph.svg") def test_follow_track(self): self.mapper.follow_track("www.example2.com") self.test_write_svg()
3,930
Python
.py
88
37.159091
81
0.636483
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,725
test_JSON.py
buffer_thug/tests/Logging/modules/test_JSON.py
# coding=utf-8 import os import io import shutil import logging import thug from thug.ThugAPI.ThugOpts import ThugOpts from thug.Logging.modules.JSON import JSON from thug.ThugAPI.ThugVulnModules import ThugVulnModules from thug.Logging.ThugLogging import ThugLogging from thug.Encoding.Encoding import Encoding configuration_path = thug.__configuration_path__ log = logging.getLogger("Thug") log.personalities_path = thug.__personalities_path__ if configuration_path else None log.ThugOpts = ThugOpts() log.configuration_path = configuration_path log.ThugLogging = ThugLogging() log.ThugVulnModules = ThugVulnModules() log.Encoding = Encoding() log.PyHooks = dict() json = JSON() class TestJSON: cve = "CVE-XXXX" url = "sample-url" data = "sample-data" desc = "sample-desc" file_data = { "content": data, "status": 200, "md5": "ba4ba63ec75693aedfebc7299a4f7661", "sha256": "c45df724cba87ac84892bf3eeb910393d69d163e9ad96cac2e2074487eaa907b", "fsize": 11, # len(data) "ctype": "text/plain", "mtype": "text/plain", } base_dir = "sample-basedir" code_snippet = "var i = 12;" base64_snippet = "dmFyIGkgPSAxMjs=" favicon_dhash = "55aa554d2da796165500d755692bbeb6" language = "Javascript" relationship = "Contained_Inside" tag = "Tag" # TODO: Better tag method = "Dynamic Analysis" def test_json_enabled(self): log.ThugOpts.json_logging = True assert json.json_enabled log.ThugOpts.json_logging = False assert not json.json_enabled def test_get_vuln_module(self): acropdf = json.get_vuln_module("acropdf") assert acropdf in ("9.1.0",) assert "disabled" in json.get_vuln_module("unknown") def test_fix(self): encoded_data = json.fix("") assert "" in (encoded_data,) encoded_data = json.fix("sample\n-\ncontent") assert "sample-content" in (encoded_data,) encoded_data = json.fix("sample\n-\ncontent(í)", drop_spaces=False) assert "sample\n-\ncontent(í)" in (encoded_data,) def test_set_url(self): json.set_url(self.url) assert not json.data["url"] log.ThugOpts.json_logging = True json.set_url(self.url) log.ThugOpts.json_logging = False assert self.url in (json.data["url"],) def test_add_code_snippet(self): json.add_code_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert not json.data["code"] log.ThugOpts.json_logging = True json.add_code_snippet( self.code_snippet, self.language, self.relationship, self.tag ) data = json.data["code"][0] log.ThugOpts.json_logging = False assert self.code_snippet in (data["snippet"],) assert self.language in (data["language"],) assert self.relationship in (data["relationship"],) assert self.tag in (data["tag"],) assert self.method in (data["method"],) def test_add_shellcode_snippet(self): json.data["code"] = [] json.add_shellcode_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert not json.data["code"] log.ThugOpts.json_logging = True json.add_shellcode_snippet( self.code_snippet, self.language, self.relationship, self.tag ) data = json.data["code"][0] log.ThugOpts.json_logging = False assert self.base64_snippet in (data["snippet"],) assert self.language in (data["language"],) assert self.relationship in (data["relationship"],) assert self.tag in (data["tag"],) assert self.method in (data["method"],) def test_log_connection(self): json.log_connection("source", "destination", "link") assert not json.data["connections"] log.ThugOpts.json_logging = True json.log_connection("source1", "destination1", "link") connections = json.data["connections"][0] assert "source1" in (connections["source"],) assert "destination1" in (connections["destination"],) assert "link" in (connections["method"],) assert "source1 -- link --> destination1" in ( json.data["behavior"][0]["description"], ) json.log_connection("source1", "destination1", "link", {"exploit": "EXC"}) assert "[Exploit] source1 -- link --> destination1" in ( json.data["behavior"][1]["description"], ) log.ThugOpts.json_logging = False def test_get_content(self): content = json.get_content(self.file_data) assert self.data in (content,) log.ThugOpts.code_logging = False content = json.get_content(self.file_data) log.ThugOpts.code_logging = True assert "NOT AVAILABLE" in (content,) def test_log_location(self): json.log_location(self.url, self.file_data) assert not json.data["locations"] log.ThugOpts.json_logging = True json.log_location(self.url, self.file_data) locations_json = json.data["locations"][0] log.ThugOpts.json_logging = False assert self.url in (locations_json["url"],) assert self.file_data["content"] in (locations_json["content"],) assert self.file_data["status"] in (locations_json["status"],) assert self.file_data["ctype"] in (locations_json["content-type"],) assert self.file_data["md5"] in (locations_json["md5"],) assert self.file_data["sha256"] in (locations_json["sha256"],) assert self.file_data["fsize"] in (locations_json["size"],) assert self.file_data["mtype"] in (locations_json["mimetype"],) def test_log_exploit_event(self): json.log_exploit_event(self.url, "ActiveX", self.desc, self.cve, self.data) assert not json.data["exploits"] log.ThugOpts.json_logging = True json.log_exploit_event(self.url, "ActiveX", self.desc, self.cve, self.data) exploit_json = json.data["exploits"][0] log.ThugOpts.json_logging = False assert self.url in (exploit_json["url"],) assert "ActiveX" in (exploit_json["module"],) assert self.desc in (exploit_json["description"],) assert self.cve in (exploit_json["cve"],) assert self.data in (exploit_json["data"],) def test_log_classifier(self): json.log_classifier("exploit", self.url, self.cve, None) assert not json.data["classifiers"] log.ThugOpts.json_logging = True json.log_classifier("exploit", self.url, self.cve, None) classifier_json = json.data["classifiers"][0] log.ThugOpts.json_logging = False assert "exploit" in (classifier_json["classifier"],) assert self.url in (classifier_json["url"],) assert self.cve in (classifier_json["rule"],) assert not classifier_json["tags"] def test_add_behaviour_warn(self): json.data["behavior"] = [] json.add_behavior_warn(self.desc, self.cve, self.code_snippet) assert not json.data["behavior"] log.ThugOpts.json_logging = True json.add_behavior_warn() assert not json.data["behavior"] json.add_behavior_warn(self.desc, self.cve, self.code_snippet) behaviour_json = json.data["behavior"][0] log.ThugOpts.json_logging = False assert self.desc in (behaviour_json["description"],) assert self.cve in (behaviour_json["cve"],) assert self.code_snippet in (behaviour_json["snippet"],) assert self.method in (behaviour_json["method"],) def test_log_file(self): json.log_file(self.base_dir) assert not json.data["files"] log.ThugOpts.json_logging = True json.log_file(self.base_dir) log.ThugOpts.json_logging = False assert self.base_dir in json.data["files"] def test_log_image_ocr(self): json.log_image_ocr("url", "result") assert not json.data["images"] log.ThugOpts.json_logging = True json.log_image_ocr("url", "result") assert json.data["images"] log.ThugOpts.json_logging = False def test_log_screenshot(self): json.log_screenshot("url", b"data") assert not json.data["screenshots"] log.ThugOpts.json_logging = True json.log_screenshot("url", b"data") assert json.data["screenshots"] log.ThugOpts.json_logging = False def test_export(self): log.ThugOpts.json_logging = True log.ThugOpts.file_logging = True json.export(self.base_dir) assert json.cached_data assert os.path.isdir(self.base_dir) json.cached_data = None shutil.rmtree(self.base_dir) log.ThugOpts.json_logging = False log.ThugOpts.file_logging = False json.export(self.base_dir) assert not os.path.isdir(self.base_dir) def test_get_json_data(self): output = io.StringIO() output.write(self.data) json.cached_data = output data = json.get_json_data(self.base_dir) assert self.data in (data,) json.cached_data = None assert not json.get_json_data(self.base_dir) def test_log_favicon(self): log.ThugOpts.json_logging = False json.log_favicon("https://example.com/favicon.ico", self.favicon_dhash) assert len(json.data["favicons"]) == 0 log.ThugOpts.json_logging = True json.log_favicon("https://example.com/favicon.ico", self.favicon_dhash) assert len(json.data["favicons"]) == 1 log.ThugOpts.json_logging = False
9,729
Python
.py
224
35.397321
85
0.644
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,726
test_ElasticSearch.py
buffer_thug/tests/Logging/modules/test_ElasticSearch.py
import os import logging import configparser from mock import patch import pytest import thug from thug.Logging.modules.ElasticSearch import ElasticSearch from thug.ThugAPI.ThugVulnModules import ThugVulnModules from thug.ThugAPI.ThugOpts import ThugOpts log = logging.getLogger("Thug") cwd_path = os.path.dirname(os.path.realpath(__file__)) configuration_path = os.path.join(cwd_path, os.pardir, os.pardir, "test_files") log.configuration_path = thug.__configuration_path__ log.personalities_path = thug.__personalities_path__ if configuration_path else None log.ThugVulnModules = ThugVulnModules() log.ThugOpts = ThugOpts() log.ThugOpts.useragent = "winxpie60" config = configparser.ConfigParser() conf_file = os.path.join(log.configuration_path, "thug.conf") config.read(conf_file) IN_GITHUB_ACTIONS = os.getenv("GITHUB_ACTIONS") == "true" and os.getenv( "RUNNER_OS" ) in ("Linux",) class TestElasticSearch: @pytest.mark.skipif( not (IN_GITHUB_ACTIONS), reason="Test works just in Github Actions (Linux)" ) def test_export(self): log.ThugOpts.elasticsearch_logging = True log.configuration_path = configuration_path assert log.ThugOpts.elasticsearch_logging elastic_search = ElasticSearch() response = elastic_search.export("sample-dir") enabled = elastic_search.enabled assert response assert enabled log.ThugOpts.elasticsearch_logging = False log.configuration_path = thug.__configuration_path__ assert not log.ThugOpts.elasticsearch_logging def test_disable_opt(self): elastic_search = ElasticSearch() response = elastic_search.export("sample-dir") enabled = elastic_search.enabled assert not response assert not enabled @patch("configparser.ConfigParser.getboolean", return_value=False) def test_disable_conf(self, mocked_parser): log.ThugOpts.elasticsearch_logging = True log.configuration_path = configuration_path assert log.ThugOpts.elasticsearch_logging elastic_search = ElasticSearch() enabled = elastic_search.enabled assert not enabled log.ThugOpts.elasticsearch_logging = False log.configuration_path = thug.__configuration_path__ assert not log.ThugOpts.elasticsearch_logging @patch("elasticsearch.Elasticsearch") def test_ping_error(self, mocked_es, caplog): caplog.clear() ping_mock = mocked_es.return_value.ping ping_mock.return_value = False log.ThugOpts.elasticsearch_logging = True log.configuration_path = configuration_path elastic_search = ElasticSearch() enabled = elastic_search.enabled log.ThugOpts.elasticsearch_logging = False log.configuration_path = thug.__configuration_path__ assert not enabled assert ( "[WARNING] ElasticSearch instance not properly initialized" in caplog.text ) assert not log.ThugOpts.elasticsearch_logging def test_no_conf_path(self): log.ThugOpts.elasticsearch_logging = True log.configuration_path = "non/existing/path" assert log.ThugOpts.elasticsearch_logging elastic_search = ElasticSearch() enabled = elastic_search.enabled assert not enabled log.ThugOpts.elasticsearch_logging = False log.configuration_path = thug.__configuration_path__ assert not log.ThugOpts.elasticsearch_logging
3,511
Python
.py
82
36.158537
86
0.718612
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,727
test_ExploitGraph.py
buffer_thug/tests/Logging/modules/test_ExploitGraph.py
import json from thug.Logging.modules.ExploitGraph import ExploitGraph class TestExploitGraph: url = "www.example.com" source = "www.ex1.com" dest = "www.ex2.com" method = "iframe" exploit_graph = ExploitGraph(url) def test_init(self): assert self.exploit_graph.G.graph["url"] in (self.url,) assert self.exploit_graph.G.graph["name"] in ("thug-exploit-graph",) def test_add_connection(self): self.exploit_graph.add_connection(self.source, self.dest, self.method) nodes = self.exploit_graph.G.nodes assert self.source in nodes assert self.dest in nodes edge = list(self.exploit_graph.G.edges(data=True))[0] assert self.source in edge assert self.dest in edge assert {"method": self.method} in edge def test_draw(self): graph = json.loads(self.exploit_graph.draw()) assert graph["directed"] assert graph["multigraph"] assert graph["graph"] assert graph["nodes"] assert graph["links"]
1,050
Python
.py
27
31.666667
78
0.659113
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,728
test_MongoDB.py
buffer_thug/tests/Logging/modules/test_MongoDB.py
# coding=utf-8 import logging import pymongo from mock import patch import mongomock import thug from thug.ThugAPI.ThugOpts import ThugOpts from thug.Logging.modules.MongoDB import MongoDB from thug.ThugAPI.ThugVulnModules import ThugVulnModules from thug.Logging.ThugLogging import ThugLogging from thug.Encoding.Encoding import Encoding from thug.DOM.HTTPSession import HTTPSession configuration_path = thug.__configuration_path__ log = logging.getLogger("Thug") log.personalities_path = thug.__personalities_path__ if configuration_path else None log.ThugOpts = ThugOpts() log.configuration_path = configuration_path log.ThugLogging = ThugLogging() log.ThugVulnModules = ThugVulnModules() log.Encoding = Encoding() log.HTTPSession = HTTPSession() log.PyHooks = dict() class TestMongoDB: cve = "CVE-XXXX" url = "www.example.com" data = b"sample-data" desc = "sample-desc" cert = "sample-cert" file_data = { "sha1": "b13d13733c4c9406fd0e01485bc4a34170b7d326", "data": data, "ssdeep": "24:9EGtDqSyDVHNkCq4LOmvmuS+MfTAPxokCOB:97tG5DjQ4LDs+sTAPxLT", "sha256": "459bf0aeda19633c8e757c05ee06b8121a51217cea69ce60819bb34092a296a0", "type": "JAR", "md5": "d4be8fbeb3a219ec8c6c26ffe4033a16", } base_dir = "path/to/sample/basedir" code_snippet = b"var i = 12;" base64_snippet = "dmFyIGkgPSAxMjs=" favicon_dhash = "55aa554d2da796165500d755692bbeb6" language = "Javascript" relationship = "Contained_Inside" tag = "Tag" # TODO: Better tag method = "Dynamic Analysis" source = "www.ex1.com" dest = "www.ex2.com" con_method = "iframe" # Creating a MongoDB object for all the test methods. with ( patch(pymongo.__name__ + ".MongoClient", new=mongomock.MongoClient), patch("gridfs.Database", new=mongomock.database.Database), ): log.ThugOpts.mongodb_address = "mongodb://localhost:123" mongo = MongoDB() log.ThugOpts.mongodb_address = None @patch(pymongo.__name__ + ".MongoClient", new=mongomock.MongoClient) @patch("gridfs.Database", new=mongomock.database.Database) def test_address(self): log.ThugOpts.mongodb_address = "syntax-error://localhost:123" mongo = MongoDB() log.ThugOpts.mongodb_address = None assert not mongo.enabled def test_init(self): """ Testing for conf file 'thug.conf' """ mongo = MongoDB() assert not mongo.enabled def test_make_counter(self): counter = self.mongo.make_counter(2) assert next(counter) in (2,) assert next(counter) in (3,) def test_get_url(self): assert self.mongo.urls.count_documents({}) in (0,) self.mongo.get_url(self.url) assert self.mongo.urls.count_documents({}) in (1,) # Testing for Duplicate entry self.mongo.get_url(self.url) assert self.mongo.urls.count_documents({}) in (1,) def test_set_url(self): self.mongo.enabled = False self.mongo.set_url(self.url) assert self.mongo.analyses.count_documents({}) in (0,) self.mongo.enabled = True log.ThugVulnModules.disable_acropdf() self.mongo.set_url(self.url) log.ThugVulnModules._acropdf_disabled = ( False # TODO: Have enable_acropdf() function? ) analysis = self.mongo.analyses.find_one({"thug.plugins.acropdf": "disabled"}) assert analysis assert self.mongo.analyses.count_documents({}) in (1,) def test_log_location(self): self.mongo.enabled = False self.mongo.log_location(self.url, self.file_data) assert self.mongo.locations.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_location(self.url, self.file_data) assert self.mongo.locations.count_documents({}) in (1,) def test_log_connection(self): self.mongo.enabled = False self.mongo.log_connection(self.source, self.dest, self.con_method) assert self.mongo.connections.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_connection(self.source, self.dest, self.con_method) assert self.mongo.connections.count_documents({}) in (1,) nodes = self.mongo.graph.G.nodes assert self.source in nodes assert self.dest in nodes def test_log_exploit_event(self): self.mongo.enabled = False self.mongo.log_exploit_event(self.url, "ActiveX", self.desc, self.cve) assert self.mongo.exploits.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_exploit_event(self.url, "ActiveX", self.desc, self.cve) assert self.mongo.exploits.count_documents({}) in (1,) def test_log_image_ocr(self): self.mongo.enabled = False self.mongo.log_image_ocr(self.url, "Test") assert self.mongo.images.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_image_ocr(self.url, "Test") assert self.mongo.images.count_documents({}) in (1,) def test_log_classifier(self): self.mongo.enabled = False self.mongo.log_classifier("exploit", self.url, self.cve, self.tag) assert self.mongo.classifiers.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_classifier("exploit", self.url, self.cve, self.tag) assert self.mongo.classifiers.count_documents({}) in (1,) @patch("gridfs.grid_file.Collection", new=mongomock.collection.Collection) def test_log_file(self): self.mongo.enabled = False self.mongo.log_file(self.file_data) assert self.mongo.samples.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_file(self.file_data) assert self.mongo.samples.count_documents({}) in (1,) # Testing for duplicate entry self.mongo.log_file(self.file_data) assert self.mongo.samples.count_documents({}) in (1,) def test_log_json(self): self.mongo.enabled = False self.mongo.log_json(self.base_dir) assert self.mongo.json.count_documents({}) in (0,) # Setting self.mongo.enabled = True self.mongo.enabled = True self.mongo.log_json(self.base_dir) assert self.mongo.json.count_documents({}) in (0,) # Enabling json_logging log.ThugOpts.json_logging = True self.mongo.log_json(self.base_dir) log.ThugOpts.json_logging = False assert self.mongo.json.count_documents({}) in (0,) def test_log_screenshot(self): self.mongo.enabled = False self.mongo.log_screenshot(self.url, self.data) assert self.mongo.screenshots.count_documents({}) in (0,) # Setting self.mongo.enabled = True self.mongo.enabled = True self.mongo.log_screenshot(self.url, self.data) assert self.mongo.screenshots.count_documents({}) in (1,) def test_log_event(self): self.mongo.enabled = False self.mongo.log_event(self.base_dir) assert self.mongo.graphs.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_event(self.base_dir) assert self.mongo.graphs.count_documents({}) in (1,) def test_fix(self): encoded_data = self.mongo.fix("") assert "" in (encoded_data,) encoded_data = self.mongo.fix("sample\n-\ncontent") assert "sample-content" in (encoded_data,) encoded_data = self.mongo.fix("sample\n-\ncontent(í)", drop_spaces=False) assert "sample\n-\ncontent(í)" in (encoded_data,) def test_add_code_snippet(self): self.mongo.enabled = False self.mongo.add_code_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert self.mongo.codes.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.add_code_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert self.mongo.codes.count_documents({}) in (1,) def test_add_shellcode_snippet(self): self.mongo.codes.delete_many({}) self.mongo.enabled = False self.mongo.add_shellcode_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert self.mongo.codes.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.add_shellcode_snippet( self.code_snippet, self.language, self.relationship, self.tag ) assert self.mongo.codes.count_documents({}) in (1,) def test_add_behaviour_warn(self): self.mongo.enabled = False self.mongo.add_behavior_warn(self.desc, self.cve, self.code_snippet) assert self.mongo.behaviors.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.add_behavior_warn(self.desc, self.cve, self.code_snippet) assert self.mongo.behaviors.count_documents({}) in (1,) self.mongo.add_behavior_warn() assert self.mongo.behaviors.count_documents({}) in (1,) def test_log_certificate(self): self.mongo.enabled = False self.mongo.log_certificate(self.url, self.cert) assert self.mongo.certificates.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_certificate(self.url, self.cert) assert self.mongo.certificates.count_documents({}) in (1,) def test_log_honeyagent(self): assert self.mongo.honeyagent.count_documents({}) in (0,) self.mongo.log_honeyagent(self.file_data, "sample-report") assert self.mongo.honeyagent.count_documents({}) in (1,) def test_log_cookies(self): assert self.mongo.cookies.count_documents({}) in (0,) log.HTTPSession.cookies.set("domain", "test.com") self.mongo.log_cookies() assert self.mongo.honeyagent.count_documents({}) in (1,) def test_log_favicon(self): self.mongo.enabled = False self.mongo.log_favicon(self.url, self.favicon_dhash) assert self.mongo.favicons.count_documents({}) in (0,) self.mongo.enabled = True self.mongo.log_favicon(self.url, self.favicon_dhash) assert self.mongo.favicons.count_documents({}) in (1,)
10,350
Python
.py
231
37.047619
85
0.662458
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,729
test_ThugAPI.py
buffer_thug/tests/ThugAPI/test_ThugAPI.py
import os import shutil import logging import pytest from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestThugAPI: thug_api = ThugAPI() cwd_path = os.path.dirname(os.path.realpath(__file__)) samples_path = os.path.join(cwd_path, os.pardir, "test_files") yara_file = os.path.join(samples_path, "test_yara") log_url = os.path.join(samples_path, "../log-dir-example") log_file = os.path.join(samples_path, "test-filehandler") def test_version(self): with pytest.raises(SystemExit): # TODO: Needs assert statement by mocking print self.thug_api.version() def test_useragent(self): assert self.thug_api.get_useragent() in ("winxpie60",) self.thug_api.set_useragent("winxpchrome20") assert self.thug_api.get_useragent() in ("winxpchrome20",) def test_events(self): assert self.thug_api.get_events() in ([],) self.thug_api.set_events("event1,event2,event2,event3") assert self.thug_api.get_events() in (["event1", "event2", "event3"],) def test_delay(self): assert self.thug_api.get_delay() in (0,) self.thug_api.set_delay(10) assert self.thug_api.get_delay() in (10,) def test_attachment(self): assert not self.thug_api.get_attachment() self.thug_api.set_attachment() assert self.thug_api.get_attachment() def test_file_logging(self): assert not self.thug_api.get_file_logging() self.thug_api.set_file_logging() assert self.thug_api.get_file_logging() def test_json_logging(self): assert not self.thug_api.get_json_logging() self.thug_api.set_json_logging() assert self.thug_api.get_json_logging() def test_elasticsearch_logging(self): assert not self.thug_api.get_elasticsearch_logging() self.thug_api.set_elasticsearch_logging() assert self.thug_api.get_elasticsearch_logging() assert logging.getLogger("elasticsearch").getEffectiveLevel() in ( logging.ERROR, ) def test_referer(self): assert self.thug_api.get_referer() in ("about:blank",) self.thug_api.set_referer("https://www.example.com") assert self.thug_api.get_referer() in ("https://www.example.com",) def test_proxy(self): assert self.thug_api.get_proxy() is None self.thug_api.set_proxy("http://www.example.com") assert self.thug_api.get_proxy() in ("http://www.example.com",) def test_raise_for_proxy(self): assert self.thug_api.get_raise_for_proxy() self.thug_api.set_raise_for_proxy(False) assert not self.thug_api.get_raise_for_proxy() def test_no_fetch(self): assert not log.ThugOpts.no_fetch self.thug_api.set_no_fetch() assert log.ThugOpts.no_fetch def test_verbose(self): assert not log.ThugOpts.verbose self.thug_api.set_verbose() assert log.ThugOpts.verbose assert log.getEffectiveLevel() in (logging.INFO,) def test_debug(self): assert not log.ThugOpts.debug self.thug_api.set_debug() assert log.ThugOpts.debug assert log.getEffectiveLevel() in (logging.DEBUG,) def test_ast_debug(self): assert not log.ThugOpts.ast_debug self.thug_api.set_ast_debug() assert log.ThugOpts.ast_debug def test_http_debug(self): assert log.ThugOpts.http_debug in (0,) self.thug_api.set_http_debug() assert log.ThugOpts.http_debug in (1,) self.thug_api.set_http_debug() assert log.ThugOpts.http_debug in (2,) def test_acropdf_pdf(self): assert log.ThugVulnModules.acropdf_pdf in ("9.1.0",) self.thug_api.set_acropdf_pdf( "1.0.0", ) assert log.ThugVulnModules.acropdf_pdf in ("1.0.0",) def test_disable_acropdf(self): assert not log.ThugVulnModules.acropdf_disabled self.thug_api.disable_acropdf() assert log.ThugVulnModules.acropdf_disabled def test_shockwave_flash(self): assert log.ThugVulnModules.shockwave_flash in ("10.0.64.0",) self.thug_api.set_shockwave_flash( "8.0", ) assert log.ThugVulnModules.shockwave_flash in ("8.0",) def test_disable_shockwave_flash(self): assert not log.ThugVulnModules.shockwave_flash_disabled self.thug_api.disable_shockwave_flash() assert log.ThugVulnModules.shockwave_flash_disabled def test_javaplugin(self): assert log.ThugVulnModules.javaplugin in ("160_32",) self.thug_api.set_javaplugin( "1.0", ) assert log.ThugVulnModules.javaplugin in ("100_00",) def test_disable_javaplugin(self): assert not log.ThugVulnModules.javaplugin_disabled self.thug_api.disable_javaplugin() assert log.ThugVulnModules.javaplugin_disabled def test_silverlight(self): assert log.ThugVulnModules.silverlight in ("4.0.50826.0",) self.thug_api.set_silverlight( "1.0", ) assert log.ThugVulnModules.silverlight in ("1.0",) def test_disable_silverlight(self): assert not log.ThugVulnModules.silverlight_disabled self.thug_api.disable_silverlight() assert log.ThugVulnModules.silverlight_disabled def test_threshold(self): assert self.thug_api.get_threshold() in (0,) self.thug_api.set_threshold(5) assert self.thug_api.get_threshold() in (5,) def test_extensive(self): self.thug_api.reset_extensive() assert not self.thug_api.get_extensive() self.thug_api.set_extensive() assert self.thug_api.get_extensive() def test_timeout(self): assert self.thug_api.get_timeout() in (600,) self.thug_api.set_timeout(300) assert self.thug_api.get_timeout() in (300,) def test_connect_timeout(self): assert self.thug_api.get_connect_timeout() in (10,) self.thug_api.set_connect_timeout(20) assert self.thug_api.get_connect_timeout() in (20,) def test_proxy_connect_timeout(self): assert self.thug_api.get_proxy_connect_timeout() in (5,) self.thug_api.set_proxy_connect_timeout(10) assert self.thug_api.get_proxy_connect_timeout() in (10,) self.thug_api.set_proxy_connect_timeout("foo") assert self.thug_api.get_proxy_connect_timeout() in (10,) def test_broken_url(self): assert not self.thug_api.get_broken_url() self.thug_api.set_broken_url() assert self.thug_api.get_broken_url() def test_web_tracking(self): assert not self.thug_api.get_web_tracking() self.thug_api.set_web_tracking() assert self.thug_api.get_web_tracking() def test_honeyagent(self): assert log.ThugOpts.honeyagent self.thug_api.disable_honeyagent() assert not log.ThugOpts.honeyagent def test_awis(self): assert not log.ThugOpts.awis self.thug_api.enable_awis() assert log.ThugOpts.awis self.thug_api.disable_awis() def test_code_logging(self): self.thug_api.enable_code_logging() assert log.ThugOpts.code_logging self.thug_api.disable_code_logging() assert not log.ThugOpts.code_logging def test_cert_logging(self): self.thug_api.enable_cert_logging() assert log.ThugOpts.cert_logging self.thug_api.disable_cert_logging() assert not log.ThugOpts.cert_logging def test_log_init(self): log.ThugOpts.file_logging = True url = "../thugapi-example" self.thug_api.log_init(url) base_dir = log.ThugLogging.baseDir log_path = os.path.dirname(os.path.dirname(base_dir)) # TODO: Make this neat assert os.path.isdir(base_dir) shutil.rmtree(log_path) assert not os.path.isdir(base_dir) def test_log_dir(self): self.thug_api.set_log_dir(self.log_url) assert os.path.isdir(self.log_url) shutil.rmtree(self.log_url) assert not os.path.isdir(self.log_url) def test_log_output(self): self.thug_api.set_log_output(self.log_file) assert isinstance(log.handlers[0], logging.FileHandler) assert os.path.isfile(self.log_file) os.remove(self.log_file) assert not os.path.isfile(self.log_file) def test_mongodb_address(self): assert self.thug_api.get_mongodb_address() is None self.thug_api.set_mongodb_address("127.0.0.1:27017") assert self.thug_api.get_mongodb_address() in ("127.0.0.1:27017",) def test_add_htmlclassifier(self): self.thug_api.add_htmlclassifier(self.yara_file) rules = log.HTMLClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_urlclassifier(self): self.thug_api.add_urlclassifier(self.yara_file) rules = log.URLClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_jsclassifier(self): self.thug_api.add_jsclassifier(self.yara_file) rules = log.JSClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_vbsclassifier(self): self.thug_api.add_vbsclassifier(self.yara_file) rules = log.VBSClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_textclassifier(self): self.thug_api.add_textclassifier(self.yara_file) rules = log.TextClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_cookieclassifier(self): self.thug_api.add_cookieclassifier(self.yara_file) rules = log.CookieClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_sampleclassifier(self): self.thug_api.add_sampleclassifier(self.yara_file) rules = log.SampleClassifier._rules match = False for ns in rules: if self.yara_file in rules[ns]: match = True assert match is True def test_add_htmlfilter(self): self.thug_api.add_htmlfilter(self.yara_file) filters = log.HTMLClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_urlfilter(self): self.thug_api.add_urlfilter(self.yara_file) filters = log.URLClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_jsfilter(self): self.thug_api.add_jsfilter(self.yara_file) filters = log.JSClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_vbsfilter(self): self.thug_api.add_vbsfilter(self.yara_file) filters = log.VBSClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_textfilter(self): self.thug_api.add_textfilter(self.yara_file) filters = log.TextClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_cookiefilter(self): self.thug_api.add_cookiefilter(self.yara_file) filters = log.CookieClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_add_samplefilter(self): self.thug_api.add_samplefilter(self.yara_file) filters = log.SampleClassifier._filters match = False for ns in filters: if self.yara_file in filters[ns]: match = True assert match is True def test_log_event(self, caplog): caplog.clear() log.ThugOpts.file_logging = True self.thug_api.log_event() assert "Thug analysis logs saved" in caplog.text assert os.path.isdir(self.log_url) shutil.rmtree(self.log_url) assert not os.path.isdir(self.log_url) def test_analyse(self): with pytest.raises(NotImplementedError): self.thug_api.analyze()
13,174
Python
.py
320
32.075
88
0.639623
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,730
test_Watchdog.py
buffer_thug/tests/ThugAPI/test_Watchdog.py
import logging import time from mock import patch import thug from thug.ThugAPI.ThugOpts import ThugOpts from thug.ThugAPI.Watchdog import Watchdog from thug.DOM.HTTPSession import HTTPSession from thug.Logging.ThugLogging import ThugLogging from thug.Classifier.URLClassifier import URLClassifier from thug.Classifier.SampleClassifier import SampleClassifier configuration_path = thug.__configuration_path__ log = logging.getLogger("Thug") log.configuration_path = configuration_path log.personalities_path = thug.__personalities_path__ if configuration_path else None log.ThugOpts = ThugOpts() log.HTTPSession = HTTPSession() log.URLClassifier = URLClassifier() log.SampleClassifier = SampleClassifier() log.ThugLogging = ThugLogging() @patch("os.kill") class TestWatchDog: def callback(self, signum, frame): log.warning("Signal no. is {}".format(signum)) def test_watch(self, os_kill): with Watchdog(0, callback=self.callback): time.sleep(1) assert not os_kill.called def test_abort(self, os_kill, caplog): caplog.clear() with Watchdog(1, callback=self.callback): time.sleep(2) assert os_kill.called assert "The analysis took more than 1 second(s). Aborting!" in caplog.text assert "Signal no. is 14" in caplog.text
1,329
Python
.py
34
34.852941
84
0.75642
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,731
test_ThugOpts.py
buffer_thug/tests/ThugAPI/test_ThugOpts.py
import pytest import logging import thug from thug.ThugAPI.ThugOpts import ThugOpts configuration_path = thug.__configuration_path__ log = logging.getLogger("Thug") log.configuration_path = configuration_path log.personalities_path = thug.__personalities_path__ if configuration_path else None class TestThugOpts: opts = ThugOpts() def test_verbose(self): self.opts.verbose = True assert self.opts.verbose self.opts.verbose = False assert not self.opts.verbose def test_debug(self): self.opts.debug = True assert self.opts.debug self.opts.debug = False assert not self.opts.debug def test_proxy(self): self.opts.proxy = "" assert self.opts.proxy is None self.opts.proxy = "http://www.example.com" addr = self.opts.proxy assert addr in ("http://www.example.com",) self.opts.proxy = None assert self.opts.proxy is None def test_error_proxy(self, caplog): caplog.clear() with pytest.raises(SystemExit): self.opts.proxy = "ftp://www.example.com" assert "[ERROR] Invalid proxy scheme" in caplog.text def test_raise_for_proxy(self): self.opts.raise_for_proxy = False assert not self.opts.raise_for_proxy self.opts.raise_for_proxy = True assert self.opts.raise_for_proxy def test_useragent(self): assert self.opts.useragent in ("winxpie60",) self.opts.useragent = "linuxchrome26" ua = self.opts.useragent assert ua in ("linuxchrome26",) def test_warning_useragent(self, caplog): caplog.clear() self.opts.useragent = "nonexistent-ua" assert "[WARNING] Invalid User Agent provided" in caplog.text def test_referer(self): assert self.opts.referer in ("about:blank",) self.opts.referer = "https://www.example.com" referer = self.opts.referer assert referer in ("https://www.example.com",) def test_events(self): sample_events = "event1,event2,event2,event3" assert self.opts.events in ([],) self.opts.events = "" assert self.opts.events in ([],) self.opts.events = sample_events event_list = self.opts.events assert event_list in (["event1", "event2", "event3"],) def test_delay(self): assert self.opts.delay in (0,) self.opts.delay = 10 time = self.opts.delay assert time in (10,) def test_warning_delay(self, caplog): caplog.clear() self.opts.delay = "a" assert "[WARNING] Ignoring invalid delay value" in caplog.text def test_attachment(self): self.opts.attachment = True assert self.opts.attachment self.opts.attachment = False assert not self.opts.attachment def test_file_logging(self): self.opts.file_logging = True assert self.opts.file_logging self.opts.file_logging = False assert not self.opts.file_logging def test_json_logging(self): self.opts.json_logging = True assert self.opts.json_logging self.opts.json_logging = False assert not self.opts.json_logging def test_elasticsearch_logging(self): self.opts.elasticsearch_logging = True assert self.opts.elasticsearch_logging self.opts.elasticsearch_logging = False assert not self.opts.elasticsearch_logging def test_code_logging(self): self.opts.code_logging = False assert not self.opts.code_logging self.opts.code_logging = True assert self.opts.code_logging def test_cert_logging(self): self.opts.cert_logging = False assert not self.opts.cert_logging self.opts.cert_logging = True assert self.opts.cert_logging def test_no_fetch(self): self.opts.no_fetch = True assert self.opts.no_fetch self.opts.no_fetch = False assert not self.opts.no_fetch def test_threshold(self): assert self.opts.threshold in (0,) self.opts.threshold = 5 pages = self.opts.threshold assert pages in (5,) def test_warning_threshold(self, caplog): caplog.clear() self.opts.threshold = "a" assert "[WARNING] Ignoring invalid threshold value" in caplog.text def test_connect_timeout(self): assert self.opts.connect_timeout in (10,) self.opts.connect_timeout = 20 time = self.opts.connect_timeout assert time in (20,) def test_warning_connect_timeout(self, caplog): caplog.clear() self.opts.connect_timeout = "a" assert "[WARNING] Ignoring invalid connect timeout value" in caplog.text def test_timeout(self): assert self.opts.timeout in (600,) self.opts.timeout = 300 time = self.opts.timeout assert time in (300,) def test_warning_timeout(self, caplog): caplog.clear() self.opts.timeout = "a" assert "[WARNING] Ignoring invalid timeout value" in caplog.text def test_broken_url(self): self.opts.broken_url = True assert self.opts.broken_url self.opts.broken_url = False assert not self.opts.broken_url def test_web_tracking(self): self.opts.web_tracking = True assert self.opts.web_tracking self.opts.web_tracking = False assert not self.opts.web_tracking def test_honeyagent(self): self.opts.honeyagent = False assert not self.opts.honeyagent self.opts.honeyagent = True assert self.opts.honeyagent def test_mongodb_address(self): assert self.opts.mongodb_address is None self.opts.mongodb_address = "127.0.0.1:27017" addr = self.opts.mongodb_address assert addr in ("127.0.0.1:27017",)
5,904
Python
.py
151
30.900662
84
0.652021
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,732
test_ThugVulnModules.py
buffer_thug/tests/ThugAPI/test_ThugVulnModules.py
from thug.ThugAPI.ThugVulnModules import ThugVulnModules class TestThugVulnModules: vuln_modules = ThugVulnModules() def test_invalid_version(self): assert not self.vuln_modules.invalid_version("1.6.0.32") assert not self.vuln_modules.invalid_version("1") assert self.vuln_modules.invalid_version("1.6.A.32") # Acropdf def test_acropdf(self): acropdf_version = self.vuln_modules.acropdf_pdf assert acropdf_version in ("9.1.0",) self.vuln_modules.acropdf_pdf = "1.0.0" acropdf_version = self.vuln_modules.acropdf # Testing the 'acropdf' property assert acropdf_version in ("1.0.0",) def test_warning_acropdf(self, caplog): caplog.clear() self.vuln_modules.acropdf_pdf = "1.0.A" assert "[WARNING] Invalid Adobe Acrobat Reader version provided" in caplog.text def test_disable_acropdf(self): self.vuln_modules.disable_acropdf() assert self.vuln_modules.acropdf_disabled # Shockwave-flash def test_shockwave_flash(self): shockwave_version = self.vuln_modules.shockwave_flash assert shockwave_version in ("10.0.64.0",) self.vuln_modules.shockwave_flash = "8.0" shockwave_version = self.vuln_modules.shockwave_flash assert shockwave_version in ("8.0",) def test_warning_shockwave_flash(self, caplog): caplog.clear() self.vuln_modules.shockwave_flash = "1.0" assert "[WARNING] Invalid Shockwave Flash version provided" in caplog.text def test_disable_shockwave_flash(self): self.vuln_modules.disable_shockwave_flash() assert self.vuln_modules.shockwave_flash_disabled # Java def test_javaplugin(self): javaplugin_version = self.vuln_modules.javaplugin assert javaplugin_version in ("160_32",) self.vuln_modules.javaplugin = "1.0" javaplugin_version = self.vuln_modules.javaplugin assert javaplugin_version in ("100_00",) def test_warning_javaplugin(self, caplog): caplog.clear() self.vuln_modules.javaplugin = "1.A" assert "[WARNING] Invalid JavaPlugin version provided" in caplog.text def test_disable_javaplugin(self): self.vuln_modules.disable_javaplugin() assert self.vuln_modules.javaplugin_disabled def test_javawebstart_isinstalled(self): version = self.vuln_modules.javawebstart_isinstalled assert version in ("1.0.0.0",) # Silverlight def test_silverlight(self): silverlight_version = self.vuln_modules.silverlight assert silverlight_version in ("4.0.50826.0",) self.vuln_modules.silverlight = "1.0" silverlight_version = self.vuln_modules.silverlight assert silverlight_version in ("1.0",) def test_warning_silverlight(self, caplog): caplog.clear() self.vuln_modules.silverlight = "6.0" assert "[WARNING] Invalid Silverlight version provided" in caplog.text def test_disable_silverlight(self): self.vuln_modules.disable_silverlight() assert self.vuln_modules.silverlight_disabled
3,144
Python
.py
66
39.666667
87
0.691225
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,733
test_OpaqueFilter.py
buffer_thug/tests/ThugAPI/test_OpaqueFilter.py
from thug.ThugAPI.OpaqueFilter import OpaqueFilter class TestOpaqueFilter: opaque_filter = OpaqueFilter() def test_filter(self): assert not self.opaque_filter.filter("sample-record")
202
Python
.py
5
35.6
61
0.773196
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,734
test_abstractmethod.py
buffer_thug/tests/ThugAPI/test_abstractmethod.py
import pytest from thug.ThugAPI.abstractmethod import abstractmethod class SampleClass: @abstractmethod def sample_method(self): pass def test_error(): sample = SampleClass() with pytest.raises(NotImplementedError): sample.sample_method()
276
Python
.py
10
22.9
54
0.750958
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,735
test_java.py
buffer_thug/tests/Java/test_java.py
from thug.Java.java import java from thug.Java.lang import lang def test_java(): obj_java = java() assert isinstance(obj_java.lang, lang)
148
Python
.py
5
26.6
42
0.744681
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,736
test_System.py
buffer_thug/tests/Java/test_System.py
import logging from thug.Java.System import System from thug.ThugAPI.ThugVulnModules import ThugVulnModules log = logging.getLogger("Thug") log.ThugVulnModules = ThugVulnModules() class TestSystem: system = System() def test_version(self): version = self.system.getProperty("java.version") assert version in ("1.6.0_32",) def test_vendor(self): vendor = self.system.getProperty("java.vendor") assert vendor in ("Sun Microsystems Inc.",)
487
Python
.py
13
32.615385
57
0.726496
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,737
test_lang.py
buffer_thug/tests/Java/test_lang.py
from thug.Java.lang import lang from thug.Java.System import System def test_lang(): obj_lang = lang() assert isinstance(obj_lang.System, System)
156
Python
.py
5
28.2
46
0.758389
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,738
test_Classifiers.py
buffer_thug/tests/Classifier/test_Classifiers.py
import os import hashlib import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestClassifiers: cwd_path = os.path.dirname(os.path.realpath(__file__)) samples_path = os.path.join(cwd_path, os.pardir, "samples/classifiers") test_files_path = os.path.join(cwd_path, os.pardir, "test_files") signatures_path = os.path.join(cwd_path, os.pardir, "signatures") def sample_passthrough(self, sample, md5): pass def image_passthrough(self, url, text): pass def cookie_passthrough(self, url, cookie): pass def do_perform_test(self, caplog, sample, expected): thug = ThugAPI() thug.log_init(sample) thug.add_htmlclassifier( os.path.join(self.signatures_path, "html_signature_1.yar") ) thug.add_textclassifier( os.path.join(self.signatures_path, "text_signature_5.yar") ) thug.add_cookieclassifier( os.path.join(self.signatures_path, "cookie_signature_8.yar") ) thug.add_sampleclassifier( os.path.join(self.signatures_path, "sample_signature_10.yar") ) thug.add_imageclassifier( os.path.join(self.signatures_path, "image_signature_14.yar") ) thug.add_htmlfilter(os.path.join(self.signatures_path, "html_filter_2.yar")) thug.add_jsfilter(os.path.join(self.signatures_path, "js_signature_2.yar")) thug.add_vbsfilter(os.path.join(self.signatures_path, "vbs_signature_6.yar")) thug.add_textfilter(os.path.join(self.signatures_path, "text_signature_5.yar")) thug.add_cookiefilter(os.path.join(self.signatures_path, "cookie_filter_9.yar")) thug.add_samplefilter( os.path.join(self.signatures_path, "sample_filter_11.yar") ) thug.add_imagefilter(os.path.join(self.signatures_path, "image_filter_16.yar")) thug.add_htmlclassifier(os.path.join(self.signatures_path, "not_existing.yar")) thug.add_htmlfilter(os.path.join(self.signatures_path, "not_existing.yar")) thug.add_customclassifier("wrong_type", "wrong_method") thug.add_customclassifier("url", "wrong_method") thug.add_customclassifier("sample", self.sample_passthrough) thug.add_customclassifier("image", self.image_passthrough) thug.add_customclassifier("cookie", self.cookie_passthrough) with open(os.path.join(self.samples_path, sample), "rb") as fd: data = fd.read() log.HTMLClassifier.classify(os.path.basename(sample), data) log.TextClassifier.classify(os.path.basename(sample), data) log.TextClassifier.classify(os.path.basename(sample), data) log.CookieClassifier.classify(os.path.basename(sample), data) log.CookieClassifier.classify(os.path.basename(sample), data) log.SampleClassifier.classify(data, hashlib.md5(data).hexdigest()) log.ImageClassifier.classify( "https://buffer.antifork.org/images/antifork.jpg", "Antifork" ) log.ImageClassifier.classify( "https://buffer.antifork.org/images/antifork.jpg", "Antifork" ) log.HTMLClassifier.filter(os.path.basename(sample), data) log.JSClassifier.filter(os.path.basename(sample), data) log.VBSClassifier.filter(os.path.basename(sample), data) log.TextClassifier.filter(os.path.basename(sample), data) log.CookieClassifier.filter(os.path.basename(sample), data) log.SampleClassifier.filter(data, hashlib.md5(data).hexdigest()) log.ImageClassifier.filter( "https://buffer.antifork.org/images/antifork.jpg", "Antifork" ) records = [r.message for r in caplog.records] matches = 0 for e in expected: for record in records: if e in record: matches += 1 assert matches >= len(expected) def test_html_classifier_1(self, caplog): sample = os.path.join(self.samples_path, "test1.html") expected = [ "[HTML Classifier] URL: test1.html (Rule: html_signature_1, Classification: strVar)" ] self.do_perform_test(caplog, sample, expected) def test_html_filter_2(self, caplog): sample = os.path.join(self.samples_path, "test2.html") expected = [ "[HTMLFILTER Classifier] URL: test2.html (Rule: html_filter_2, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_js_filter_2(self, caplog): sample = os.path.join(self.samples_path, "test2.html") expected = [ "[JSFILTER Classifier] URL: test2.html (Rule: js_signature_2, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_text_classifier_5(self, caplog): sample = os.path.join(self.samples_path, "test5.html") expected = [ "[TEXT Classifier] URL: test5.html (Rule: text_signature_5, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_text_filter_5(self, caplog): sample = os.path.join(self.samples_path, "test5.html") expected = [ "[TEXTFILTER Classifier] URL: test5.html (Rule: text_signature_5, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_vbs_filter_6(self, caplog): sample = os.path.join(self.samples_path, "test6.html") expected = [ "[VBSFILTER Classifier] URL: test6.html (Rule: vbs_signature_6, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_cookie_classifier_8(self, caplog): sample = os.path.join(self.samples_path, "cookie1.txt") expected = [ "[COOKIE Classifier] URL: cookie1.txt (Rule: cookie_signature_8, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_cookie_filter_9(self, caplog): sample = os.path.join(self.samples_path, "cookie2.txt") expected = [ "[COOKIEFILTER Classifier] URL: cookie2.txt (Rule: cookie_filter_9, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_sample_signature_10(self, caplog): sample = os.path.join(self.test_files_path, "sample.exe") expected = [ "[SAMPLE Classifier] URL: 52bfb8491cbf6c39d44d37d3c59ef406 (Rule: sample_signature_10, Classification: )" ] self.do_perform_test(caplog, sample, expected) def test_sample_filter_11(self, caplog): sample = os.path.join(self.test_files_path, "sample.exe") expected = [ "[SAMPLEFILTER Classifier] URL: 52bfb8491cbf6c39d44d37d3c59ef406 (Rule: sample_filter_11, Classification: )" ] self.do_perform_test(caplog, sample, expected)
6,918
Python
.py
140
40.257143
120
0.653561
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,739
thug.py
buffer_thug/thug/thug.py
#!/usr/bin/env python # # thug.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import sys import getopt import logging from .ThugAPI import ThugAPI from .Plugins.ThugPlugins import ThugPlugins from .Plugins.ThugPlugins import PRE_ANALYSIS_PLUGINS from .Plugins.ThugPlugins import POST_ANALYSIS_PLUGINS log = logging.getLogger("Thug") log.setLevel(logging.WARN) class Thug(ThugAPI): def __init__(self, args): self.args = args ThugAPI.__init__(self) def usage(self): msg = """ Synopsis: Thug: Pure Python honeyclient implementation Usage: thug [ options ] url Options: -h, --help \tDisplay this help information -V, --version \tDisplay Thug version -i, --list-ua \tDisplay available user agents -u, --useragent= \tSelect a user agent (use option -b for values, default: winxpie60) -e, --events= \tEnable comma-separated specified DOM events handling -w, --delay= \tSet a maximum setTimeout/setInterval delay value (in milliseconds) -n, --logdir= \tSet the log output directory -o, --output= \tLog to a specified file -r, --referer \tSpecify a referer -p, --proxy= \tSpecify a proxy (see below for format and supported schemes) -m, --attachment \tSet the attachment mode -l, --local \tAnalyze a locally saved page -x, --local-nofetch \tAnalyze a locally saved page and prevent remote content fetching -v, --verbose \tEnable verbose mode -d, --debug \tEnable debug mode -q, --quiet \tDisable console logging -g, --http-debug \tEnable HTTP debug mode -t, --threshold \tMaximum pages to fetch -j, --extensive \tExtensive fetch of linked pages -O, --connect-timeout \tSet the connect timeout (in seconds, default: 10 seconds) -Y, --proxy-connect-timeout \tSet the proxy connect timeout (in seconds, default: 5 seconds) -T, --timeout= \tSet the analysis timeout (in seconds, default: 600 seconds) -c, --broken-url \tSet the broken URL mode -z, --web-tracking \tEnable web client tracking inspection -b, --async-prefetch \tEnable async prefetching mode -k, --no-honeyagent \tDisable HoneyAgent support -a, --image-processing \tEnable image processing analysis -f, --screenshot \tEnable screenshot capturing -E, --awis \tEnable AWS Alexa Web Information Service (AWIS) -s, --no-down-prevent \tDisable download prevention mechanism Plugins: -A, --adobepdf= \tSpecify Adobe Acrobat Reader version (default: 9.1.0) -P, --no-adobepdf \tDisable Adobe Acrobat Reader plugin -S, --shockwave= \tSpecify Shockwave Flash version (default: 10.0.64.0) -R, --no-shockwave \tDisable Shockwave Flash plugin -J, --javaplugin= \tSpecify JavaPlugin version (default: 1.6.0.32) -K, --no-javaplugin \tDisable Java plugin -L, --silverlight \tSpecify SilverLight version (default: 4.0.50826.0) -N, --no-silverlight \tDisable SilverLight plugin Classifiers: --htmlclassifier= \tSpecify a list of additional (comma separated) HTML classifier rule files --urlclassifier= \tSpecify a list of additional (comma separated) URL classifier rule files --jsclassifier= \tSpecify a list of additional (comma separated) JS classifier rule files --vbsclassifier= \tSpecify a list of additional (comma separated) VBS classifier rule files --sampleclassifier= \tSpecify a list of additional (comma separated) Sample classifier rule files --textclassifier= \tSpecify a list of additional (comma separated) Text classifier rule files --cookieclassifier= \tSpecify a list of additional (comma separated) Cookie classifier rule files --imageclassifier= \tSpecify a list of additional (comma separated) Image classifier rule files --htmlfilter= \tSpecify a list of additional (comma separated) HTML filter files --urlfilter= \tSpecify a list of additional (comma separated) URL filter files --jsfilter= \tSpecify a list of additional (comma separated) JS filter files --vbsfilter= \tSpecify a list of additional (comma separated) VBS filter files --samplefilter= \tSpecify a list of additional (comma separated) Sample filter files --textfilter= \tSpecify a list of additional (comma separated) Text filter files --cookiefilter= \tSpecify a list of additional (comma separated) Cookie filter files --imagefilter= \tSpecify a list of additional (comma separated) Image filter files Logging: -F, --file-logging \tEnable file logging mode (default: disabled) -Z, --json-logging \tEnable JSON logging mode (default: disabled) -W, --features-logging \tEnable features logging mode (default: disabled) -G, --elasticsearch-logging \tEnable ElasticSearch logging mode (default: disabled) -D, --mongodb-address= \tSpecify address and port of the MongoDB instance (format: host:port) -Y, --no-code-logging \tDisable code logging -U, --no-cert-logging \tDisable SSL/TLS certificate logging Proxy Format: scheme://[username:password@]host:port (supported schemes: http, socks4, socks5, socks5h) """ print(msg) sys.exit(0) def list_ua(self): msg = """ Synopsis: Thug: Pure Python honeyclient implementation Available User-Agents: """ for key, value in sorted( iter(log.ThugOpts.Personality.items()), key=lambda k_v: (k_v[1]["id"], k_v[0]), ): msg += "\t\033[1m{:<22}\033[0m{}\n".format(key, value["description"]) # pylint: disable=consider-using-f-string print(msg) sys.exit(0) def analyze(self): p = getattr(self, "run_remote", None) try: options, args = getopt.getopt( self.args, "hViu:e:w:n:o:r:p:mzbkafEslxvdqgA:PS:RJ:KL:Nt:jO:Y:T:cFZWGYUD:", [ "help", "version", "list-ua", "useragent=", "events=", "delay=", "logdir=", "output=", "referer=", "proxy=", "attachment", "web-tracking", "async-prefetch", "no-honeyagent", "image-processing", "screenshot", "awis", "no-down-prevent", "local", "local-nofetch", "verbose", "debug", "quiet", "http-debug", "adobepdf=", "no-adobepdf", "shockwave=", "no-shockwave", "javaplugin=", "no-javaplugin", "silverlight=", "no-silverlight", "threshold=", "extensive", "connect-timeout=", "proxy-connect-timeout=", "timeout=", "broken-url", "htmlclassifier=", "urlclassifier=", "jsclassifier=", "vbsclassifier=", "sampleclassifier=", "imageclassifier=", "textclassifier=", "cookieclassifier=", "htmlfilter=", "urlfilter=", "jsfilter=", "vbsfilter=", "samplefilter=", "textfilter=", "cookiefilter=", "imagefilter=", "file-logging", "json-logging", "features-logging", "elasticsearch-logging", "no-code-logging", "no-cert-logging", "mongodb-address=", ], ) except getopt.GetoptError: self.usage() if not options and not args: self.usage() for option in options: if option[0] in ("-h", "--help"): self.usage() elif option[0] in ("-V", "--version"): self.version() elif option[0] in ("-i", "--list-ua"): self.list_ua() self.set_raise_for_proxy(False) for option in options: if option[0] in ( "-u", "--useragent", ): self.set_useragent(option[1]) elif option[0] in ("-e", "--events"): self.set_events(option[1]) elif option[0] in ("-w", "--delay"): self.set_delay(option[1]) elif option[0] in ( "-r", "--referer", ): self.set_referer(option[1]) elif option[0] in ( "-p", "--proxy", ): self.set_proxy(option[1]) elif option[0] in ( "-m", "--attachment", ): self.set_attachment() elif option[0] in ( "-z", "--web-tracking", ): self.set_web_tracking() elif option[0] in ( "-b", "--async-prefetch", ): self.set_async_prefetch() elif option[0] in ( "-k", "--no-honeyagent", ): self.disable_honeyagent() elif option[0] in ( "-a", "--image-processing", ): self.set_image_processing() elif option[0] in ( "-f", "--screenshot", ): self.enable_screenshot() elif option[0] in ( "-E", "--awis", ): self.enable_awis() elif option[0] in ( "-s", "--no-down-prevent", ): self.disable_download_prevent() elif option[0] in ( "-l", "--local", ): p = getattr(self, "run_local") elif option[0] in ( "-x", "--local-nofetch", ): p = getattr(self, "run_local") self.set_no_fetch() elif option[0] in ( "-v", "--verbose", ): self.set_verbose() elif option[0] in ( "-d", "--debug", ): self.set_debug() elif option[0] in ( "-a", "--ast-debug", ): self.set_ast_debug() elif option[0] in ( "-g", "--http-debug", ): self.set_http_debug() elif option[0] in ( "-A", "--adobepdf", ): self.set_acropdf_pdf(option[1]) elif option[0] in ( "-P", "--no-adobepdf", ): self.disable_acropdf() elif option[0] in ( "-S", "--shockwave", ): self.set_shockwave_flash(option[1]) elif option[0] in ( "-R", "--no-shockwave", ): self.disable_shockwave_flash() elif option[0] in ( "-J", "--javaplugin", ): self.set_javaplugin(option[1]) elif option[0] in ( "-K", "--no-javaplugin", ): self.disable_javaplugin() elif option[0] in ( "-L", "--silverlight", ): self.set_silverlight(option[1]) elif option[0] in ( "-N", "--no-silverlight", ): self.disable_silverlight() elif option[0] in ( "-t", "--threshold", ): self.set_threshold(option[1]) elif option[0] in ( "-j", "--extensive", ): self.set_extensive() elif option[0] in ( "-O", "--connect-timeout", ): self.set_connect_timeout(option[1]) elif option[0] in ( "-Y", "--proxy-connect-timeout", ): self.set_proxy_connect_timeout(option[1]) elif option[0] in ( "-T", "--timeout", ): self.set_timeout(option[1]) elif option[0] in ("--htmlclassifier",): for classifier in option[1].split(","): self.add_htmlclassifier(os.path.abspath(classifier)) elif option[0] in ("--urlclassifier",): for classifier in option[1].split(","): self.add_urlclassifier(os.path.abspath(classifier)) elif option[0] in ("--jsclassifier",): for classifier in option[1].split(","): self.add_jsclassifier(os.path.abspath(classifier)) elif option[0] in ("--vbsclassifier",): for classifier in option[1].split(","): self.add_vbsclassifier(os.path.abspath(classifier)) elif option[0] in ("--sampleclassifier",): for classifier in option[1].split(","): self.add_sampleclassifier(os.path.abspath(classifier)) elif option[0] in ("--textclassifier",): for classifier in option[1].split(","): self.add_textclassifier(os.path.abspath(classifier)) elif option[0] in ("--cookieclassifier",): for classifier in option[1].split(","): self.add_cookieclassifier(os.path.abspath(classifier)) elif option[0] in ("--imageclassifier",): for classifier in option[1].split(","): self.add_imageclassifier(os.path.abspath(classifier)) elif option[0] in ("--htmlfilter",): for f in option[1].split(","): self.add_htmlfilter(os.path.abspath(f)) elif option[0] in ("--urlfilter",): for f in option[1].split(","): self.add_urlfilter(os.path.abspath(f)) elif option[0] in ("--jsfilter",): for f in option[1].split(","): self.add_jsfilter(os.path.abspath(f)) elif option[0] in ("--vbsfilter",): for f in option[1].split(","): self.add_vbsfilter(os.path.abspath(f)) elif option[0] in ("--samplefilter",): for f in option[1].split(","): self.add_samplefilter(os.path.abspath(f)) elif option[0] in ("--textfilter",): for f in option[1].split(","): self.add_textfilter(os.path.abspath(f)) elif option[0] in ("--cookiefilter",): for f in option[1].split(","): self.add_cookiefilter(os.path.abspath(f)) elif option[0] in ("--imagefilter",): for f in option[1].split(","): self.add_imagefilter(os.path.abspath(f)) elif option[0] in ( "-c", "--broken-url", ): self.set_broken_url() elif option[0] in ( "-F", "--file-logging", ): self.set_file_logging() elif option[0] in ( "-Z", "--json-logging", ): self.set_json_logging() elif option[0] in ( "-W", "--features-logging", ): self.set_features_logging() elif option[0] in ( "-G", "--elasticsearch-logging", ): self.set_elasticsearch_logging() elif option[0] in ( "-Y", "--no-code-logging", ): self.disable_code_logging() elif option[0] in ( "-U", "--no-cert-logging", ): self.disable_cert_logging() elif option[0] in ( "-D", "--mongodb-address", ): self.set_mongodb_address(option[1]) self.log_init(args[0]) for option in options: if option[0] in ("-n", "--logdir"): self.set_log_dir(option[1]) elif option[0] in ( "-o", "--output", ): self.set_log_output(option[1]) elif option[0] in ( "-q", "--quiet", ): self.set_log_quiet() if p: # pylint:disable=using-constant-test ThugPlugins(PRE_ANALYSIS_PLUGINS, self)() p(args[0]) ThugPlugins(POST_ANALYSIS_PLUGINS, self)() self.log_event() return log def main(): if not os.getenv("THUG_PROFILE", None): Thug(sys.argv[1:])() else: import io import cProfile import pstats import tempfile profiler = cProfile.Profile() profiler.enable() Thug(sys.argv[1:])() profiler.disable() s = io.StringIO() ps = pstats.Stats(profiler, stream=s).sort_stats("cumulative") ps.print_stats() with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", prefix="thug-profiler-", suffix=".log", delete=False, ) as fd: print(f"Saving profiler results to {fd.name}") fd.write(s.getvalue()) if __name__ == "__main__": main()
19,877
Python
.py
492
26.754065
124
0.473774
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,740
__init__.py
buffer_thug/thug/__init__.py
import os import importlib.resources import appdirs __version__ = "6.9" __jsengine__ = "" __jsengine_version__ = "" __global_configuration_path__ = "/etc/thug" __user_configuration_path__ = f"{appdirs.user_config_dir()}/thug" __package_configuration_path__ = os.path.join(importlib.resources.files("thug"), "conf") __configuration_path__ = __package_configuration_path__ if os.path.exists(__user_configuration_path__): __configuration_path__ = __user_configuration_path__ # pragma: no cover if os.path.exists(__global_configuration_path__): __configuration_path__ = __global_configuration_path__ __personalities_path__ = os.path.join(__configuration_path__, "personalities") __rules_path__ = os.path.join(__configuration_path__, "rules") __scripts_path__ = os.path.join(__configuration_path__, "scripts") __plugins_path__ = os.path.join(__configuration_path__, "plugins") __hooks_path__ = os.path.join(__configuration_path__, "hooks") __html_rules_path__ = os.path.join(__rules_path__, "htmlclassifier") __js_rules_path__ = os.path.join(__rules_path__, "jsclassifier") __vbs_rules_path__ = os.path.join(__rules_path__, "vbsclassifier") __url_rules_path__ = os.path.join(__rules_path__, "urlclassifier") __sample_rules_path__ = os.path.join(__rules_path__, "sampleclassifier") __text_rules_path__ = os.path.join(__rules_path__, "textclassifier") __cookie_rules_path__ = os.path.join(__rules_path__, "cookieclassifier") __image_rules_path__ = os.path.join(__rules_path__, "imageclassifier") __html_filter_path__ = os.path.join(__rules_path__, "htmlfilter") __js_filter_path__ = os.path.join(__rules_path__, "jsfilter") __vbs_filter_path__ = os.path.join(__rules_path__, "vbsfilter") __url_filter_path__ = os.path.join(__rules_path__, "urlfilter") __sample_filter_path__ = os.path.join(__rules_path__, "samplefilter") __text_filter_path__ = os.path.join(__rules_path__, "textfilter") __cookie_filter_path__ = os.path.join(__rules_path__, "cookiefilter") __image_filter_path__ = os.path.join(__rules_path__, "imagefilter") try: import STPyV8 __jsengine__ = "Google V8" __jsengine_version__ = getattr(STPyV8, "__version__", "") except ImportError: # pragma: no cover pass
2,203
Python
.py
41
51.902439
88
0.681691
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,741
ContextAnalyzer.py
buffer_thug/thug/Analysis/context/ContextAnalyzer.py
#!/usr/bin/env python # # ContextAnalyzer.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import inspect import logging log = logging.getLogger("Thug") class ContextAnalyzer: def __init__(self): self.__init_checks() def __init_checks(self): self.checks = [] for name, method in inspect.getmembers(self, predicate=inspect.ismethod): if name.startswith("context_analyzer_check"): self.checks.append(method) def context_analyzer_check_sharepoint_is_anonymous_user(self, window): spPageContextInfo = getattr(window, "_spPageContextInfo", None) if ( spPageContextInfo and "isAnonymousGuestUser" in spPageContextInfo ): # pragma: no cover log.ThugLogging.log_classifier( "sharepoint", log.ThugLogging.url, "SharePointAnonymousGuestUser" ) def analyze(self, window): for m in self.checks: m(window)
1,609
Python
.py
39
34.589744
82
0.689433
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,742
Screenshot.py
buffer_thug/thug/Analysis/screenshot/Screenshot.py
import sys import logging import bs4 try: import imgkit IMGKIT_MODULE = True except ImportError: # pragma: no cover IMGKIT_MODULE = False log = logging.getLogger("Thug") class Screenshot: content_types = ("text/html",) def __init__(self): self.enable = IMGKIT_MODULE def run(self, window, url, response, ctype): if not self.enable or not log.ThugOpts.screenshot: return if not ctype.startswith(self.content_types): return # pragma: no cover soup = bs4.BeautifulSoup(response.content, "html5lib") for img in soup.find_all("img"): src = img.get("src", None) if not src: continue # pragma: no cover norm_src = log.HTTPSession.normalize_url(window, src) if norm_src: img["src"] = norm_src content = soup.prettify(formatter=None) options = {"quiet": ""} if sys.platform in ("linux",): options["xvfb"] = "" try: screenshot = imgkit.from_string(content, False, options=options) log.ThugLogging.log_screenshot(url, screenshot) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[SCREENSHOT] Error: %s", str(e))
1,309
Python
.py
35
28.685714
78
0.605556
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,743
HoneyAgent.py
buffer_thug/thug/Analysis/honeyagent/HoneyAgent.py
#!/usr/bin/env python # # HoneyAgent.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import base64 import tempfile import logging import configparser import requests log = logging.getLogger("Thug") class HoneyAgent: def __init__(self): self.enabled = True self.opts = {} self.__init_config() def __init_config(self): conf_file = os.path.join(log.configuration_path, "thug.conf") if not os.path.isfile(conf_file): # pragma: no cover self.enabled = False return config = configparser.ConfigParser() config.read(conf_file) self.opts["enable"] = config.getboolean("honeyagent", "enable") if not self.opts["enable"]: self.enabled = False return self.opts["scanurl"] = config.get("honeyagent", "scanurl") # pragma: no cover def save_report(self, response, basedir, sample): log_dir = os.path.join(basedir, "analysis", "honeyagent") log.ThugLogging.log_honeyagent(log_dir, sample, response.text) def save_dropped(self, response, basedir, sample): data = response.json() result = data.get("result", None) if result is None: # pragma: no cover return None files = result.get("files", None) if files is None: # pragma: no cover return result md5 = sample["md5"] log_dir = os.path.join(basedir, "analysis", "honeyagent", "dropped") for filename in files.keys(): log.warning( "[HoneyAgent][%s] Dropped sample %s", md5, os.path.basename(filename) ) data = base64.b64decode(files[filename]) log.ThugLogging.store_content(log_dir, os.path.basename(filename), data) log.ThugLogging.log_file(data) return result def dump_yara_analysis(self, result, sample): yara = result.get("yara", None) if yara is None: # pragma: no cover return md5 = sample["md5"] for key in yara.keys(): for v in yara[key]: log.warning( "[HoneyAgent][%s] Yara %s rule %s match", md5, key, v["rule"] ) def submit(self, data, sample, params): md5 = sample["md5"] sample = os.path.join(tempfile.gettempdir(), md5) with open(sample, "wb") as fd: fd.write(data) files = {"file": (md5, open(sample, "rb"))} # pylint: disable=consider-using-with response = requests.post( self.opts["scanurl"], files=files, params=params, timeout=10 ) if response.ok: log.warning("[HoneyAgent][%s] Sample submitted", md5) os.remove(sample) return response def analyze(self, data, sample, basedir, params): if not self.enabled: return if not log.ThugOpts.honeyagent: # pragma: no cover return if params is None: params = {} response = self.submit(data, sample, params) self.save_report(response, basedir, sample) result = self.save_dropped(response, basedir, sample) if result: self.dump_yara_analysis(result, sample)
3,980
Python
.py
97
31.587629
91
0.608627
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,744
Favicon.py
buffer_thug/thug/Analysis/favicon/Favicon.py
import io import dhash from PIL import Image class Favicon: @staticmethod def eval_dhash(favicon): try: icon = io.BytesIO(favicon) image = Image.open(icon) row, col = dhash.dhash_row_col(image) return dhash.format_hex(row, col) except Exception: # pragma: no cover,pylint:disable=broad-except return None
394
Python
.py
13
22.538462
73
0.625995
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,745
AWIS.py
buffer_thug/thug/Analysis/awis/AWIS.py
#!/usr/bin/env python import os import logging import configparser from urllib.parse import urlparse MYAWIS_MODULE = True try: import myawis except ImportError: MYAWIS_MODULE = False log = logging.getLogger("Thug") class AWIS: def __init__(self): self.enabled = MYAWIS_MODULE self.__init_awis() def __init_awis(self): self._awis_api = None if not self.enabled: return conf_file = os.path.join(log.configuration_path, "thug.conf") if not os.path.exists(conf_file): self.enabled = False return config = configparser.ConfigParser() config.read(conf_file) enable = config.getboolean("awis", "enable") if not enable: self.enabled = False return self.apikey = config.get("awis", "apikey") self.secretkey = config.get("awis", "secretkey") @property def awis_api(self): if not self.enabled: log.warning("[AWIS] Analysis subsystem disabled") return None if not self._awis_api: self._awis_api = myawis.CallAwis(self.apikey, self.secretkey) return self._awis_api def query(self, url): result = {} if not log.ThugOpts.awis: return result if not url: return result if not self.awis_api: return result p_url = urlparse(url) hostname = p_url.hostname if not hostname: return result result["url"] = url result["hostname"] = hostname urlinfo = self.awis_api.urlinfo(hostname) for trafficdata in urlinfo.findAll("TrafficData"): rank = trafficdata.find("Rank") result["SiteRank"] = rank.text if rank else str() log.warning("[AWIS][Host: %s] SiteRank: %s", hostname, result["SiteRank"]) for contentdata in urlinfo.findAll("ContentData"): links = contentdata.find("LinksInCount") result["LinksInCount"] = links.text if links else str() log.warning( "[AWIS][Host: %s] LinksInCount: %s", hostname, result["LinksInCount"] ) for sitedata in contentdata.findAll("SiteData"): title = sitedata.find("Title") result["SiteTitle"] = title.text if title else str() log.warning( "[AWIS][Host: %s] SiteTitle: %s", hostname, result["SiteTitle"] ) description = sitedata.find("Description") result["SiteDescription"] = description.text if description else str() log.warning( "[AWIS][Host: %s] SiteDescription: %s", hostname, result["SiteDescription"], ) onlinesince = sitedata.find("OnlineSince") result["OnlineSince"] = onlinesince.text if onlinesince else str() log.warning( "[AWIS][Host: %s] OnlineSince: %s", hostname, result["OnlineSince"] ) for adultcontent in contentdata.findAll("AdultContent"): result["AdultContent"] = adultcontent.text if adultcontent else str() log.warning( "[AWIS][Host: %s] AdultContent: %s", hostname, result["AdultContent"], ) return result
3,488
Python
.py
90
27.2
87
0.559382
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,746
Shellcode.py
buffer_thug/thug/Analysis/shellcode/Shellcode.py
#!/usr/bin/env python # # Shellcode.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging try: import pylibemu PYLIBEMU_MODULE = True except ImportError: # pragma: no cover PYLIBEMU_MODULE = False try: # pragma: no cover import speakeasy SPEAKEASY_MODULE = True except ImportError: # pragma: no cover SPEAKEASY_MODULE = False log = logging.getLogger("Thug") class Shellcode: modules = ( "pylibemu", "speakeasy", ) def __init__(self): self.enabled = any( [ PYLIBEMU_MODULE, SPEAKEASY_MODULE, ] ) self.snippet = None @property def window(self): return log.DFT.window def retrieve_URLDownloadToFile(self, url): if url in log.ThugLogging.shellcode_urls: # pragma: no cover return try: if ( self.window._navigator.fetch( url, redirect_type="URLDownloadToFile", snippet=self.snippet ) is None ): log.ThugLogging.add_behavior_warn( "[URLDownloadToFile] Fetch failed", snippet=self.snippet ) log.ThugLogging.shellcode_urls.add(url) except Exception: # pylint:disable=broad-except log.ThugLogging.add_behavior_warn( "[URLDownloadToFile] Fetch failed", snippet=self.snippet ) def check_URLDownloadToFile(self, emu): profile = emu.emu_profile_output.decode() while True: offset = profile.find("URLDownloadToFile") if offset < 0: break profile = profile[offset:] p = profile.split(";") if len(p) < 2: # pragma: no cover profile = profile[1:] continue p = p[1].split('"') if len(p) < 3: profile = profile[1:] continue url = p[1] self.retrieve_URLDownloadToFile(url) profile = profile[1:] def retrieve_WinExec(self, url): if url in log.ThugLogging.shellcode_urls: return log.ThugLogging.shellcode_urls.add(url) try: url = url[2:].replace("\\", "/") self.window._navigator.fetch( url, redirect_type="WinExec", snippet=self.snippet ) except Exception: # pylint:disable=broad-except log.ThugLogging.add_behavior_warn( "[WinExec] Fetch failed", snippet=self.snippet ) def check_WinExec(self, emu): profile = emu.emu_profile_output.decode() while True: offset = profile.find("WinExec") if offset < 0: break profile = profile[offset:] p = profile.split(";") if not p: # pragma: no cover profile = profile[1:] continue s = p[0].split('"') if len(s) < 2: # pragma: no cover profile = profile[1:] continue url = s[1] if not url.startswith("\\\\"): profile = profile[1:] continue self.retrieve_WinExec(url) profile = profile[1:] def build_shellcode(self, s): i = 0 sc = [] while i < len(s): if s[i] == '"': # pragma: no cover i += 1 continue if s[i] in ("%",) and (i + 1) < len(s) and s[i + 1] == "u": if (i + 6) <= len(s): currchar = int(s[i + 2 : i + 4], 16) nextchar = int(s[i + 4 : i + 6], 16) sc.append(nextchar) sc.append(currchar) i += 6 elif (i + 3) <= len(s): # pragma: no cover currchar = int(s[i + 2 : i + 4], 16) sc.append(currchar) i += 3 else: sc.append(ord(s[i])) i += 1 return bytes(sc) @staticmethod def build_snippet(shellcode): return log.ThugLogging.add_shellcode_snippet( shellcode, "Assembly", "Shellcode", method="Static Analysis" ) def log_shellcode_profile(self, module, profile): description = f"[{module}][Shellcode Profile] {profile}" log.ThugLogging.add_behavior_warn( description=description, snippet=self.snippet, method="Static Analysis" ) def check_shellcode_pylibemu(self, shellcode, sc): if not PYLIBEMU_MODULE: return # pragma: no cover emu = pylibemu.Emulator(enable_hooks=False) emu.run(sc) if emu.emu_profile_output: # pylint:disable=using-constant-test profile = emu.emu_profile_output.decode() # pylint:disable=no-member if self.snippet is None: self.snippet = self.build_snippet(shellcode) self.log_shellcode_profile("LIBEMU", profile) self.check_URLDownloadToFile(emu) self.check_WinExec(emu) emu.free() def hook_URLDownloadToFile( self, emu, api_name, func, params ): # pragma: no cover,pylint:disable=unused-argument rv = func(params) pCaller, szURL, szFileName, dwReserved, lpfnCB = params # pylint:disable=unused-variable self.retrieve_URLDownloadToFile(szURL) return rv def hook_WinExec( self, emu, api_name, func, params ): # pragma: no cover,pylint:disable=unused-argument rv = func(params) lpCmdLine, uCmdShow = params # pylint:disable=unused-variable uncs = [ p.strip('"').strip("'") for p in lpCmdLine.split() if p.startswith("\\\\") ] for unc in uncs: self.retrieve_WinExec(unc) # pragma: no cover return rv def check_shellcode_speakeasy(self, shellcode, sc): # pragma: no cover if not SPEAKEASY_MODULE: return # pragma: no cover se = speakeasy.Speakeasy() se.add_api_hook(self.hook_URLDownloadToFile, "urlmon", "URLDownloadToFile*") se.add_api_hook(self.hook_WinExec, "kernel32", "WinExec") address = se.load_shellcode(None, speakeasy.arch.ARCH_X86, data=sc) se.run_shellcode(address) if self.snippet is None: self.snippet = self.build_snippet(shellcode) self.log_shellcode_profile("SPEAKEASY", se.get_report()) def do_check_shellcode(self, shellcode, sc): self.snippet = None for module in self.modules: m = getattr(self, f"check_shellcode_{module}", None) if m: m(shellcode, sc) # pylint:disable=not-callable def check_shellcode(self, shellcode): if not self.enabled: return # pragma: no cover if not shellcode: return try: sc = self.build_shellcode(shellcode) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("Shellcode building error (%s)", str(e)) return self.do_check_shellcode(shellcode, sc) def check_shellcodes(self): while True: try: shellcode = log.ThugLogging.shellcodes.pop() self.check_shellcode(shellcode) except KeyError: break
8,118
Python
.py
213
27.323944
97
0.563903
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,747
Magic.py
buffer_thug/thug/Magic/Magic.py
#!/usr/bin/env python # # Magic.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import magic class Magic: @staticmethod def get_mime(data): try: # This works with python-magic >= 0.4.6 from pypi mtype = magic.from_buffer(data, mime=True) except Exception: # pragma: no cover,pylint:disable=broad-except try: # Ubuntu workaround # This works with python-magic >= 5.22 from Ubuntu (apt) ms = magic.open(magic.MAGIC_MIME) # pylint:disable=no-member ms.load() mtype = ms.buffer(data).split(";")[0] except Exception: # pylint:disable=broad-except # Filemagic workaround # This works with filemagic >= 1.6 from pypi with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m: # pylint:disable=unexpected-keyword-arg,not-context-manager mtype = m.id_buffer(data) return mtype
1,592
Python
.py
37
35.756757
128
0.660864
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,748
Window.py
buffer_thug/thug/DOM/Window.py
#!/usr/bin/env python # # Window.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import sched import time import logging import traceback import numbers import collections.abc import datetime import random import types from urllib.parse import unquote import bs4 from thug.ActiveX.ActiveX import _ActiveXObject from thug.Java.java import java from thug.DOM.W3C import w3c from thug.DOM.W3C import File from thug.DOM.W3C import URL from .JSClass import JSClass from .JSClass import JSClassConstructor from .JSClass import JSClassPrototype from .JSInspector import JSInspector from .Navigator import Navigator from .Location import Location from .Screen import Screen from .History import History from .CCInterpreter import CCInterpreter from .LocalStorage import LocalStorage from .SessionStorage import SessionStorage from .w3c_bindings import w3c_bindings sched = sched.scheduler(time.time, time.sleep) log = logging.getLogger("Thug") class Window(JSClass): __symbols__ = set() class Timer: max_loops = 3 max_timers = 16 def __init__(self, window, code, delay, repeat, lang="JavaScript"): self.window = window self.code = code self.delay = float(delay) / 1000 self.repeat = repeat self.lang = lang self.running = True self.loops = self.__init_loops() def __init_loops(self): max_loops = self.max_loops - 1 if not self.delay: return max_loops loops = int(0.1 * log.ThugOpts.timeout / self.delay) return min(loops, max_loops) def start(self): self.event = sched.enter(self.delay, 1, self.execute, ()) try: sched.run() except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[Timer] Scheduler error: %s", str(e)) def stop(self): self.running = False if self.event in sched.queue: sched.cancel(self.event) # pragma: no cover def execute(self): if len(self.window.timers) > self.max_timers: self.running = False if not self.running: return with self.window.context as ctx: try: if log.JSEngine.isJSFunction(self.code): self.code() else: ctx.eval(self.code) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("Error while handling timer callback (%s)", str(e)) if log.ThugOpts.Personality.isIE(): raise TypeError() from e return if self.repeat and self.loops > 0: self.loops -= 1 self.event = sched.enter(self.delay, 1, self.execute, ()) def __init__( self, url, dom_or_doc, navigator=None, personality="winxpie60", name="", target="_blank", parent=None, opener=None, replace=False, screen=None, width=800, height=600, left=0, top=None, **kwds, ): self._top = top if top else self self.url = url self.doc = ( w3c.getDOMImplementation(dom_or_doc, **kwds) if isinstance(dom_or_doc, bs4.BeautifulSoup) else dom_or_doc ) self.doc.window = self self.doc.contentWindow = self for p in w3c_bindings: # pylint: disable=consider-using-dict-items setattr(self, p, w3c_bindings[p]) self._navigator = navigator if navigator else Navigator(personality, self) self._location = Location(self) self._history = parent.history if parent and parent.history else History(self) if url not in ("about:blank",): self._history.update(url, replace) self.doc.location = property(self.getLocation, self.setLocation) self._target = target self._parent = parent if parent else self self._opener = opener self._screen = screen or Screen(width, height, 32) self._closed = False self._personality = personality self.__init_window_personality() self.name = name self._left = left self._screen_top = random.randint(0, 30) self.innerWidth = width self.innerHeight = height self.outerWidth = width self.outerHeight = height self.timers = [] self.java = java() log.MIMEHandler.window = self def __getattr__(self, key): if key in ("__members__", "__methods__", "__symbols__"): raise AttributeError(key) if key in self.__symbols__: raise AttributeError(key) if key == "constructor": return JSClassConstructor(self.__class__) if key == "prototype": return JSClassPrototype(self.__class__) prop = self.__dict__.setdefault("__properties__", {}).get(key, None) if prop and isinstance(prop[0], collections.abc.Callable): return prop[0]() if log.ThugOpts.Personality.isIE(): if key.lower() in ( "wscript", "wsh", ): return self.WScript if key in self.WScript.__dict__ and callable(self.WScript.__dict__[key]): return self.WScript.__dict__[key] xmlhttp = getattr(log, "XMLHTTP", None) if xmlhttp and isinstance(xmlhttp, dict): value = xmlhttp.get(key, None) if value is not None: return value context = self.__class__.__dict__["context"].__get__(self, Window) try: self.__symbols__.add(key) symbol = context.eval(key) except Exception as e: raise AttributeError(key) from e finally: self.__symbols__.discard(key) if log.JSEngine.isJSFunction(symbol): # pragma: no cover _method = None if _method is None: _method = types.MethodType(symbol, Window) setattr(self, key, _method) context.locals[key] = _method return _method _types = (str, bool, numbers.Number, datetime.datetime) if isinstance(symbol, _types) or log.JSEngine.isJSObject(symbol): setattr(self, key, symbol) context.locals[key] = symbol return symbol raise AttributeError(key) # pragma: no cover @property def closed(self): return self._closed def close(self): self._closed = True @property def this(self): return self @property def window(self): return self @property def self(self): return self def get_top(self): return self._top def set_top(self, top): # pragma: no cover self._top = top top = property(get_top, set_top) @property def _document(self): return self.doc def _findAll(self, tags): return self.doc.doc.find_all(tags, recursive=True) @property def frames(self): """an array of all the frames (including iframes) in the current window""" from thug.DOM.W3C.HTML.HTMLCollection import HTMLCollection frames = set() for frame in self._findAll(["frame", "iframe"]): if not getattr(frame, "_node", None): log.DOMImplementation.createHTMLElement(self.window.doc, frame) frames.add(frame._node) return HTMLCollection(self.doc, list(frames)) @property def length(self): """the number of frames (including iframes) in a window""" return len(self._findAll(["frame", "iframe"])) @property def history(self): """the History object for the window""" return self._history def getLocation(self): """the Location object for the window""" return self._location def setLocation(self, location): self._location.href = location location = property(getLocation, setLocation) @property def navigator(self): """the Navigator object for the window""" return self._navigator @property def opener(self): """a reference to the window that created the window""" return self._opener @property def pageXOffset(self): return 0 @property def pageYOffset(self): return 0 @property def parent(self): return self._parent @property def screen(self): return self._screen @property def screenLeft(self): return self._left @property def screenTop(self): return self._screen_top @property def screenX(self): return self._left @property def screenY(self): return self._screen_top def _do_ActiveXObject(self, cls, typename="name"): if cls.lower() in ("htmlfile",): setattr(self.doc, "Script", self) return self.doc return _ActiveXObject(self, cls, typename) def alert(self, text): """ Display an alert dialog with the specified text. Syntax window.alert(text) Parameters text is a string of the text you want displayed in the alert dialog. """ log.TextClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else log.last_url, str(text) ) if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_alert_count() log.warning("[Window] Alert Text: %s", str(text)) def back(self): """ Returns the window to the previous item in the history. Syntax window.back() Parameters None. """ log.warning("[Window] back()") def blur(self): """ Shifts focus away from the window. Syntax window.blur() Parameters None. """ log.warning("[Window] blur()") def captureEvents(self, eventType): """ Registers the window to capture all events of the specified type. Syntax window.captureEvents(Event.eventType) Parameters eventType is a string """ self.alert(f"[Captured Event] {eventType}") def clearInterval(self, intervalID): """ Clears a delay that's been set for a specific function. Syntax window.clearInterval(intervalID) Parameters intervalID is the ID of the specific interval you want to clear. """ if intervalID is not None and intervalID < len(self.timers): self.timers[intervalID].stop() def clearTimeout(self, timeoutID): """ Clears the delay set by window.setTimeout(). Syntax window.clearTimeout(timeoutID) Parameters timeoutID is the ID of the timeout you wish you clear. """ if timeoutID is not None and timeoutID < len(self.timers): self.timers[timeoutID].stop() def confirm(self, text): """ Displays a dialog with a message that the user needs to respond to. Syntax result = window.confirm(text) Parameters text is a string. result is a boolean value indicating whether OK or Cancel was selected. """ log.TextClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else log.last_url, str(text) ) return True def dump(self, text): """ Prints messages to the console. Syntax window.dump(text) Parameters text is a string. """ log.TextClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else log.last_url, str(text) ) self.alert(text) def focus(self): """ Sets focus on the window. Syntax window.focus() Parameters None. """ log.warning("[Window] focus()") def forward(self): """ Moves the window one document forward in the history. Syntax window.forward() Parameters None. """ self._history.forward() def GetAttention(self): """ Flashes the application icon to get the user's attention. Syntax window.GetAttention() Parameters None. """ log.warning("[Window] GetAttention()") def getSelection(self): # pylint:disable=useless-return """ Returns the selection (generally text). Syntax selection = window.getSelection() Parameters selection is a selection object. """ log.warning("[Window] getSelection()") return None def home(self): """ Returns the window to the home page. Syntax window.home() Parameters None. """ self.open() def moveBy(self, deltaX, deltaY): """ Moves the current window by a specified amount. Syntax window.moveBy(deltaX, deltaY) Parameters deltaX is the amount of pixels to move the window horizontally. deltaY is the amount of pixels to move the window vertically. """ log.warning("[Window] moveBy(%s, %s)", deltaX, deltaY) def moveTo(self, x, y): """ Moves the window to the specified coordinates. Syntax window.moveTo(x, y) Parameters x is the horizontal coordinate to be moved to. y is the vertical coordinate to be moved to. """ log.warning("[Window] moveTo(%s, %s)", x, y) def prompt(self, text, defaultText=None): """ Returns the text entered by the user in a prompt dialog. """ log.TextClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else log.last_url, str(text) ) return defaultText if defaultText else "" def releaseEvents(self, eventType): """ Releases the window from trapping events of a specific type. Syntax window.releaseEvents(Event.eventType) Parameters eventType is a string """ self.alert(f"[Released Event] {eventType}") def resizeBy(self, xDelta, yDelta): """ Resizes the current window by a certain amount. Syntax window.resizeBy(xDelta, yDelta) Parameters xDelta is the number of pixels to grow the window horizontally. yDelta is the number of pixels to grow the window vertically. """ log.warning("[Window] resizeBy(%s, %s)", xDelta, yDelta) def resizeTo(self, iWidth, iHeight): """ Dynamically resizes window. Syntax window.resizeTo(iWidth, iHeight) Parameters iWidth is an integer representing the new width in pixels. iHeight is an integer value representing the new height in pixels. """ log.warning("[Window] resizeTo(%s, %s)", iWidth, iHeight) def scroll(self, x, y): """ Scrolls the window to a particular place in the document. Syntax window.scroll(x-coord, y-coord) Parameters x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. """ log.warning("[Window] scroll(%s, %s)", x, y) def scrollBy(self, xDelta, yDelta): """ Scrolls the document in the window by the given amount. Syntax window.scrollBy(xDelta, yDelta) Parameters xDelta is the amount of pixels to scroll horizontally. yDelta is the amount of pixels to scroll vertically. """ log.warning("[Window] scrollBy(%s, %s)", xDelta, yDelta) def scrollByLines(self, lines): """ Scrolls the document by the given number of lines. Syntax window.scrollByLines(lines) Parameters lines is the number of lines. """ log.warning("[Window] scrollByLines(%s)", lines) def scrollByPages(self, pages): """ Scrolls the current document by the specified number of pages. Syntax window.scrollByPages(pages) Parameters pages is the number of pages to scroll. """ log.warning("[Window] scrollByPages(%s)", pages) def scrollTo(self, x, y): """ Scrolls to a particular set of coordinates in the document. Syntax window.scrollTo(x-coord, y-coord) Parameters x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. """ log.warning("[Window] scrollTo(%s, %s)", x, y) def setInterval(self, f, delay, lang="JavaScript"): """ Set a delay for a specific function. Syntax ID = window.setInterval("funcName", delay) Parameters funcName is the name of the function for which you want to set a delay. delay is the number of milliseconds (thousandths of a second) that the function should be delayed. ID is the interval ID. """ if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_setinterval_count() if log.ThugOpts.Personality.isIE() and not f: raise TypeError() if log.ThugOpts.delay: delay = min(delay, log.ThugOpts.delay) timer = Window.Timer(self, f, delay, True, lang) self.timers.append(timer) timer.start() return len(self.timers) - 1 def setTimeout(self, f, delay=0, lang="JavaScript"): """ Sets a delay for executing a function. Syntax ID = window.setTimeout("funcName", delay) Parameters funcName is the name of the function for which you want to set a delay. delay is the number of milliseconds (thousandths of a second) that the function should be delayed. ID is the interval ID. """ if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_settimeout_count() if log.ThugOpts.Personality.isIE() and not f: raise TypeError() if log.ThugOpts.delay: delay = min(delay, log.ThugOpts.delay) timer = Window.Timer(self, f, delay, False, lang) self.timers.append(timer) timer.start() return len(self.timers) - 1 def stop(self): """ This method stops window loading. Syntax window.stop() Parameters None. """ log.warning("[Window] stop()") def _attachEvent(self, sEvent, fpNotify, useCapture=False): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_attachevent_count() setattr(self, sEvent.lower(), fpNotify) def _detachEvent(self, sEvent, fpNotify): if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_detachevent_count() notify = getattr(self, sEvent.lower(), None) if notify is None: return if notify in (fpNotify,): delattr(self, sEvent.lower()) def _addEventListener(self, _type, listener, useCapture=False): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_addeventlistener_count() setattr(self, f"on{_type.lower()}", listener) def _removeEventListener(self, _type, listener, useCapture=False): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_removeeventlistener_count() _listener = getattr(self, f"on{_type.lower()}", None) if _listener is None: return # pragma: no cover if _listener in (listener,): delattr(self, f"on{_type.lower()}") def _CollectGarbage(self): pass def _navigate(self, location): self.location = location return 0 def _execScript(self, code, language="JScript"): # pylint:disable=useless-return if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet(code, language, "Contained_Inside") if language.lower().startswith(("jscript", "javascript")): self.eval(code) if language.lower().startswith("vbs"): log.DFT.handle_vbscript_text(code) return None def __init_window_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_window_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_window_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_window_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_window_personality_Safari() return def __init_window_personality_IE(self): from .ClipboardData import ClipboardData from .Console import Console from .External import External from thug.DOM.W3C.DOMParser import DOMParser log.ThugOpts.activex_ready = False if not (log.ThugOpts.local and log.ThugOpts.attachment): self.XMLHttpRequest = self._XMLHttpRequest self.document = self._document self.ActiveXObject = self._do_ActiveXObject self.DeferredListDataComplete = self._DeferredListDataComplete self.CollectGarbage = self._CollectGarbage self.WScript = _ActiveXObject(self, "WScript.Shell") self.navigate = self._navigate self.clientInformation = self.navigator self.clipboardData = ClipboardData() self.external = External() self.console = Console() self.ScriptEngineMajorVersion = ( log.ThugOpts.Personality.ScriptEngineMajorVersion ) self.ScriptEngineMinorVersion = ( log.ThugOpts.Personality.ScriptEngineMinorVersion ) self.ScriptEngineBuildVersion = ( log.ThugOpts.Personality.ScriptEngineBuildVersion ) if log.ThugOpts.Personality.browserMajorVersion < 11: self.execScript = self._execScript self.attachEvent = self._attachEvent self.detachEvent = self._detachEvent if log.ThugOpts.Personality.browserMajorVersion >= 8: self.DOMParser = DOMParser self.addEventListener = self._addEventListener self.removeEventListener = self._removeEventListener self.localStorage = LocalStorage() self.sessionStorage = SessionStorage() self.doc.parentWindow = self._parent log.ThugOpts.activex_ready = True def __init_window_personality_Firefox(self): from .Components import Components from .Console import Console from .Crypto import Crypto from .Map import Map from .MozConnection import mozConnection from .Sidebar import Sidebar from thug.DOM.W3C.DOMParser import DOMParser self.document = self._document self.DOMParser = DOMParser self.XMLHttpRequest = self._XMLHttpRequest self.addEventListener = self._addEventListener self.removeEventListener = self._removeEventListener self.crypto = Crypto() self.sidebar = Sidebar() self.Components = Components() self.console = Console() self.localStorage = LocalStorage() self.sessionStorage = SessionStorage() self.Blob = File.Blob self.File = File.File if log.ThugOpts.Personality.browserMajorVersion > 11: self.navigator.mozConnection = mozConnection() if log.ThugOpts.Personality.browserMajorVersion > 12: self.Map = Map() if log.ThugOpts.Personality.browserMajorVersion > 18: self.URL = URL.URL with self.context as ctxt: ctxt.eval( """ var objurl = new URL(window.url); window.URL.createObjectURL = objurl.createObjectURL; window.URL.revokeObjectURL = objurl.revokeObjectURL; """ ) if log.ThugOpts.Personality.browserMajorVersion > 28: self.URLSearchParams = URL.URLSearchParams if log.ThugOpts.Personality.browserMajorVersion > 32: self.RadioNodeList = None if log.ThugOpts.Personality.browserMajorVersion > 12: self.Map = Map() with self.context as ctxt: if log.ThugOpts.Personality.browserMajorVersion <= 20: ctxt.eval("delete Math.imul;") if log.ThugOpts.Personality.browserMajorVersion <= 4: ctxt.eval("delete Array.isArray;") def __init_window_personality_Chrome(self): from .Chrome import Chrome from .Console import Console from .External import External from thug.DOM.W3C.DOMParser import DOMParser self.document = self._document self.DOMParser = DOMParser self.XMLHttpRequest = self._XMLHttpRequest self.addEventListener = self._addEventListener self.removeEventListener = self._removeEventListener self.clientInformation = self.navigator self.external = External() self.chrome = Chrome() self.console = Console() self.localStorage = LocalStorage() self.sessionStorage = SessionStorage() self.onmousewheel = None self.Blob = File.Blob self.File = File.File if log.ThugOpts.Personality.browserMajorVersion > 18: self.URL = URL.URL with self.context as ctxt: ctxt.eval( """ var objurl = new URL(window.url); window.URL.createObjectURL = objurl.createObjectURL; window.URL.revokeObjectURL = objurl.revokeObjectURL; """ ) if log.ThugOpts.Personality.browserMajorVersion > 48: self.URLSearchParams = URL.URLSearchParams def __init_window_personality_Safari(self): from .Console import Console from thug.DOM.W3C.DOMParser import DOMParser self.document = self._document self.DOMParser = DOMParser self.XMLHttpRequest = self._XMLHttpRequest self.addEventListener = self._addEventListener self.removeEventListener = self._removeEventListener self.clientInformation = self.navigator self.console = Console() self.localStorage = LocalStorage() self.sessionStorage = SessionStorage() self.onmousewheel = None self.Blob = File.Blob self.File = File.File if log.ThugOpts.Personality.browserMajorVersion > 9: self.URLSearchParams = URL.URLSearchParams if log.ThugOpts.Personality.browserMajorVersion > 13: self.URL = URL.URL with self.context as ctxt: ctxt.eval( """ var objurl = new URL(window.url); window.URL.createObjectURL = objurl.createObjectURL; window.URL.revokeObjectURL = objurl.revokeObjectURL; """ ) def eval(self, script): if not script: return None # pragma: no cover log.ThugLogging.add_code_snippet( script, language="Javascript", relationship="eval argument", check=True ) return self.evalScript(script) @property def context(self): # if not hasattr(self, '_context'): if "_context" not in self.__dict__: log.JSEngine.init_context(self) self._context = log.JSEngine.context return self._context def evalScript(self, script, tag=None): if log.ThugOpts.verbose or log.ThugOpts.debug: log.info(script) result = 0 try: log.JSClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else log.last_url, script ) if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet( script, "Javascript", "Contained_Inside" ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[Window] JSClassifier error: %s", str(e)) if tag: self.doc.current = tag else: try: body = self.doc.body except Exception: # pragma: no cover,pylint:disable=broad-except # This code is for when you are desperate :) body = self.doc.getElementsByTagName("body")[0] if body and body.tag.contents: self.doc.current = body.tag.contents[-1] else: # pragma: no cover self.doc.current = self.doc.doc.contents[-1] with self.context as ctxt: if log.ThugOpts.Personality.isIE(): cc = CCInterpreter() script = cc.run(script) inspector = JSInspector(self, ctxt, script) result = inspector.run() log.ThugLogging.ContextAnalyzer.analyze(self) return result def unescape(self, s): i = 0 sc = str() if len(s) > 16: log.ThugLogging.shellcodes.add(s) # %xx format if "%" in s and "%u" not in s: return unquote(s) # %uxxxx format while i < len(s): if s[i] == '"': # pragma: no cover i += 1 continue if s[i] in ("%",) and (i + 1) < len(s) and s[i + 1] == "u": if (i + 6) <= len(s): currchar = int(s[i + 2 : i + 4], 16) nextchar = int(s[i + 4 : i + 6], 16) sc += chr(nextchar) sc += chr(currchar) i += 6 elif (i + 3) <= len(s): currchar = int(s[i + 2 : i + 4], 16) sc += chr(currchar) i += 3 else: sc += s[i] i += 1 return sc def decodeURIComponent(self, s): return unquote(s) if s else "" def Image(self, width=800, height=600): # pylint:disable=unused-argument return self.doc.createElement("img") def _XMLHttpRequest(self): return _ActiveXObject(self, "microsoft.xmlhttp") def _DeferredListDataComplete(self): # pragma: no cover for name in self.context.locals.keys(): local = getattr(self.context.locals, name, None) if not local: continue rootFolder = getattr(local, "rootFolder", None) if not rootFolder: continue try: self._navigator.fetch(rootFolder, redirect_type="Sharepoint") except Exception: # pylint:disable=broad-except log.warning(traceback.format_exc()) def getComputedStyle(self, element, pseudoelt=None): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_getcomputedstyle_count() return getattr(element, "style", None) def open(self, url=None, name="_blank", specs="", replace=False): if url and not isinstance(url, str): url = str(url) # pragma: no cover if url and url not in ("about:blank",): if self.url not in ("about:blank",): log.last_url = url # pragma: no cover try: response = self._navigator.fetch(url, redirect_type="window open") except Exception: # pylint:disable=broad-except return None if response is None or not response.ok: return None # pragma: no cover html = response.content if response.history: url = response.url try: log.HTMLClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else url, html ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[Window] HTMLClassifier error: %s", str(e)) content_type = response.headers.get( "content-type", log.Magic.get_mime(response.content) ) if content_type: handler = log.MIMEHandler.get_handler(content_type) # No need to invoke the MIME handler here because Navigator # fetch method has already taken care of it. Here we have # just to check if a MIME handler exists and stop further # processing if it does. if handler: return None # Log response here kwds = {"referer": self.url} if "set-cookie" in response.headers: kwds["cookie"] = response.headers["set-cookie"] if "last-modified" in response.headers: kwds["lastModified"] = response.headers["last-modified"] else: url = "about:blank" html = "" kwds = {} dom = log.HTMLInspector.run(html, "html5lib") for spec in specs.split(","): spec = [s.strip() for s in spec.split("=")] if len(spec) == 2: if spec[0] in ["width", "height", "left", "top"]: kwds[spec[0]] = int(spec[1]) if name in ["_blank", "_parent", "_self", "_top"]: kwds["target"] = name name = "" else: kwds["target"] = "_blank" return Window( url, dom, navigator=None, personality=self._personality, name=name, parent=self, opener=self, replace=replace, **kwds, )
35,482
Python
.py
927
28.044229
104
0.596013
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,749
ClipboardData.py
buffer_thug/thug/DOM/ClipboardData.py
#!/usr/bin/env python # # ClipboardData.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class ClipboardData(JSClass): def __init__(self): self._data = {} def getData(self, dataFormat): if dataFormat in self._data: return self._data[dataFormat] return None def setData(self, dataFormat, data): if dataFormat not in ("Text", "URL"): return False self._data[dataFormat] = data return True def clearData(self, dataFormat=None): if dataFormat is None: self._data.clear() return if dataFormat in self._data: del self._data[dataFormat]
1,302
Python
.py
36
31.027778
70
0.695306
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,750
HTMLInspector.py
buffer_thug/thug/DOM/HTMLInspector.py
#!/usr/bin/env python # # HTMLInspector.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import logging import json import bs4 log = logging.getLogger("Thug") class HTMLInspector: def __init__(self): self.enabled = True conf_file = os.path.join(log.configuration_path, "inspector.json") if not os.path.exists(conf_file): # pragma: no cover self.enabled = False return with open(conf_file, encoding="utf-8", mode="r") as fd: self.rules = json.load(fd) @staticmethod def check_ignore_handler(html): ignore_handlers = ( log.MIMEHandler.passthrough, log.MIMEHandler.handle_zip, log.MIMEHandler.handle_rar, log.MIMEHandler.handle_java_jnlp, log.MIMEHandler.handle_json, log.MIMEHandler.handle_image, ) mtype = log.Magic.get_mime(html) handler = log.MIMEHandler.get_handler(mtype) return handler in ignore_handlers def run(self, html, parser="html.parser"): if self.check_ignore_handler(html): return bs4.BeautifulSoup() if self.enabled and html: self.inspect(html, parser) return bs4.BeautifulSoup(html, parser) @property def inspect_url(self): return log.ThugLogging.url if log.ThugOpts.local else log.last_url def inspect(self, html, parser): soup = bs4.BeautifulSoup(html, parser) modified = False for action in self.rules: for s in self.rules[action]: for p in soup.select(s): m = getattr(p, action, None) if m: m() modified = True if modified: try: snippet = str(soup) except Exception: # pragma: no cover,pylint:disable=broad-except return log.ThugLogging.add_behavior_warn( description="[HTMLInspector] Detected potential code obfuscation", snippet=snippet, method="HTMLInspector deobfuscation", ) log.HTMLClassifier.classify(self.inspect_url, snippet)
2,831
Python
.py
74
29.554054
82
0.634538
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,751
DFT.py
buffer_thug/thug/DOM/DFT.py
#!/usr/bin/env python # # DFT.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import types import operator import re import base64 import logging from urllib.parse import unquote from urllib.parse import urljoin import bs4 from bs4.element import NavigableString from bs4.element import CData from bs4.element import Script from cssutils.parse import CSSParser from thug.ActiveX.ActiveX import _ActiveXObject from thug.DOM.W3C import w3c from thug.DOM.AsyncPrefetcher import AsyncPrefetcher log = logging.getLogger("Thug") class DFT: javascript = ("javascript",) vbscript = ("vbs", "vbscript", "visualbasic") # Some event types are directed at the browser as a whole, rather than at # any particular document element. In JavaScript, handlers for these events # are registered on the Window object. In HTML, we place them on the <body> # tag, but the browser registers them on the Window. The following is the # complete list of such event handlers as defined by the draft HTML5 # specification: # # onafterprint onfocus ononline onresize # onbeforeprint onhashchange onpagehide onstorage # onbeforeunload onload onpageshow onundo # onblur onmessage onpopstate onunload # onerror onoffline onredo window_events = ( "abort", "afterprint", "beforeprint", "beforeunload", "blur", "error", "focus", "hashchange", "load", "message", "offline", "online", "pagehide", "pageshow", "popstate", "redo", "resize", "storage", "undo", "unload", ) window_on_events = ["on" + e for e in window_events] window_storage_events = ("storage",) window_on_storage_events = ["on" + e for e in window_storage_events] _on_events = window_on_events + window_on_storage_events user_detection_events = ( "mousemove", "scroll", ) on_user_detection_events = ["on" + e for e in user_detection_events] async_prefetch_tags = ["script", "img"] def __init__(self, window, **kwds): self.window = window self.window.doc.DFT = self self.anchors = [] self.forms = kwds["forms"] if "forms" in kwds else [] self._context = None self.async_prefetcher = AsyncPrefetcher(window) log.DFT = self self._init_events() self._init_pyhooks() def _init_events(self): self.listeners = [] # Events are handled in the same order they are inserted in this list self.handled_events = ["load", "mousemove"] for event in log.ThugOpts.events: self.handled_events.append(event) self.handled_on_events = ["on" + e for e in self.handled_events] self.dispatched_events = set() def _init_pyhooks(self): hooks = log.PyHooks.get("DFT", None) if hooks is None: return get_method_function = operator.attrgetter("__func__") get_method_self = operator.attrgetter("__self__") for label, hook in hooks.items(): name = f"{label}_hook" _hook = get_method_function(hook) if get_method_self(hook) else hook method = types.MethodType(_hook, DFT) setattr(self, name, method) @property def context(self): if self._context is None: self._context = self.window.context return self._context def get_evtObject(self, elem, evtType): from thug.DOM.W3C.Events.Event import Event from thug.DOM.W3C.Events.MouseEvent import MouseEvent from thug.DOM.W3C.Events.HTMLEvent import HTMLEvent evtObject = None if evtType in MouseEvent.EventTypes: evtObject = MouseEvent() if evtType in HTMLEvent.EventTypes: evtObject = HTMLEvent() if evtObject is None: return None evtObject._target = elem evtObject.eventPhase = Event.AT_TARGET evtObject.currentTarget = elem return evtObject # Events handling def handle_element_event(self, evt): from thug.DOM.W3C.Events.Event import Event for elem, eventType, listener, capture in self.listeners: # pylint:disable=unused-variable if getattr(elem, "name", None) is None: # pragma: no cover continue if elem.name in ("body",): # pragma: no cover continue evtObject = Event() evtObject._type = eventType if eventType in (evt,): if (elem._node, evt) in self.dispatched_events: continue self.dispatched_events.add((elem._node, evt)) elem._node.dispatchEvent(evtObject) def handle_window_storage_event(self, onevt, evtObject): if onevt in self.handled_on_events: handler = getattr(self.window, onevt, None) if handler: handler(evtObject) def run_event_handler(self, handler, evtObject): if ( log.ThugOpts.Personality.isIE() and log.ThugOpts.Personality.browserMajorVersion < 9 ): self.window.event = evtObject handler() else: handler.apply(evtObject.currentTarget) def handle_window_event(self, onevt): if onevt not in self.handled_on_events: return # pragma: no cover if onevt not in self.window_on_events: return if onevt in self.window_on_storage_events: return handler = getattr(self.window, onevt, None) if handler: if (self.window, onevt[2:], handler) in self.dispatched_events: return self.dispatched_events.add((self.window, onevt[2:], handler)) evtObject = self.get_evtObject(self.window, onevt[2:]) self.run_event_handler(handler, evtObject) return with self.context as ctx: handler_type = ctx.eval(f"typeof window.{onevt}") if handler_type in ("function",): # pragma: no cover handler = ctx.eval(f"window.{onevt}") if (self.window, onevt[2:], handler) in self.dispatched_events: return handler.call() self.dispatched_events.add((self.window, onevt[2:], handler)) def handle_document_event(self, onevt): if onevt not in self.handled_on_events: return # pragma: no cover evtObject = self.get_evtObject(self.window.doc, onevt[2:]) handler = getattr(self.window.doc, onevt, None) if handler: self.run_event_handler(handler, evtObject) if "_listeners" not in self.window.doc.tag.__dict__: return # pragma: no cover for ( eventType, listener, capture, ) in ( self.window.doc.tag._listeners ): # pragma: no cover,pylint:disable=unused-variable if eventType not in (onevt[2:],): continue if (self.window.doc, onevt[2:], handler) in self.dispatched_events: return self.dispatched_events.add((self.window.doc, onevt[2:], handler)) evtObject = self.get_evtObject(self.window.doc, eventType) self.run_event_handler(listener, evtObject) def _build_event_handler(self, ctx, h): # When an event handler is registered by setting an HTML attribute # the browser converts the string of JavaScript code into a function. # Browsers other than IE construct a function with a single argument # named `event'. IE constructs a function that expects no argument. # If the identifier `event' is used in such a function, it refers to # `window.event'. In either case, HTML event handlers can refer to # the event object as `event'. if log.ThugOpts.Personality.isIE(): return ctx.eval( f"(function() {{ with(document) {{ with(this.form || {{}}) {{ with(this) {{ event = window.event; {h} }} }} }} }}) " ) return ctx.eval( f"(function(event) {{ with(document) {{ with(this.form || {{}}) {{ with(this) {{ {h} }} }} }} }}) " ) def build_event_handler(self, ctx, h): try: return self._build_event_handler(ctx, h) except SyntaxError as e: # pragma: no cover log.info("[SYNTAX ERROR][build_event_handler] %s", str(e)) return None def get_event_handler(self, h): handler = None if isinstance(h, str): handler = self.build_event_handler(self.context, h) elif log.JSEngine.isJSFunction(h): handler = h else: # pragma: no cover try: handler = getattr(self.context.locals, h, None) except Exception: # pylint:disable=broad-except handler = None return handler def set_event_handler_attributes(self, elem): try: attrs = elem.attrs except Exception: # pylint:disable=broad-except return if "language" in list(attrs.keys()) and attrs["language"].lower() not in ( "javascript", ): return for evt, h in attrs.items(): if evt not in self.handled_on_events: continue self.attach_event(elem, evt, h) def attach_event(self, elem, evt, h): handler = self.get_event_handler(h) if not handler: return # pragma: no cover if ( getattr(elem, "name", None) and elem.name in ("body",) and evt in self.window_on_events ): setattr(self.window, evt, handler) return if not getattr(elem, "_node", None): log.DOMImplementation.createHTMLElement(self.window.doc, elem) elem._node._attachEvent(evt, handler, True) def set_event_listeners(self, elem): p = getattr(elem, "_node", None) if p: for evt in self.handled_on_events: h = getattr(p, evt, None) if h: self.attach_event(elem, evt, h) listeners = getattr(elem, "_listeners", None) if listeners: for eventType, listener, capture in listeners: if eventType in self.handled_events: self.listeners.append((elem, eventType, listener, capture)) def _handle_onerror(self, tag): from thug.DOM.W3C.Events.Event import Event if "onerror" not in tag.attrs: return if log.ThugOpts.Personality.isIE(): evtObject = Event() evtObject._type = "onerror" self.window.event = evtObject try: handler = self.get_event_handler(tag.attrs["onerror"]) handler.call() except Exception as e: # pylint:disable=broad-except log.warning("[ERROR][_handle_onerror] %s", str(e)) @property def javaUserAgent(self): javaplugin = log.ThugVulnModules._javaplugin.split(".") last = javaplugin.pop() version = f"{'.'.join(javaplugin)}_{last}" return log.ThugOpts.Personality.javaUserAgent % (version,) @property def javaWebStartUserAgent(self): javaplugin = log.ThugVulnModules._javaplugin.split(".") last = javaplugin.pop() version = f"{'.'.join(javaplugin)}_{last}" return f"JNLP/6.0 javaws/{version} (b04) Java/{version}" @property def shockwaveFlash(self): return ",".join(log.ThugVulnModules.shockwave_flash.split(".")) def _check_jnlp_param(self, param): name = param.attrs["name"] value = param.attrs["value"] if name in ("__applet_ssv_validated",) and value.lower() in ("true",): log.ThugLogging.log_exploit_event( self.window.url, "Java WebStart", "Java Security Warning Bypass (CVE-2013-2423)", cve="CVE-2013-2423", ) log.ThugLogging.log_classifier( "exploit", log.ThugLogging.url, "CVE-2013-2423" ) def _handle_jnlp(self, data, headers, params): try: soup = bs4.BeautifulSoup(data, "lxml") except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][_handle_jnlp] %s", str(e)) return jnlp = soup.find("jnlp") if jnlp is None: return # pragma: no cover codebase = jnlp.attrs["codebase"] if "codebase" in jnlp.attrs else "" log.ThugLogging.add_behavior_warn( description="[JNLP Detected]", method="Dynamic Analysis" ) for param in soup.find_all("param"): log.ThugLogging.add_behavior_warn( description=f"[JNLP] {param}", method="Dynamic Analysis" ) self._check_jnlp_param(param) jars = soup.find_all("jar") if not jars: return # pragma: no cover headers["User-Agent"] = self.javaWebStartUserAgent for jar in jars: try: url = f"{codebase}{jar.attrs['href']}" self.window._navigator.fetch( url, headers=headers, redirect_type="JNLP", params=params ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][_handle_jnlp] %s", str(e)) def do_handle_params(self, _object): params = {} for child in _object.find_all(): name = getattr(child, "name", None) if name is None: continue # pragma: no cover if name.lower() in ("param",): if all( p in child.attrs for p in ( "name", "value", ) ): params[child.attrs["name"].lower()] = child.attrs["value"] if "type" in child.attrs: params["type"] = child.attrs["type"] if name.lower() in ("embed",): self.handle_embed(child) if not params: return params hook = getattr(self, "do_handle_params_hook", None) if hook: hook(params) # pylint:disable=not-callable headers = {} headers["Connection"] = "keep-alive" if "type" in params: headers["Content-Type"] = params["type"] else: name = getattr(_object, "name", None) if name in ("applet",) or "archive" in params: headers["Content-Type"] = "application/x-java-archive" if "movie" in params: headers["x-flash-version"] = self.shockwaveFlash if ( "Content-Type" in headers and "java" in headers["Content-Type"] and log.ThugOpts.Personality.javaUserAgent ): headers["User-Agent"] = self.javaUserAgent for key in ( "filename", "movie", ): if key not in params: continue if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: self.window._navigator.fetch( params[key], headers=headers, redirect_type="params", params=params ) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][do_handle_params] %s", str(e)) for key, value in params.items(): if key in ( "filename", "movie", "archive", "code", "codebase", "source", ): continue if key.lower() not in ("jnlp_href",) and not value.startswith("http"): continue if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: response = self.window._navigator.fetch( value, headers=headers, redirect_type="params", params=params ) if response: self._handle_jnlp(response.content, headers, params) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][do_handle_params] %s", str(e)) for p in ("source", "data", "archive"): handler = getattr(self, f"do_handle_params_{p}", None) if handler: handler(params, headers) # pylint:disable=not-callable return params def do_params_fetch(self, url, headers, params): if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: self.window._navigator.fetch( url, headers=headers, redirect_type="params", params=params ) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][do_params_fetch] %s", str(e)) def do_handle_params_source(self, params, headers): if "source" not in params: return self.do_params_fetch(params["source"], headers, params) def do_handle_params_data(self, params, headers): if "data" not in params: return self.do_params_fetch(params["data"], headers, params) def do_handle_params_archive(self, params, headers): if "archive" not in params: return if "codebase" in params: archive = urljoin(params["codebase"], params["archive"]) else: archive = params["archive"] self.do_params_fetch(archive, headers, params) def handle_object(self, _object): log.warning(_object) if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_object_count() self.check_small_element(_object, "object") params = self.do_handle_params(_object) classid = _object.get("classid", None) _id = _object.get("id", None) codebase = _object.get("codebase", None) data = _object.get("data", None) if codebase: if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: self.window._navigator.fetch( codebase, redirect_type="object codebase", params=params ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_object] %s", str(e)) if data and not log.HTTPSession.is_data_uri(data): if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: self.window._navigator.fetch( data, redirect_type="object data", params=params ) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_object] %s", str(e)) if not log.ThugOpts.Personality.isIE(): return if classid: try: axo = _ActiveXObject(self.window, classid, "id") except TypeError as e: # pragma: no cover log.info("[ERROR][handle_object] %s", str(e)) return if _id is None: return try: setattr(self.window, _id, axo) setattr(self.window.doc, _id, axo) except TypeError as e: # pragma: no cover log.info("[ERROR][handle_object] %s", str(e)) def _get_script_for_event_params(self, attr_event): result = [] params = attr_event.split("(") if len(params) > 1: params = params[1].split(")")[0] result = [p for p in params.split(",") if p] return result def _handle_script_for_event(self, script): attr_for = script.get("for", None) attr_event = script.get("event", None) if not attr_for or not attr_event: return params = self._get_script_for_event_params(attr_event) if "playstatechange" in attr_event.lower() and params: with self.context as ctx: newState = params.pop() ctx.eval(f"{newState.strip()} = 0;") try: oldState = params.pop() ctx.eval(f"{oldState.strip()} = 3;") # pragma: no cover except Exception as e: # pylint:disable=broad-except log.info("[ERROR][_handle_script_for_event] %s", str(e)) def get_script_handler(self, script): language = script.get("language", None) if language is None: language = script.get("type", None) if language is None: return getattr(self, "handle_javascript") if language.lower() in ( "jscript.compact", "jscript.encode", ): language = language.lower().replace(".", "_") try: _language = language.lower().split("/")[-1] except Exception: # pragma: no cover,pylint:disable=broad-except log.warning("[SCRIPT] Unhandled script type: %s", language) return None if _language in ("script",): _language = "javascript" # pragma: no cover return getattr(self, f"handle_{_language}", None) def handle_jscript_compact(self, script): log.ThugLogging.log_classifier( "jscript", log.ThugLogging.url, "JScript.Compact" ) self.handle_jscript(script) def handle_jscript_encode(self, script): from .JScriptEncode import JScriptEncode log.ThugLogging.log_classifier("jscript", log.ThugLogging.url, "JScript.Encode") decoder = JScriptEncode() encoded = script.get_text(types=(NavigableString, CData, Script)) js = decoder.decode(encoded) if not js: return if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet(js, "Javascript", "Contained_Inside") self.increase_script_chars_count("javascript", "inline", js) self.check_strings_in_script(js) self.window.evalScript(js, tag=script) log.ThugLogging.Shellcode.check_shellcodes() self.check_anchors() def handle_script(self, script): handler = self.get_script_handler(script) if not handler: return node = getattr(script, "_node", None) self.window.doc._currentScript = node if log.ThugOpts.Personality.isIE(): self._handle_script_for_event(script) handler(script) self.handle_events(script._soup) def handle_external_javascript_text(self, s, response): # First attempt # Requests will automatically decode content from the server. Most # unicode charsets are seamlessly decoded. When you make a request, # Requests makes educated guesses about the encoding of the response # based on the HTTP headers. try: s.text = response.text return True except Exception: # pragma: no cover,pylint:disable=broad-except return self.handle_external_javascript_text_last_attempt(s, response) def handle_external_javascript_text_last_attempt( self, s, response ): # pragma: no cover # Last attempt # The encoding will be (hopefully) detected through the Encoding class. js = response.content enc = log.Encoding.detect(js) if enc["encoding"] is None: log.warning( "[ERROR][handle_external_javascript_text_last attempt] Encoding not detected" ) return False try: s.text = js.decode(enc["encoding"]) except Exception as e: # pylint:disable=broad-except log.warning( "[ERROR][handle_external_javascript_text_last_attempt] %s", str(e) ) return False return True def handle_data_javascript(self, script, src): data = self._handle_data_uri(src) if data is None: return # pragma: no cover s = self.window.doc.createElement("script") for attr in script.attrs: if attr.lower() not in ("src",): s.setAttribute(attr, script.get(attr)) s.text = data.decode() if isinstance(data, bytes) else data def handle_external_javascript(self, script): src = script.get("src", None) if src is None: return if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() if log.HTTPSession.is_data_uri(src): self.handle_data_javascript(script, src) return try: response = self.window._navigator.fetch(src, redirect_type="script src") except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_external_javascript] %s", str(e)) return if response is None or not response.ok or not response.content: return # pragma: no cover if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet(response.content, "Javascript", "External") self.increase_script_chars_count("javascript", "external", response.text) try: s = self.window.doc.createElement("script") except TypeError: # pragma: no cover self.window.evalScript(response.text, tag=script) return for attr in script.attrs: if attr.lower() not in ("src",) and getattr(s, "setAttribute", None): s.setAttribute(attr, script.get(attr)) self.handle_external_javascript_text(s, response) def increase_javascript_count(self, provenance): if not log.ThugOpts.features_logging: return m = getattr( log.ThugLogging.Features, f"increase_{provenance}_javascript_count", None ) if m: m() def increase_script_chars_count(self, type_, provenance, code): if not log.ThugOpts.features_logging: return m = getattr( log.ThugLogging.Features, f"add_{provenance}_{type_}_characters_count", None ) if m: m(len(code)) m = getattr( log.ThugLogging.Features, f"add_{provenance}_{type_}_whitespaces_count", None, ) if m: m(len([a for a in code if a.isspace()])) def check_strings_in_script(self, code): if not log.ThugOpts.features_logging: return for s in ("iframe", "embed", "object", "frame", "form"): count = code.count(s) if not count: continue m = getattr(log.ThugLogging.Features, f"add_{s}_string_count", None) if m: m(count) def get_javascript_provenance(self, script): src = script.get("src", None) return "external" if src else "inline" def handle_javascript(self, script): log.info(script) provenance = self.get_javascript_provenance(script) self.handle_external_javascript(script) self.increase_javascript_count(provenance) js = script.get_text(types=(NavigableString, CData, Script)) if js: if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet(js, "Javascript", "Contained_Inside") if provenance in ("inline",): self.increase_script_chars_count("javascript", provenance, js) self.check_strings_in_script(js) # According to HTML specifications "if the src has a URI value, user # agents must ignore the element's contents and retrieve the script # via the URI" [1] # # [1] https://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.2.1 if provenance in ("inline",): self.window.evalScript(js, tag=script) log.ThugLogging.Shellcode.check_shellcodes() self.check_anchors() def handle_jscript(self, script): self.handle_javascript(script) def handle_vbscript(self, script): log.info(script) if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_inline_vbscript_count() text = script.get_text(types=(NavigableString, CData, Script)) self.handle_vbscript_text(text) def handle_vbscript_text(self, text): log.warning("VBScript parsing not available") url = log.ThugLogging.url if log.ThugOpts.local else log.last_url self.increase_script_chars_count("vbscript", "inline", text) if log.ThugOpts.code_logging: log.ThugLogging.add_code_snippet(text, "VBScript", "Contained_Inside") try: log.ThugLogging.log_file(text, url, sampletype="VBS") log.VBSClassifier.classify(url, text) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_vbscript_text] %s", str(e)) hook = getattr(self, "do_handle_vbscript_text_hook", None) if hook and hook(text): # pylint:disable=not-callable return # pragma: no cover try: urls = re.findall(r"(?P<url>https?://[^\s'\"]+)", text) for url in urls: if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() self.window._navigator.fetch(url, redirect_type="VBS embedded URL") except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_vbscript_text] %s", str(e)) def handle_vbs(self, script): self.handle_vbscript(script) def handle_visualbasic(self, script): self.handle_vbscript(script) def handle_noscript(self, script): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_noscript_count() def handle_html(self, html): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_html_count() def handle_head(self, head): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_head_count() def handle_title(self, title): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_title_count() def handle_body(self, body): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_body_count() def do_handle_form(self, form): log.info(form) action = form.get("action", None) if action in ( None, "self", ): # pragma: no cover last_url = getattr(log, "last_url", None) action = last_url if last_url else self.window.url if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() _action = log.HTTPSession.normalize_url(self.window, action) if _action is None: return # pragma: no cover if _action not in self.forms: self.forms.append(_action) method = form.get("method", "get") payload = None for child in form.find_all(): name = getattr(child, "name", None) if name.lower() in ("input",): if payload is None: payload = {} if all( p in child.attrs for p in ( "name", "value", ) ): payload[child.attrs["name"]] = child.attrs["value"] headers = {} headers["Content-Type"] = "application/x-www-form-urlencoded" try: response = self.window._navigator.fetch( action, headers=headers, method=method.upper(), body=payload, redirect_type="form", ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][do_handle_form] %s", str(e)) return if response is None or not response.ok: return if getattr(response, "thug_mimehandler_hit", False): return # pragma: no cover window = self.do_window_open(_action, response.content) self.run_dft(window, forms=self.forms) def handle_param(self, param): log.info(param) def handle_embed(self, embed): log.warning(embed) if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_embed_count() src = embed.get("src", None) if src is None: src = embed.get("data", None) if src is None: return if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() if self._handle_data_uri(src): return # pragma: no cover headers = {} embed_type = embed.get("type", None) if embed_type: headers["Content-Type"] = embed_type if "Content-Type" in headers: if ( "java" in headers["Content-Type"] and log.ThugOpts.Personality.javaUserAgent ): headers["User-Agent"] = self.javaUserAgent if "flash" in headers["Content-Type"]: headers["x-flash-version"] = self.shockwaveFlash try: self.window._navigator.fetch(src, headers=headers, redirect_type="embed") except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_embed] %s", str(e)) def handle_applet(self, applet): log.warning(applet) params = self.do_handle_params(applet) archive = applet.get("archive", None) if not archive: return if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() headers = {} headers["Connection"] = "keep-alive" headers["Content-type"] = "application/x-java-archive" if log.ThugOpts.Personality.javaUserAgent: headers["User-Agent"] = self.javaUserAgent try: self.window._navigator.fetch( archive, headers=headers, redirect_type="applet", params=params ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_applet] %s", str(e)) def handle_meta(self, meta): log.info(meta) name = meta.get("name", None) if name and name.lower() in ("generator",): content = meta.get("content", None) if content: log.ThugLogging.add_behavior_warn(f"[Meta] Generator: {content}") self.handle_meta_http_equiv(meta) def handle_meta_http_equiv(self, meta): http_equiv = meta.get("http-equiv", None) if http_equiv in (None, "http-equiv"): return content = meta.get("content", None) if content is None: return tag = http_equiv.lower().replace("-", "_") handler = getattr(self, f"handle_meta_{tag}", None) if handler: handler(http_equiv, content) # pylint:disable=not-callable def handle_meta_x_ua_compatible(self, http_equiv, content): # Internet Explorer < 8.0 doesn't support the X-UA-Compatible header # and the webpage doesn't specify a <!DOCTYPE> directive. if ( log.ThugOpts.Personality.isIE() and log.ThugOpts.Personality.browserMajorVersion >= 8 ): if http_equiv.lower() in ("x-ua-compatible",): self.window.doc.compatible = content if "emulate" in content.lower(): log.ThugLogging.log_classifier( "x-ua-compatible", log.ThugLogging.url, content ) def force_handle_meta_x_ua_compatible(self): for meta in self.window.doc.doc.find_all("meta"): http_equiv = meta.get("http-equiv", None) if http_equiv is None: continue if http_equiv.lower() not in ("x-ua-compatible",): continue content = meta.get("content", None) if content is None: continue self.handle_meta_x_ua_compatible(http_equiv, content) def handle_meta_refresh(self, http_equiv, content, delayed=False): if http_equiv.lower() not in ("refresh",) or "url" not in content.lower(): return url = None timeout = 0 data_uri = "data:" in content for s in content.split(";"): if data_uri is True and url is not None: url = f"{url};{s}" s = s.strip() if s.lower().startswith("url="): url = s[4:] continue try: timeout = int(s) except ValueError: pass if not url: return # pragma: no cover if not delayed and timeout > 0: log.ThugLogging.meta_refresh.append((http_equiv, content)) return if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_meta_refresh_count() log.ThugLogging.Features.increase_url_count() if url.startswith("'") and url.endswith("'"): url = url[1:-1] if url.startswith("\\'") and url.endswith("\\'"): url = url[2:-2] n_url = log.HTTPSession._normalize_query_fragment_url(url) if n_url in log.ThugLogging.meta and log.ThugLogging.meta[n_url] >= 3: return # pragma: no cover if data_uri: self._handle_data_uri(url) return try: response = self.window._navigator.fetch(url, redirect_type="meta") except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_meta_refresh] %s", str(e)) return if response is None or not response.ok: return if n_url not in log.ThugLogging.meta: log.ThugLogging.meta[n_url] = 0 log.ThugLogging.meta[n_url] += 1 self.window_open(self.window.url, response.content) def do_handle_frame(self, frame, url, content): window = self.do_window_open(url, content) frame_id = frame.get("id", None) if frame_id: log.ThugLogging.windows[frame_id] = window self.run_dft(window) def handle_frame(self, frame, redirect_type="frame"): if redirect_type not in ("iframe",): log.warning(frame) src = frame.get("src", None) if not src: return if self._handle_data_uri(src): return if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() try: response = self.window._navigator.fetch(src, redirect_type=redirect_type) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_frame] %s", str(e)) return if response is None or not response.ok: return # pragma: no cover if ( response.url in log.ThugLogging.frames and log.ThugLogging.frames[response.url] >= 3 ): return # pragma: no cover if response.url not in log.ThugLogging.frames: log.ThugLogging.frames[response.url] = 0 log.ThugLogging.frames[response.url] += 1 if getattr(response, "thug_mimehandler_hit", False): return # pragma: no cover self.do_handle_frame(frame, response.url, response.content) def handle_iframe(self, iframe): log.warning(iframe) if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_iframe_count() self.check_small_element(iframe, "iframe") srcdoc = iframe.get("srcdoc", None) if srcdoc: url = log.ThugLogging.url if log.ThugOpts.local else log.last_url self.do_handle_frame(iframe, url, srcdoc) return self.handle_frame(iframe, "iframe") def do_handle_font_face_rule(self, rule): for p in rule.style: if p.name.lower() not in ("src",): continue url = p.value if url.startswith("url(") and len(url) > 4: url = url.split("url(")[1].split(")")[0] if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() if self._handle_data_uri(url): continue # pragma: no cover try: self.window._navigator.fetch(url, redirect_type="font face") except Exception as e: # pylint:disable=broad-except log.info("[ERROR][do_handle_font_face_rule] %s", str(e)) return def handle_style(self, style): log.info(style) cssparser = CSSParser(loglevel=logging.CRITICAL, validate=False) try: sheet = cssparser.parseString(style.encode_contents()) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_style] %s", str(e)) return for rule in sheet: if rule.type == rule.FONT_FACE_RULE: self.do_handle_font_face_rule(rule) def _check_decode_data_uri(self, data, opts): mimetypes = ( "application/javascript", "application/x-javascript", "text/javascript", ) if opts and opts[0].lower() in mimetypes: data.decode() def _handle_data_uri(self, uri): """ Data URI Scheme data:[<MIME-type>][;charset=<encoding>][;base64],<data> The encoding is indicated by ;base64. If it is present the data is encoded as base64. Without it the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard %xx hex encoding of URLs for octets outside that range. If <MIME-type> is omitted, it defaults to text/plain;charset=US-ASCII. (As a shorthand, the type can be omitted but the charset parameter supplied.) Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset's specification must precede the base64 token. """ uri = uri if isinstance(uri, str) else str(uri) if not log.HTTPSession.is_data_uri(uri): return None if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_data_uri_count() h = uri.split(",") if len(h) < 2 or not h[1]: return None # pragma: no cover data = h[1] opts = h[0][len("data:") :].split(";") if "base64" in opts: try: data = base64.b64decode(h[1]) self._check_decode_data_uri(data, opts) except Exception: # pylint:disable=broad-except try: data = base64.b64decode(unquote(h[1]).strip()) self._check_decode_data_uri(data, opts) except Exception: # pragma: no cover,pylint:disable=broad-except log.warning("[WARNING] Error while handling data URI: %s", data) return None opts.remove("base64") if not opts or not opts[0]: opts = ["text/plain", "charset=US-ASCII"] mimetype = opts[0] handler = log.MIMEHandler.get_handler(mimetype) if handler: handler(self.window.url, data) return None if mimetype.startswith(("text/html",)): self.window_open(self.window.url, data) return data def _handle_blob_uri(self, uri): uri = uri if isinstance(uri, str) else str(uri) if not log.HTTPSession.is_blob_uri(uri): return # pragma: no cover blob = log.UrlObjects.get(uri, None) if not blob: return # pragma: no cover handler = log.MIMEHandler.get_handler(blob.type) if handler: handler(self.window.url, blob.blob) return log.ThugLogging.log_file(blob.blob, uri) # pragma: no cover def handle_a(self, anchor): log.info(anchor) self.anchors.append(anchor) if not log.ThugOpts.extensive: return href = anchor.get("href", None) if not href: return # pragma: no cover if self._handle_data_uri(href): return try: response = self.window._navigator.fetch(href, redirect_type="anchor") except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_a] %s", str(e)) return if response is None or not response.ok: return # pragma: no cover content_type = response.headers.get("content-type", None) if not content_type: return # pragma: no cover if content_type.startswith(("text/html",)): self.window_open(self.window.url, response.content) def handle_link(self, link): log.info(link) # When a browser requests a resource from a third party server, that cross-origin’s # domain name must be resolved to an IP address before the browser can issue the # request. This process is known as DNS resolution. While DNS caching can help to # reduce this latency, DNS resolution can add significant latency to requests. For # websites that open connections to many third parties, this latency can significantly # reduce loading performance. # # dns-prefetch helps developers mask DNS resolution latency. The HTML <link> element # offers this functionality by way of a rel attribute value of dns-prefetch. The # cross-origin domain is then specified in the href attribute rel = link.get("rel", None) if rel and any(r in ("dns-prefetch",) for r in rel): return # pragma: no cover href = link.get("href", None) if not href: return # pragma: no cover if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_url_count() if self._handle_data_uri(href): return # pragma: no cover is_favicon = rel and any(r in ("icon",) for r in rel) try: response = self.window._navigator.fetch( href, redirect_type="link", disable_download_prevention=is_favicon ) except Exception as e: # pylint:disable=broad-except log.info("[ERROR][handle_link] %s", str(e)) return if not response or not response.ok: return if is_favicon: log.ThugLogging.log_favicon(response.url, response.content) def handle_img(self, img): log.info(img) src = img.get("src", None) if not src: return # pragma: no cover if self._handle_data_uri(src): return # pragma: no cover cache = getattr(self, "img_cache", None) if not cache: self.img_cache = set() if src in self.img_cache: return # pragma: no cover self.img_cache.add(src) try: self.window._navigator.fetch(src, redirect_type="img") except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][handle_img] %s", str(e)) self._handle_onerror(img) def check_anchors(self): clicked_anchors = [a for a in self.anchors if "_clicked" in a.attrs] if not clicked_anchors: return clicked_anchors.sort(key=lambda anchor: anchor["_clicked"]) for anchor in clicked_anchors: del anchor["_clicked"] if "href" not in anchor.attrs: continue # pragma: no cover href = anchor.attrs["href"] self.follow_href(href) def follow_href(self, href): window = self.do_window_open(self.window.url, "") window = window.open(href) if window: self.run_dft(window) def do_handle(self, child, soup, skip=True): name = getattr(child, "name", None) if name is None: return False if skip and name in ( "object", "applet", ): return False handler = None try: handler = getattr(self, f"handle_{str(name.lower())}", None) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[ERROR][do_handle] %s", str(e)) child._soup = soup if handler: handler(child) if name in ("script",): self.run_htmlclassifier(soup) return True return False def check_hidden_element(self, element): if not log.ThugOpts.features_logging: return attrs = getattr(element, "attrs", None) if attrs is None: return if "hidden" in attrs: log.ThugLogging.Features.increase_hidden_count() def check_small_element(self, element, tagname): if not log.ThugOpts.features_logging: return attrs = getattr(element, "attrs", None) if attrs is None: return # pragma: no cover attrs_count = 0 element_area = 1 for key in ("width", "height"): if key not in attrs: continue try: value = int(attrs[key].split("px")[0]) except Exception: # pylint:disable=broad-except value = None if not value: continue if value <= 2: m = getattr( log.ThugLogging.Features, f"increase_{tagname}_small_{key}_count", None, ) if m: m() attrs_count += 1 element_area *= value if attrs_count > 1 and element_area < 30: m = getattr( log.ThugLogging.Features, f"increase_{tagname}_small_area_count", None ) if m: m() def run_htmlclassifier(self, soup): try: log.HTMLClassifier.classify( log.ThugLogging.url if log.ThugOpts.local else self.window.url, str(soup), ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.info("[ERROR][run_htmlclassifier] %s", str(e)) def do_window_open(self, url, content): doc = w3c.parseString(content) window = log.Window(url, doc, personality=log.ThugOpts.useragent) return window def run_dft(self, window, forms=None): if forms is None: forms = [] dft = DFT(window, forms=forms) dft.run() def window_open(self, url, content): window = self.do_window_open(url, content) self.run_dft(window) def async_prefetch(self, soup): for tag in soup.find_all(self.async_prefetch_tags): src = tag.get("src", None) if src: self.async_prefetcher.fetch(src) def _run(self, soup=None): if soup is None: soup = self.window.doc.doc _soup = soup if log.ThugOpts.async_prefetch: self.async_prefetch(soup) # Dirty hack for p in soup.find_all("object"): self.check_hidden_element(p) self.handle_object(p) self.run_htmlclassifier(soup) for p in soup.find_all("applet"): self.check_hidden_element(p) self.handle_applet(p) for child in soup.descendants: if child is None: continue # pragma: no cover self.check_hidden_element(child) parents = [p.name.lower() for p in child.parents] if "noscript" in parents: continue self.set_event_handler_attributes(child) if not self.do_handle(child, soup): continue analyzed = set() recur = True while recur: recur = False if tuple(soup.descendants) == tuple(_soup.descendants): break for _child in set(soup.descendants) - set( _soup.descendants ): # pragma: no cover if _child not in analyzed: analyzed.add(_child) recur = True name = getattr(_child, "name", None) if name: self.do_handle(_child, soup, False) analyzed.clear() _soup = soup self.window.doc._readyState = "complete" for child in soup.descendants: self.set_event_listeners(child) self.handle_events(soup) while log.ThugLogging.meta_refresh: http_equiv, content = log.ThugLogging.meta_refresh.pop() self.handle_meta_refresh(http_equiv, content, True) def handle_events(self, soup): for evt in self.handled_on_events: try: self.handle_window_event(evt) except Exception: # pragma: no cover,pylint:disable=broad-except log.warning("[handle_events] Event %s not properly handled", evt) for evt in self.handled_on_events: try: self.handle_document_event(evt) except Exception: # pragma: no cover,pylint:disable=broad-except log.warning("[handle_events] Event %s not properly handled", evt) for evt in self.handled_events: try: self.handle_element_event(evt) except Exception: # pragma: no cover,pylint:disable=broad-except log.warning("[handle_events] Event %s not properly handled", evt) self.run_htmlclassifier(soup) def run(self): with self.context: self._run() log.ThugLogging.Shellcode.check_shellcodes()
56,116
Python
.py
1,316
31.206687
132
0.577493
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,752
Storage.py
buffer_thug/thug/DOM/Storage.py
#!/usr/bin/env python # # Storage.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from collections import OrderedDict from .JSClass import JSClass log = logging.getLogger("Thug") class Storage(OrderedDict, JSClass): def __str__(self): return "[object Storage]" @property def length(self): return len(self) def key(self, index): if index > self.length: return None return list(self.keys())[index - 1] def getItem(self, key): try: return super().__getitem__(key) except KeyError: return None def __setitem__(self, key, value, dict_setitem=dict.__setitem__): self.setItem(key, value) def setItem(self, key, value): from thug.DOM.W3C.Events.StorageEvent import StorageEvent oldvalue = self[key] if key in self else None super().__setitem__(key, value) log.WebTracking.inspect_storage_setitem(self, key, value) evtObject = StorageEvent() evtObject.initStorageEvent( "storage", False, False, key, oldvalue, value, log.DFT.window.url, self ) log.DFT.handle_window_storage_event("onstorage", evtObject) def __delitem__(self, key, dict_delitem=dict.__delitem__): # pragma: no cover self.removeItem(key) def removeItem(self, key): from thug.DOM.W3C.Events.StorageEvent import StorageEvent oldvalue = self[key] if key in self else None super().__delitem__(key) log.WebTracking.inspect_storage_removeitem(self, key) evtObject = StorageEvent() evtObject.initStorageEvent( "storage", False, False, key, oldvalue, None, log.DFT.window.url, self ) log.DFT.handle_window_storage_event("onstorage", evtObject) def clear(self): from thug.DOM.W3C.Events.StorageEvent import StorageEvent super().clear() self.__init__() log.WebTracking.inspect_storage_clear(self) evtObject = StorageEvent() evtObject.initStorageEvent( "storage", False, False, None, None, None, log.DFT.window.url, self ) log.DFT.handle_window_storage_event("onstorage", evtObject)
2,830
Python
.py
70
33.842857
83
0.675923
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,753
Sidebar.py
buffer_thug/thug/DOM/Sidebar.py
#!/usr/bin/env python # # Sidebar.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .JSClass import JSClass log = logging.getLogger("Thug") class Sidebar(JSClass): def __init__(self): self._providers = set() self._engines = set() self._favorites = set() self._generators = set() def addMicrosummaryGenerator(self, generatorURL): self._generators.add(generatorURL) def addPanel(self, title, URL, customizeURL): self._favorites.add((title, URL, customizeURL)) def addPersistentPanel(self, title, URL, customizeURL): self._favorites.add((title, URL, customizeURL)) def addSearchEngine(self, engineURL, iconURL, message, suggestedCategory): self._engines.add((engineURL, iconURL, message, suggestedCategory)) def AddSearchProvider(self, URL): self._providers.add(URL) def IsSearchProviderInstalled(self, URL): if URL in self._providers: return ( 1 # A matching search provider is installed, but it is not the default. ) return 0 # No installed search provider was found with the specified prefix
1,775
Python
.py
42
37.261905
88
0.715863
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,754
JSEngine.py
buffer_thug/thug/DOM/JSEngine.py
#!/usr/bin/env python # # JSEngine.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import logging import configparser try: import STPyV8 as V8 except ImportError: # pragma: no cover import PyV8 as V8 import thug log = logging.getLogger("Thug") class JSEngine: builtins = ( "Map", "Set", "WeakMap", "WeakSet", ) def __init__(self): self.init_config() self.init_engine() @property def builtin_map(self): return [ { "method": log.ThugOpts.Personality.isIE, "min_Map": 11, "min_Map_iter": 100, "min_Set": 11, "min_Set_iter": 100, "min_WeakMap": 11, "min_WeakMap_iter": 100, "min_WeakSet": 100, "min_WeakSet_iter": 100, }, { "method": log.ThugOpts.Personality.isChrome, "min_Map": 38, "min_Map_iter": 38, "min_Set": 38, "min_Set_iter": 38, "min_WeakMap": 36, "min_WeakMap_iter": 38, "min_WeakSet": 36, "min_WeakSet_iter": 38, }, { "method": log.ThugOpts.Personality.isFirefox, "min_Map": 13, "min_Map_iter": 13, "min_Set": 13, "min_Set_iter": 13, "min_WeakMap": 6, "min_WeakMap_iter": 36, "min_WeakSet": 34, "min_WeakSet_iter": 34, }, { "method": log.ThugOpts.Personality.isSafari, "min_Map": 8, "min_Map_iter": 9, "min_Set": 8, "min_Set_iter": 9, "min_WeakMap": 8, "min_WeakMap_iter": 9, "min_WeakSet": 9, "min_WeakSet_iter": 9, }, ] def init_config(self): conf_file = os.path.join(log.configuration_path, "thug.conf") self.config = configparser.ConfigParser() self.config.read(conf_file) def init_engine(self): self.engine = self.config.get("jsengine", "engine") @property def JSLocker(self): return V8.JSLocker() def init_v8_context(self, window): self._context = V8.JSContext(window) V8.JSEngine.setStackLimit(1024 * 1024) def do_init_context(self, window): m = getattr(self, f"init_{self.engine}_context", None) if m: m(window) # pylint:disable=not-callable def init_scripts_thug(self, ctxt): thug_js = os.path.join(thug.__scripts_path__, "thug.js") with open(thug_js, encoding="utf-8", mode="r") as fd: thug_js_code = fd.read() ctxt.eval(thug_js_code) def init_scripts_atob(self, ctxt): atob_js = os.path.join(thug.__scripts_path__, "atob.js") with open(atob_js, encoding="utf-8", mode="r") as fd: atob_js_code = fd.read() ctxt.eval(atob_js_code) def init_scripts_btoa(self, ctxt): btoa_js = os.path.join(thug.__scripts_path__, "btoa.js") with open(btoa_js, encoding="utf-8", mode="r") as fd: btoa_js_code = fd.read() ctxt.eval(btoa_js_code) def init_scripts_storage(self, ctxt): if not log.ThugOpts.Personality.isIE(): return if log.ThugOpts.Personality.browserMajorVersion < 8: storage_js = os.path.join(thug.__scripts_path__, "storage.js") with open(storage_js, encoding="utf-8", mode="r") as fd: storage_js_code = fd.read() ctxt.eval(storage_js_code) def init_scripts_date(self, ctxt): if not log.ThugOpts.Personality.isIE(): return if log.ThugOpts.Personality.browserMajorVersion < 9: date_js = os.path.join(thug.__scripts_path__, "date.js") with open(date_js, encoding="utf-8", mode="r") as fd: date_js_code = fd.read() ctxt.eval(date_js_code) def init_scripts_message_event(self, ctxt): if ( log.ThugOpts.Personality.isFirefox() and log.ThugOpts.Personality.browserMajorVersion > 26 ): return if not log.ThugOpts.Personality.isIE(): return message_event_js = os.path.join(thug.__scripts_path__, "message-event.js") with open(message_event_js, encoding="utf-8", mode="r") as fd: message_event_js_code = fd.read() ctxt.eval(message_event_js_code) def undefine_object_iter(self, ctxt, jso): ctxt.eval(f"{jso}.prototype.forEach = undefined") def undefine_object(self, ctxt, jso): ctxt.eval(f"{jso} = undefined") def do_init_scripts_builtin(self, ctxt, item): for jso in self.builtins: if log.ThugOpts.Personality.browserMajorVersion < item[f"min_{jso}"]: self.undefine_object(ctxt, jso) continue if log.ThugOpts.Personality.browserMajorVersion < item[f"min_{jso}_iter"]: self.undefine_object_iter(ctxt, jso) def init_scripts_builtin(self, ctxt): for item in self.builtin_map: if item["method"](): self.do_init_scripts_builtin(ctxt, item) return def init_hooks(self, ctxt): hooks = ( os.listdir(thug.__hooks_path__) if os.path.exists(thug.__hooks_path__) else [] ) for hook in sorted([h for h in hooks if h.endswith(".js")]): with open( os.path.join(thug.__hooks_path__, hook), encoding="utf-8", mode="r" ) as fd: # pragma: no cover hook_code = fd.read() ctxt.eval(hook_code) for hook in ("eval", "write"): js = os.path.join(thug.__scripts_path__, f"{hook}.js") if not os.path.exists(js): # pragma: no cover continue symbol = getattr(log.ThugLogging, f"{hook}_symbol") with open(js, encoding="utf-8", mode="r") as fd: js_code = fd.read() ctxt.eval(js_code % {"name": symbol[0], "saved": symbol[1]}) def init_scripts(self): with self._context as ctxt: self.init_scripts_thug(ctxt) self.init_scripts_atob(ctxt) self.init_scripts_btoa(ctxt) self.init_scripts_storage(ctxt) self.init_scripts_date(ctxt) self.init_scripts_builtin(ctxt) self.init_scripts_message_event(ctxt) self.init_hooks(ctxt) def init_v8_symbols(self): self.terminateAllThreads = V8.JSEngine.terminateAllThreads def init_symbols(self): m = getattr(self, f"init_{self.engine}_symbols", None) if m: m() # pylint:disable=not-callable @property def context(self): return self._context def init_context(self, window): self.do_init_context(window) self.init_scripts() self.init_symbols() def is_v8_jsfunction(self, symbol): return isinstance(symbol, V8.JSFunction) def isJSFunction(self, symbol): m = getattr(self, f"is_{self.engine}_jsfunction", None) return m(symbol) if m else False # pylint:disable=not-callable def is_v8_jsobject(self, symbol): return isinstance(symbol, V8.JSObject) def isJSObject(self, symbol): m = getattr(self, f"is_{self.engine}_jsobject", None) return m(symbol) if m else False # pylint:disable=not-callable
8,294
Python
.py
212
28.764151
86
0.564974
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,755
Map.py
buffer_thug/thug/DOM/Map.py
#!/usr/bin/env python # # Map.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class Map(JSClass): def __init__(self): pass
762
Python
.py
21
34.571429
70
0.765583
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,756
JSClass.py
buffer_thug/thug/DOM/JSClass.py
import os import collections.abc class JSClass: __properties__ = {} __methods__ = {} __watchpoints__ = {} def __str__(self): return self.toString() def __getattr__(self, name): if name == "constructor": return JSClassConstructor(self.__class__) if name == "prototype": return JSClassPrototype(self.__class__) prop = self.__dict__.setdefault("__properties__", {}).get(name, None) if prop and isinstance(prop[0], collections.abc.Callable): return prop[0]() method = self.__methods__.get(name, None) if method and isinstance(method, collections.abc.Callable): return method raise AttributeError(name) def __setattr__(self, name, value): prop = self.__dict__.setdefault("__properties__", {}).get(name, None) if prop and isinstance(prop[1], collections.abc.Callable): return prop[1](value) return object.__setattr__(self, name, value) def toString(self): """Returns a string representation of an object""" return f"[object {self.__class__.__name__}]" def toLocaleString(self): """Returns a value as a string value appropriate to the host environment's current locale""" return self.toString() def valueOf(self): """Returns the primitive value of the specified object""" return self def hasOwnProperty(self, name): """Returns a Boolean value indicating whether an object has a property with the specified name""" return hasattr(self, name) # def isPrototypeOf(self, obj): # """Returns a Boolean value indicating whether an object exists in the prototype chain of another object""" # raise NotImplementedError() def __defineGetter__(self, name, getter): """Binds an object's property to a function to be called when that property is looked up""" self.__properties__[name] = (getter, self.__lookupSetter__(name)) def __lookupGetter__(self, name): """Return the function bound as a getter to the specified property""" return self.__properties__.get(name, (None, None))[0] def __defineSetter__(self, name, setter): """Binds an object's property to a function to be called when an attempt is made to set that property""" self.__properties__[name] = (self.__lookupGetter__(name), setter) def __lookupSetter__(self, name): """Return the function bound as a setter to the specified property""" return self.__properties__.get(name, (None, None))[1] def watch(self, prop, handler): """Watches for a property to be assigned a value and runs a function when that occurs""" self.__watchpoints__[prop] = handler def unwatch(self, prop): """Removes a watchpoint set with the watch method""" del self.__watchpoints__[prop] class JSClassConstructor(JSClass): def __init__(self, cls): self.cls = cls @property def name(self): return self.cls.__name__ def toString(self): return f"function {self.name}() {{{os.linesep} [native code]{os.linesep}}}" def __call__(self, *args, **kwds): return self.cls(*args, **kwds) class JSClassPrototype(JSClass): def __init__(self, cls): self.cls = cls @property def constructor(self): return JSClassConstructor(self.cls) @property def name(self): return self.cls.__name__
3,501
Python
.py
77
37.818182
115
0.63355
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,757
SessionStorage.py
buffer_thug/thug/DOM/SessionStorage.py
#!/usr/bin/env python # # SessionStorage.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .Storage import Storage class SessionStorage(Storage): pass
756
Python
.py
20
36.45
70
0.785812
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,758
History.py
buffer_thug/thug/DOM/History.py
#!/usr/bin/env python # # History.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .JSClass import JSClass from .Alexa import Alexa log = logging.getLogger("Thug") class History(JSClass): def __init__(self, window): self._window = window self.urls = Alexa self.pos = len(self.urls) - 1 self.__init_history_personality() def __init_history_personality(self): self._navigationMode = "automatic" if log.ThugOpts.Personality.isIE(): self.__init_history_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_history_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_history_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_history_personality_Safari() return def __init_history_personality_IE(self): pass def __init_history_personality_Firefox(self): self.current = self._current self.next = self._next self.previous = self._previous def __init_history_personality_Chrome(self): pass def __init_history_personality_Safari(self): pass @property def window(self): return self._window @property def length(self): return len(self.urls) @property def _current(self): return self.urls[self.pos] if self.length > self.pos and self.pos > 0 else None @property def _next(self): return ( self.urls[self.pos + 1] if self.length > self.pos + 1 and self.pos > 0 else None ) @property def _previous(self): return ( self.urls[self.pos - 1] if self.length > self.pos - 1 and self.pos > 0 else None ) def _get_navigationMode(self): return self._navigationMode def _set_navigationMode(self, value): if value in ( "automatic", "compatible", "fast", ): self._navigationMode = value navigationMode = property(_get_navigationMode, _set_navigationMode) def pushState(self, state, title, URL): # self._window.url = URL pass def back(self): """Loads the previous URL in the history list""" return self.go(-1) def forward(self): """Loads the next URL in the history list""" return self.go(1) def go(self, num_or_url): """Loads a specific URL from the history list""" try: off = int(num_or_url) self.pos += off self.pos = min(max(0, self.pos), len(self.urls) - 1) self._window.open(self.urls[self.pos]) except ValueError: self._window.open(num_or_url) def update(self, url, replace=False): if replace: self.urls[self.pos] = url return if self.urls[self.pos] != url: self.urls.insert(self.pos, url) self.pos += 1
3,717
Python
.py
109
26.330275
87
0.618222
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,759
Plugin.py
buffer_thug/thug/DOM/Plugin.py
#!/usr/bin/env python # # Plugin.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class Plugin(JSClass): def __init__(self, init=None): self._plugin = {} if init is None: return for k, v in init.items(): self._plugin[k] = v def __setitem__(self, key, value): self._plugin[key] = value def __getitem__(self, name): if name not in self._plugin: return None return self._plugin[name] def __delitem__(self, name): if name not in self._plugin: return del self._plugin[name]
1,231
Python
.py
35
30.2
70
0.676793
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,760
WebStore.py
buffer_thug/thug/DOM/WebStore.py
#!/usr/bin/env python # # WebStore.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class WebStore(JSClass): def __init__(self): pass def __str__(self): return "[object Object]"
829
Python
.py
23
33.826087
70
0.75187
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,761
UserProfile.py
buffer_thug/thug/DOM/UserProfile.py
#!/usr/bin/env python # # UserProfile.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class UserProfile(JSClass): vCardSchemas = ( "vCard.Business.City", "vCard.Business.Country", "vCard.Business.Fax", "vCard.Business.Phone", "vCard.Business.State", "vCard.Business.StreetAddress", "vCard.Business.URL", "vCard.Business.Zipcode", "vCard.Cellular", "vCard.Company", "vCard.Department", "vCard.DisplayName", "vCard.Email", "vCard.FirstName", "vCard.Gender", "vCard.Home.City", "vCard.Home.Country", "vCard.Home.Fax", "vCard.Home.Phone", "vCard.Home.State", "vCard.Home.StreetAddress", "vCard.Home.Zipcode", "vCard.Homepage", "vCard.JobTitle", "vCard.LastName", "vCard.MiddleName", "vCard.Notes", "vCard.Office", "vCard.Pager", ) def __init__(self): self._vCard = {} self._queue = [] def addReadRequest(self, vCardName, reserved=None): # pylint:disable=unused-argument for schema in self.vCardSchemas: if schema.lower() == vCardName.lower(): self._queue.append(vCardName) return True return False def doReadRequest( self, usageCode, displayName=None, domain=None, path=None, expiration=None, reserved=None, ): pass def clearRequest(self): del self._queue[:] def getAttribute(self, vCardName): if vCardName not in self.vCardSchemas: return None if vCardName not in self._vCard: return None return self._vCard[vCardName] def setAttribute(self, vCardName, vCardValue, caseSens=1): if caseSens: if vCardName not in self.vCardSchemas: return self._vCard[vCardName] = vCardValue return for schema in self.vCardSchemas: if schema.lower() == vCardName.lower(): self._vCard[schema] = vCardValue return
2,805
Python
.py
87
24.45977
89
0.619453
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,762
SchemeHandler.py
buffer_thug/thug/DOM/SchemeHandler.py
import logging log = logging.getLogger("Thug") class SchemeHandler: def __init__(self): pass def handle_hcp(self, window, url): log.warning("Microsoft Internet Explorer HCP Scheme Detected") hcp = url.split("svr=") if len(hcp) < 2: return hcp = hcp[1].split("defer>") if len(hcp) < 2: return hcp = hcp[1].split("</script") log.ThugLogging.add_behavior_warn( "Microsoft Windows Help Center Malformed Escape Sequences Incorrect Handling", "CVE-2010-1885", ) log.ThugLogging.log_classifier("exploit", log.ThugLogging.url, "CVE-2010-1885") if not hcp or not hcp[0]: return window.evalScript(hcp[0]) def handle_res(self, window, url): # pylint:disable=unused-argument log.warning("Microsoft Internet Explorer RES Scheme Detected") try: log.URLClassifier.classify(url) except Exception: # pragma: no cover,pylint:disable=broad-except pass
1,064
Python
.py
28
28.821429
90
0.612903
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,763
HTTPSession.py
buffer_thug/thug/DOM/HTTPSession.py
#!/usr/bin/env python # # HTTPSession.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging import sys import socket import ssl import urllib.parse import requests import urllib3 urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning) log = logging.getLogger("Thug") class HTTPSession: def __init__(self, proxy=None): self.__init_download_prevention() if proxy is None: proxy = log.ThugOpts.proxy self.__init_session(proxy) self.filecount = 0 def __check_proxy_alive(self, hostname, port): s = socket.create_connection( (hostname, port), timeout=log.ThugOpts.proxy_connect_timeout ) s.close() def __do_init_proxy(self, proxy): url = urllib.parse.urlparse(proxy) if not url.scheme: return False if not url.scheme.lower().startswith(("http", "socks4", "socks5")): return False try: self.__check_proxy_alive(url.hostname, url.port) except Exception as e: # pylint:disable=broad-except log.critical("[CRITICAL] Proxy not available. Aborting the analysis!") if log.ThugOpts.raise_for_proxy: raise ValueError("[CRITICAL] Proxy not available") from e sys.exit(0) # pragma: no cover self.session.proxies = {"http": proxy, "https": proxy} return True def __init_proxy(self, proxy): if proxy is None: return if self.__do_init_proxy(proxy): return log.critical("[CRITICAL] Wrong proxy specified. Aborting the analysis!") sys.exit(0) def __init_session(self, proxy): self.session = requests.Session() self.__init_proxy(proxy) def __init_download_prevention(self): if not log.ThugOpts.download_prevent: self.download_prevented_mimetypes = tuple() return mimetypes = ["audio/", "video/"] if not log.ThugOpts.image_processing: mimetypes.append("image/") self.download_prevented_mimetypes = tuple(mimetypes) def _normalize_protocol_relative_url(self, window, url): if not url.startswith("//"): return url if window.url in ("about:blank",): return f"http:{url}" base_url = urllib.parse.urlparse(window.url) return f"{base_url.scheme}:{url}" if base_url.scheme else f"http:{url}" @staticmethod def _normalize_query_fragment_url(url): p_url = urllib.parse.urlparse(urllib.parse.urldefrag(url)[0]) p_query = urllib.parse.parse_qs(p_url.query, keep_blank_values=True) e_query = urllib.parse.urlencode(p_query.fromkeys(p_query, "")) return p_url._replace(query=e_query).geturl() def _is_compatible(self, url, scheme): return url.startswith(f"{scheme}:/") and not url.startswith(f"{scheme}://") def _check_compatibility(self, url): for scheme in ( "http", "https", ): if self._is_compatible(url, scheme): return f"{scheme}://{url.split(f'{scheme}:/')[1]}" return url def is_download_prevented(self, mimetype=None): if mimetype and mimetype.startswith(self.download_prevented_mimetypes): return True return False @staticmethod def is_data_uri(url): if url.lower().startswith("data:"): return True if url.startswith(("'", '"')) and url[1:].lower().startswith("data:"): return True # pragma: no cover return False @staticmethod def is_blob_uri(url): if url.lower().startswith("blob:"): return True if url.startswith(("'", '"')) and url[1:].lower().startswith("blob:"): return True # pragma: no cover return False def normalize_url(self, window, url): url = url.strip() # Do not normalize Data and Blob URI scheme if ( url.lower().startswith("url=") or self.is_data_uri(url) or self.is_blob_uri(url) ): return url if url.startswith("#"): log.warning("[INFO] Ignoring anchor: %s", url) return None # Check the URL is not broken (i.e. http:/www.google.com) and # fix it if the broken URL option is enabled. if log.ThugOpts.broken_url: url = self._check_compatibility(url) url = self._normalize_protocol_relative_url(window, url) try: url = urllib.parse.quote(url, safe="%/:=&?~#+!$,;'@()*[]{}") except KeyError: # pragma: no cover pass _url = urllib.parse.urlparse(url) base_url = None last_url = getattr(log, "last_url", None) for _base_url in ( last_url, window.url, ): if not _base_url: continue base_url = _base_url p_base_url = urllib.parse.urlparse(base_url) if p_base_url.scheme: break # Check if a scheme handler is registered and calls the proper # handler in such case. This is how a real browser would handle # a specific scheme so if you want to add your own handler for # analyzing specific schemes the proper way to go is to define # a method named handle_<scheme> in the SchemeHandler and put # the logic within such method. handler = getattr(log.SchemeHandler, f"handle_{_url.scheme}", None) if handler: handler(window, url) return None if not _url.netloc and base_url: _url = urllib.parse.urljoin(base_url, url) log.warning("[Navigator URL Translation] %s --> %s", url, _url) return _url return url def check_equal_urls(self, url, last_url): return urllib.parse.unquote(url) in (urllib.parse.unquote(last_url),) def check_redirection_loop_url_params(self, url): p_url = urllib.parse.urlparse(url) qs = urllib.parse.parse_qs(p_url.query) # If the query string contains more than 10 parameters with the # same name we are reasonably experiencing a redirection loop return any(len(v) > 10 for v in qs.values()) def build_http_headers(self, window, personality, headers): http_headers = { "Cache-Control": "no-cache", "Accept-Language": "en-US", "Accept": "*/*", "User-Agent": personality, } if window and window.url not in ("about:blank",): referer = ( window.url if window.url.startswith("http") else f"http://{window.url}" ) http_headers["Referer"] = referer # REVIEW ME! # if window and window.doc.cookie: # http_headers['Cookie'] = window.doc.cookie for name, value in headers.items(): http_headers[name] = value return http_headers def fetch_ssl_certificate(self, url): if not log.ThugOpts.cert_logging: return _url = urllib.parse.urlparse(url) if _url.scheme not in ("https",): return port = _url.port if _url.port else 443 certificate = log.ThugLogging.ssl_certs.get((_url.netloc, port), None) if certificate: return try: certificate = ssl.get_server_certificate( (_url.netloc, port), ssl_version=ssl.PROTOCOL_TLS_CLIENT ) log.ThugLogging.ssl_certs[(_url.netloc, port)] = certificate log.ThugLogging.log_certificate(url, certificate) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[SSL ERROR] %s", str(e)) def fetch( self, url, method="GET", window=None, personality=None, headers=None, body=None ): if log.URLClassifier.filter(url): return None if self.is_data_uri(url): log.DFT._handle_data_uri(url) return None if self.is_blob_uri(url): log.DFT._handle_blob_uri(url) return None fetcher = getattr(self.session, method.lower(), None) if fetcher is None: # pragma: no cover log.warning("Not supported method: %s", method) return None if headers is None: # pragma: no cover headers = {} response = None try: async_prefetcher = getattr(log.DFT, "async_prefetcher", None) except Exception: # pylint: disable=broad-except async_prefetcher = None if async_prefetcher: async_result = async_prefetcher.responses.get(url, None) if async_result: response = async_result.result() if response is None: _headers = self.build_http_headers(window, personality, headers) try: response = fetcher( url, # pylint:disable=not-callable headers=_headers, timeout=log.ThugOpts.connect_timeout, data=body, verify=log.ThugOpts.ssl_verify, stream=True, ) except requests.ConnectionError as e: log.warning("[HTTPSession] %s", str(e)) raise if not response.ok: return None log.ThugLogging.retrieved_urls.add(url) self.filecount += 1 if log.ThugOpts.web_tracking: log.WebTracking.inspect_response(response) return response def threshold_expired(self, url): if not log.ThugOpts.threshold: return False if self.filecount >= log.ThugOpts.threshold: log.ThugLogging.log_location( url, None, flags={"error": "Threshold Exceeded"} ) return True return False @property def no_fetch(self): return log.ThugOpts.no_fetch def about_blank(self, url): return url.lower() in ("about:blank",) def get_cookies(self): return self.session.cookies def set_cookies(self, name, value): self.session.cookies.set(name, value) cookies = property(get_cookies, set_cookies)
10,997
Python
.py
271
30.686347
87
0.598345
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,764
Components.py
buffer_thug/thug/DOM/Components.py
#!/usr/bin/env python # # Components.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass from .Utils import Utils class Components(JSClass): def __init__(self): self.utils = Utils()
817
Python
.py
22
35.454545
70
0.768939
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,765
AsyncPrefetcher.py
buffer_thug/thug/DOM/AsyncPrefetcher.py
#!/usr/bin/env python # # AsyncPrefetcher.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from requests_futures.sessions import FuturesSession log = logging.getLogger("Thug") class AsyncPrefetcher: def __init__(self, window=None): self.session = FuturesSession() self.window = window self.responses = {} def build_http_headers(self, window): http_headers = { "Cache-Control": "no-cache", "Accept-Language": "en-US", "Accept": "*/*", "User-Agent": log.ThugOpts.useragent, } if window and window.url not in ("about:blank",): referer = ( window.url if window.url.startswith("http") else f"http://{window.url}" ) http_headers["Referer"] = referer return http_headers def _fetch(self, url, method): log.warning("[PREFETCHING] URL: %s", url) fetcher = getattr(self.session, method.lower()) self.responses[url] = fetcher( url, headers=self.build_http_headers(self.window), timeout=log.ThugOpts.connect_timeout, verify=log.ThugOpts.ssl_verify, stream=True, ) def fetch(self, url, method="GET"): if log.HTTPSession.no_fetch: return # pragma: no cover if method.lower() not in ( "get", "post", ): return # pragma: no cover _url = log.HTTPSession.normalize_url(self.window, url) if _url is None: return # pragma: no cover self._fetch(_url, method)
2,236
Python
.py
60
29.833333
87
0.63136
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,766
External.py
buffer_thug/thug/DOM/External.py
#!/usr/bin/env python # # External.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .JSClass import JSClass log = logging.getLogger("Thug") class External(JSClass): def __init__(self): self._providers = set() self._channels = set() self._favorites = set() self.__init_external_personality() def __init_external_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_external_personality_IE() return if log.ThugOpts.Personality.isChrome(): self.__init_external_personality_Chrome() def __init_external_personality_IE(self): self.frozen = self._frozen self.menuArguments = self._menuArguments self.AddDesktopComponent = self._AddDesktopComponent self.AddFavorite = self._AddFavorite self.AutoCompleteSaveForm = self._AutoCompleteSaveForm self.AutoScan = self._AutoScan self.bubbleEvent = self._bubbleEvent self.IsSubscribed = self._IsSubscribed self.NavigateAndFind = self._NavigateAndFind self.raiseEvent = self._raiseEvent self.ShowBrowserUI = self._ShowBrowserUI if log.ThugOpts.Personality.browserMajorVersion < 7: self.AddChannel = self._AddChannel if log.ThugOpts.Personality.browserMajorVersion >= 7: self.AddSearchProvider = self._AddSearchProvider self.IsSearchProviderInstalled = self._IsSearchProviderInstalled def __init_external_personality_Chrome(self): self.AddSearchProvider = self._AddSearchProvider @property def _frozen(self): return False @property def _menuArguments(self): return None def _AddChannel(self, URL): self._channels.add(URL) def _AddDesktopComponent( self, URL, type, left=None, top=None, width=None, height=None ): # pylint:disable=redefined-builtin pass def _AddFavorite(self, URL, title=None): self._favorites.add((URL, title)) def _AddSearchProvider(self, URL): self._providers.add(URL) def _AutoCompleteSaveForm(self, formElement): pass def _AutoScan(self, domainPart, defaultURL=None, target=None): # pylint:disable=unused-argument # This method does not work in Internet Explorer from version 7 # and raises an exception. if log.ThugOpts.Personality.browserMajorVersion >= 7: raise TypeError() def _bubbleEvent(self): pass def _IsSearchProviderInstalled(self, URL): return 1 if URL in self._providers else 0 def _IsSubscribed(self, URL): # pylint:disable=unused-argument return False def _NavigateAndFind(self, URL, textToFind, findInFrame): pass def _raiseEvent(self, eventName, eventObj): pass def _ShowBrowserUI(self, dialogBoxType, null=None): pass
3,511
Python
.py
86
34.127907
100
0.696087
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,767
LocalStorage.py
buffer_thug/thug/DOM/LocalStorage.py
#!/usr/bin/env python # # LocalStorage.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .Storage import Storage class LocalStorage(Storage): pass
752
Python
.py
20
36.25
70
0.784636
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,768
Chrome.py
buffer_thug/thug/DOM/Chrome.py
#!/usr/bin/env python # # Chrome.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass from .WebStore import WebStore class Chrome(JSClass): def __init__(self): self.webstore = WebStore() def __str__(self): return "[object Object]"
878
Python
.py
24
34.416667
70
0.754118
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,769
Screen.py
buffer_thug/thug/DOM/Screen.py
#!/usr/bin/env python # # Screen.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .JSClass import JSClass log = logging.getLogger("Thug") class Screen(JSClass): def __init__(self, width=800, height=600, depth=32): self._width = width self._height = height self._depth = depth self._left = 0 self._top = 0 self.__init_screen_personality() def __init_screen_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_screen_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_screen_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_screen_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_screen_personality_Safari() return def __init_screen_personality_IE(self): self.bufferDepth = property(self._get_bufferDepth, self._set_bufferDepth) self.deviceXDPI = self._deviceXDPI self.deviceYDPI = self._deviceYDPI self.logicalXDPI = self._logicalXDPI self.logicalYDPI = self._logicalYDPI self.fontSmoothingEnabled = self._fontSmoothingEnabled self.updateInterval = self._updateInterval if log.ThugOpts.Personality.browserMajorVersion >= 8: self.systemXDPI = self._systemXDPI self.systemYDPI = self._systemYDPI if log.ThugOpts.Personality.browserMajorVersion >= 9: self.pixelDepth = self._pixelDepth def __init_screen_personality_Firefox(self): self.availLeft = self._availLeft self.availTop = self._availTop self.left = self._left self.top = self._top self.pixelDepth = self._pixelDepth def __init_screen_personality_Chrome(self): self.availLeft = self._availLeft self.availTop = self._availTop self.pixelDepth = self._pixelDepth def __init_screen_personality_Safari(self): self.availLeft = self._availLeft self.availTop = self._availTop self.pixelDepth = self._pixelDepth @property def availHeight(self): """ The height of the screen (excluding the Windows Taskbar) """ return self._height @property def availWidth(self): """ The width of the screen (excluding the Windows Taskbar) """ return self._width @property def colorDepth(self): """ The bit depth of the color palette for displaying images/ The color resolution (in bits per pixel) of the screen """ return self._depth @property def height(self): """ The total height of the screen """ return self._height @property def _pixelDepth(self): """ The color resolution (in bits per pixel) of the screen """ return self._depth def _get_bufferDepth(self): return self._depth def _set_bufferDepth(self, value): try: self._depth = int(value) except ValueError: pass @property def width(self): """ The total width of the screen """ return self._width @property def _availLeft(self): """ The first available pixel available from the left side of the screen """ return self._left + 1 @property def _availTop(self): """ The first available pixel from the top of the screen available to the browser """ return self._top + 1 @property def _deviceXDPI(self): """ Returns the current number of dots per inch (DPI) of the document's viewport along the horizontal (x) axis. """ return 120 @property def _deviceYDPI(self): """ Returns the current number of dots per inch (DPI) of the document's viewport along the vertical (y) axis. """ return 120 @property def _logicalXDPI(self): """ Returns the number of dots per inch (DPI) of the document's viewport along the horizontal (x) axis at normal zoom level. """ return 96 @property def _logicalYDPI(self): """ Returns the number of dots per inch (DPI) of the document's viewport along the vertical (y) axis at normal zoom level. """ return 96 @property def _systemXDPI(self): """ Returns the number of dots per inch (DPI) of the display screen along the horizontal (x) axis at normal zoom level. """ return 120 @property def _systemYDPI(self): """ Returns the number of dots per inch (DPI) of the display screen along the vertical (y) axis at normal zoom level. """ return 120 @property def _fontSmoothingEnabled(self): """ Returns a Boolean value that indicates whether font smoothing is enabled. """ return False @property def _updateInterval(self): """ Specifies or returns the time interval (in milliseconds) between screen updates. """ return 0
5,954
Python
.py
182
25.038462
81
0.625763
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,770
CCInterpreter.py
buffer_thug/thug/DOM/CCInterpreter.py
#!/usr/bin/env python # # CCInterpreter.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging log = logging.getLogger("Thug") class CCInterpreter: """ Microsoft Internet Explorer Conditional Comments tiny interpreter """ def __init__(self): pass def run(self, script): script = script.replace("@cc_on!@", "*/!/*") if "/*@cc_on" in script: script = script.replace("/*@cc_on", "") script = script.replace( "@_jscript_version", str(log.ThugOpts.Personality.cc_on["_jscript_version"]), ) script = script.replace("/*@if", "if") script = script.replace("@if", "if") script = script.replace("@elif", "else if") script = script.replace("@else", "else") script = script.replace("/*@end", "") script = script.replace("@end", "") script = script.replace("@_alpha", "false") script = script.replace("@_mc680x0", "false") script = script.replace("@_win16", "false") script = script.replace("@_win64", "false") script = script.replace("@_x86", "true") if log.ThugOpts.Personality.platform in ("Win32",): script = script.replace("@_win32", "true") script = script.replace("@_mac", "false") if log.ThugOpts.Personality.platform in ("MacIntel",): # pragma: no cover script = script.replace("@_win32", "false") script = script.replace("@_mac", "true") script = script.replace("@*/", "") script = script.replace("/*@", "") return script
2,298
Python
.py
53
35.283019
86
0.602059
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,771
Plugins.py
buffer_thug/thug/DOM/Plugins.py
#!/usr/bin/env python # # Plugins.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA class Plugins(list): def __init__(self): list.__init__(self) @property def length(self): return len(self) def __getattr__(self, key): return self.namedItem(key) def __getitem__(self, key): try: key = int(key) return self.item(key) except ValueError: return self.namedItem(key) def item(self, index): if index >= self.length: return None return list.__getitem__(self, index) def namedItem(self, name): index = 0 while index < self.length: p = self.item(index) if p["name"] == name: return p index += 1 return None def refresh(self, reloadDocuments=False): pass
1,469
Python
.py
45
26.488889
70
0.645892
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,772
Navigator.py
buffer_thug/thug/DOM/Navigator.py
#!/usr/bin/env python # # Navigator.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import hashlib import logging import ssdeep from .JSClass import JSClass from .MimeTypes import MimeTypes from .Plugins import Plugins from .HTTPSessionException import AboutBlank from .HTTPSessionException import FetchForbidden from .HTTPSessionException import InvalidUrl from .HTTPSessionException import ThresholdExpired log = logging.getLogger("Thug") class Navigator(JSClass): def __init__(self, personality, window=None): self.personality = log.ThugOpts.Personality[personality] self._plugins = Plugins() # An array of the plugins installed in the browser self._mimeTypes = MimeTypes() self._window = window for p in self._mimeTypes.values(): self._plugins.append(p["enabledPlugin"]) self.__init_navigator_personality() self.filecount = 0 def __init_navigator_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_navigator_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_navigator_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_navigator_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_navigator_personality_Safari() return def __init_navigator_personality_IE(self): from .UserProfile import UserProfile self.mimeTypes = self._mimeTypes self.plugins = self._plugins self.taintEnabled = self._taintEnabled self.appMinorVersion = self._appMinorVersion self.cpuClass = self._cpuClass self.browserLanguage = self._browserLanguage self.systemLanguage = self._systemLanguage self.userLanguage = self._userLanguage if log.ThugOpts.Personality.browserMajorVersion < 9: self.userProfile = UserProfile() def __init_navigator_personality_Firefox(self): self.mimeTypes = self._mimeTypes self.plugins = self._plugins self.taintEnabled = self._taintEnabled self.oscpu = self._oscpu self.buildID = self._buildID self.product = self._product self.productSub = self._productSub self.vendor = self._vendor self.vendorSub = self._vendorSub self.language = self._language self.preference = self._preference if log.ThugOpts.Personality.browserMajorVersion < 35: self.mozIsLocallyAvailable = self._mozIsLocallyAvailable if log.ThugOpts.Personality.browserMajorVersion < 62: self.registerContentHandler = self._registerContentHandler self.registerProtocolHandler = self._registerProtocolHandler def __init_navigator_personality_Chrome(self): self.mimeTypes = self._mimeTypes self.plugins = self._plugins self.taintEnabled = self._taintEnabled self.product = self._product self.productSub = self._productSub self.vendor = self._vendor self.vendorSub = self._vendorSub self.language = self._language def __init_navigator_personality_Safari(self): self.mimeTypes = self._mimeTypes self.plugins = self._plugins self.taintEnabled = self._taintEnabled self.product = self._product self.productSub = self._productSub self.vendor = self._vendor self.vendorSub = self._vendorSub self.language = self._language @property def window(self): return self._window @property def appCodeName(self): """ The internal "code" name of the current browser """ return self.personality["appCodeName"] @property def appName(self): """ The official name of the browser """ return self.personality["appName"] @property def appVersion(self): """ The version of the browser as a string """ return self.personality["appVersion"] @property def userAgent(self): """ The user agent string for the current browser """ return self.personality["userAgent"] @property def _buildID(self): """ The build identifier of the browser (e.g. "2006090803") """ return self.personality["buildID"] @property def cookieEnabled(self): """ A boolean indicating whether cookies are enabled """ return True @property def _language(self): """ A string representing the language version of the browser """ return "en" @property def onLine(self): """ A boolean indicating whether the browser is working online """ return True @property def _oscpu(self): """ A string that represents the current operating system """ return self.personality["oscpu"] @property def platform(self): """ A string representing the platform of the browser """ return self.personality["platform"] @property def _product(self): """ The product name of the current browser (e.g. "Gecko") """ return self.personality["product"] @property def _productSub(self): """ The build number of the current browser (e.g. "20060909") """ return self.personality["productSub"] @property def securityPolicy(self): """ An empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy". """ return "" @property def _vendor(self): """ The vendor name of the current browser (e.g. "Netscape6") """ return self.personality["vendor"] @property def _vendorSub(self): """ The vendor name of the current browser (e.g. "Netscape6") """ return self.personality["vendorSub"] @property def _appMinorVersion(self): return self.personality["appMinorVersion"] @property def _browserLanguage(self): return "en" @property def _cpuClass(self): return "x86" @property def _systemLanguage(self): return "en" @property def _userLanguage(self): return "en" # Indicates whether the host browser is Java-enabled or not. def javaEnabled(self, *arg): # pylint:disable=unused-argument return True # Lets code check to see if the document at a given URI is # available without using the network. def _mozIsLocallyAvailable(self, uri, ifOffline): # pylint:disable=unused-argument return False # Sets a user preference. # self method is only available to privileged code, and you # should use XPCOM Preferences API instead. def _preference(self, name, value=None): pass # Allows web sites to register themselves as a possible handler # for a given MIME type. def _registerContentHandler(self, mimeType, uri, title): pass # New in Firefox 3 # Allows web sites to register themselves as a possible handler # for a given protocol. def _registerProtocolHandler(self, protocol, url, title): pass # Obsolete # JavaScript taint/untaint functions removed in JavaScript 1.2[1] def _taintEnabled(self): return True def fetch( self, url, method="GET", headers=None, body=None, redirect_type=None, params=None, snippet=None, disable_download_prevention=False, ): if url and not isinstance(url, str): # pragma: no cover url = str(url) log.URLClassifier.classify(url) # The command-line option -x (--local-nofetch) prevents remote # content fetching so raise an exception and exit the method. if log.HTTPSession.no_fetch: raise FetchForbidden # Do not attempt to fetch content if the URL is "about:blank". if log.HTTPSession.about_blank(url): raise AboutBlank # URL normalization and fixing (if broken and the option is # enabled). url = log.HTTPSession.normalize_url(self._window, url) if url is None: raise InvalidUrl last_url = getattr(log, "last_url", None) if last_url is None: last_url = self._window.url # Redirection loops detection and prevention if redirect_type: item = ( url, last_url, ) if not log.ThugLogging.redirections.get(item, 0): log.ThugLogging.redirections[item] = 0 log.ThugLogging.redirections[item] += 1 if log.ThugLogging.redirections[item] > 10: return None # pragma: no cover if log.HTTPSession.check_redirection_loop_url_params( url ): # pragma: no cover log.ThugLogging.add_behavior_warn( f"[Skipping {redirect_type} redirection] {last_url} -> {url}", snippet=snippet, ) return None if redirect_type in ( "frame", "iframe", "http-redirect", "meta", ): if log.HTTPSession.check_equal_urls(url, last_url): # pragma: no cover log.ThugLogging.add_behavior_warn( f"[Skipping {redirect_type} redirection] {last_url} -> {url}", snippet=snippet, ) return None if redirect_type: log.ThugLogging.add_behavior_warn( f"[{redirect_type} redirection] {last_url} -> {url}", snippet=snippet ) log.ThugLogging.log_connection(last_url, url, redirect_type) else: log.ThugLogging.log_connection(last_url, url, "unknown") # The command-line option -t (--threshold) defines the maximum # number of pages to fetch. If the threshold is reached avoid # fetching the contents. if log.HTTPSession.threshold_expired(url): raise ThresholdExpired if headers is None: headers = {} response = log.HTTPSession.fetch( url, method, self._window, self.userAgent, headers, body ) if response is None: return None referer = response.request.headers.get("referer", "None") log.ThugLogging.add_behavior_warn( f"[HTTP] URL: {url} (Status: {response.status_code}, Referer: {referer})", snippet=snippet, ) if redirect_type in ( "window open", "http-redirect", "meta", ): self._window.url = log.HTTPSession.normalize_url(self._window, response.url) if redirect_type in ( None, "window open", "iframe", "http-redirect", "meta", ): log.last_url = response.url log.last_url_fetched = response.url _url = log.ThugLogging.log_redirect(response, self._window) if _url: url = _url ctype = response.headers.get("content-type", "unknown") if not disable_download_prevention and log.HTTPSession.is_download_prevented( mimetype=ctype ): response.close() return None mime_base = os.path.join(log.ThugLogging.baseDir, ctype) md5 = hashlib.md5() # nosec md5.update(response.content) sha256 = hashlib.sha256() sha256.update(response.content) ssdeep_hash = ssdeep.hash(response.content) mtype = log.Magic.get_mime(response.content) data = { "content": response.content, "status": response.status_code, "md5": md5.hexdigest(), "sha256": sha256.hexdigest(), "ssdeep": ssdeep_hash, "fsize": len(response.content), "ctype": ctype, "mtype": mtype, } log.ThugLogging.add_behavior_warn( f"[HTTP] URL: {response.url} (Content-type: {ctype}, MD5: {data['md5']})", snippet=snippet, ) log.ThugLogging.log_location(url, data) log.ThugLogging.store_content(mime_base, data["md5"], response.content) log.ThugLogging.log_file(response.content, response.url, params) log.ThugLogging.Screenshot.run(self._window, url, response, ctype) handler = log.MIMEHandler.get_handler( ctype if ctype not in ("unknown",) else mtype ) if handler: handler(response.url, response.content) response.thug_mimehandler_hit = True else: if log.ThugOpts.features_logging: log.ThugLogging.Features.add_characters_count(len(response.text)) log.ThugLogging.Features.add_whitespaces_count( len([a for a in response.text if a.isspace()]) ) return response
13,892
Python
.py
378
27.716931
96
0.617807
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,773
Alexa.py
buffer_thug/thug/DOM/Alexa.py
#!/usr/bin/env python # # Alexa.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import random AlexaTopSites = [ "http://www.google.com", "http://www.youtube.com", "http://www.facebook.com", "http://www.baidu.com", "http://www.wikipedia.org", "http://www.yahoo.com", "http://www.reddit.com", "http://www.taobao.com", "http://www.amazon.com", "http://www.tmall.com", "http://www.sohu.com", "http://www.twitter.com", "http://www.live.com", "http://www.instagram.com", "http://www.jd.com", "http://www.linkedin.com", "http://www.netflix.com", "http://www.t.co", "http://www.imgur.com", "http://www.ebay.com", "http://www.pornhub.com", "http://www.detail.tmall.com", "http://www.wordpress.com", "http://www.msn.com", "http://www.bing.com", "http://www.tumblr.com", "http://www.microsoft.com", "http://www.stackoverflow.com", "http://www.twitch.tv", "http://www.imdb.com", "http://www.blogspot.com", "http://www.office.com", "http://www.github.com", "http://www.microsoftonline.com", "http://www.apple.com", "http://www.popads.net", "http://www.diply.com", "http://www.pinterest.com", "http://www.csdn.net", "http://www.paypal.com", "http://www.adobe.com", "http://www.whatsapp.com", "http://www.xvideos.com", "http://www.xhamster.com", "http://www.pixnet.net", "http://www.login.tmall.com", "http://www.soso.com", "http://www.coccoc.com", "http://www.txxx.com", "http://www.dropbox.com", "http://www.googleusercontent.com", "http://www.bbc.co.uk", ] random.shuffle(AlexaTopSites) Alexa = AlexaTopSites[: random.randint(5, 9)]
2,327
Python
.py
74
27.594595
70
0.647556
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,774
JScriptEncode.py
buffer_thug/thug/DOM/JScriptEncode.py
#!/usr/bin/env python # This code is derived from the awesome VBE Decoder authored by Didier Stevens # and available at https://github.com/DidierStevens/DidierStevensSuite import re DDECODE = {} DDECODE[9] = "\x57\x6e\x7b" DDECODE[10] = "\x4a\x4c\x41" DDECODE[11] = "\x0b\x0b\x0b" DDECODE[12] = "\x0c\x0c\x0c" DDECODE[13] = "\x4a\x4c\x41" DDECODE[14] = "\x0e\x0e\x0e" DDECODE[15] = "\x0f\x0f\x0f" DDECODE[16] = "\x10\x10\x10" DDECODE[17] = "\x11\x11\x11" DDECODE[18] = "\x12\x12\x12" DDECODE[19] = "\x13\x13\x13" DDECODE[20] = "\x14\x14\x14" DDECODE[21] = "\x15\x15\x15" DDECODE[22] = "\x16\x16\x16" DDECODE[23] = "\x17\x17\x17" DDECODE[24] = "\x18\x18\x18" DDECODE[25] = "\x19\x19\x19" DDECODE[26] = "\x1a\x1a\x1a" DDECODE[27] = "\x1b\x1b\x1b" DDECODE[28] = "\x1c\x1c\x1c" DDECODE[29] = "\x1d\x1d\x1d" DDECODE[30] = "\x1e\x1e\x1e" DDECODE[31] = "\x1f\x1f\x1f" DDECODE[32] = "\x2e\x2d\x32" DDECODE[33] = "\x47\x75\x30" DDECODE[34] = "\x7a\x52\x21" DDECODE[35] = "\x56\x60\x29" DDECODE[36] = "\x42\x71\x5b" DDECODE[37] = "\x6a\x5e\x38" DDECODE[38] = "\x2f\x49\x33" DDECODE[39] = "\x26\x5c\x3d" DDECODE[40] = "\x49\x62\x58" DDECODE[41] = "\x41\x7d\x3a" DDECODE[42] = "\x34\x29\x35" DDECODE[43] = "\x32\x36\x65" DDECODE[44] = "\x5b\x20\x39" DDECODE[45] = "\x76\x7c\x5c" DDECODE[46] = "\x72\x7a\x56" DDECODE[47] = "\x43\x7f\x73" DDECODE[48] = "\x38\x6b\x66" DDECODE[49] = "\x39\x63\x4e" DDECODE[50] = "\x70\x33\x45" DDECODE[51] = "\x45\x2b\x6b" DDECODE[52] = "\x68\x68\x62" DDECODE[53] = "\x71\x51\x59" DDECODE[54] = "\x4f\x66\x78" DDECODE[55] = "\x09\x76\x5e" DDECODE[56] = "\x62\x31\x7d" DDECODE[57] = "\x44\x64\x4a" DDECODE[58] = "\x23\x54\x6d" DDECODE[59] = "\x75\x43\x71" DDECODE[60] = "\x4a\x4c\x41" DDECODE[61] = "\x7e\x3a\x60" DDECODE[62] = "\x4a\x4c\x41" DDECODE[63] = "\x5e\x7e\x53" DDECODE[64] = "\x40\x4c\x40" DDECODE[65] = "\x77\x45\x42" DDECODE[66] = "\x4a\x2c\x27" DDECODE[67] = "\x61\x2a\x48" DDECODE[68] = "\x5d\x74\x72" DDECODE[69] = "\x22\x27\x75" DDECODE[70] = "\x4b\x37\x31" DDECODE[71] = "\x6f\x44\x37" DDECODE[72] = "\x4e\x79\x4d" DDECODE[73] = "\x3b\x59\x52" DDECODE[74] = "\x4c\x2f\x22" DDECODE[75] = "\x50\x6f\x54" DDECODE[76] = "\x67\x26\x6a" DDECODE[77] = "\x2a\x72\x47" DDECODE[78] = "\x7d\x6a\x64" DDECODE[79] = "\x74\x39\x2d" DDECODE[80] = "\x54\x7b\x20" DDECODE[81] = "\x2b\x3f\x7f" DDECODE[82] = "\x2d\x38\x2e" DDECODE[83] = "\x2c\x77\x4c" DDECODE[84] = "\x30\x67\x5d" DDECODE[85] = "\x6e\x53\x7e" DDECODE[86] = "\x6b\x47\x6c" DDECODE[87] = "\x66\x34\x6f" DDECODE[88] = "\x35\x78\x79" DDECODE[89] = "\x25\x5d\x74" DDECODE[90] = "\x21\x30\x43" DDECODE[91] = "\x64\x23\x26" DDECODE[92] = "\x4d\x5a\x76" DDECODE[93] = "\x52\x5b\x25" DDECODE[94] = "\x63\x6c\x24" DDECODE[95] = "\x3f\x48\x2b" DDECODE[96] = "\x7b\x55\x28" DDECODE[97] = "\x78\x70\x23" DDECODE[98] = "\x29\x69\x41" DDECODE[99] = "\x28\x2e\x34" DDECODE[100] = "\x73\x4c\x09" DDECODE[101] = "\x59\x21\x2a" DDECODE[102] = "\x33\x24\x44" DDECODE[103] = "\x7f\x4e\x3f" DDECODE[104] = "\x6d\x50\x77" DDECODE[105] = "\x55\x09\x3b" DDECODE[106] = "\x53\x56\x55" DDECODE[107] = "\x7c\x73\x69" DDECODE[108] = "\x3a\x35\x61" DDECODE[109] = "\x5f\x61\x63" DDECODE[110] = "\x65\x4b\x50" DDECODE[111] = "\x46\x58\x67" DDECODE[112] = "\x58\x3b\x51" DDECODE[113] = "\x31\x57\x49" DDECODE[114] = "\x69\x22\x4f" DDECODE[115] = "\x6c\x6d\x46" DDECODE[116] = "\x5a\x4d\x68" DDECODE[117] = "\x48\x25\x7c" DDECODE[118] = "\x27\x28\x36" DDECODE[119] = "\x5c\x46\x70" DDECODE[120] = "\x3d\x4a\x6e" DDECODE[121] = "\x24\x32\x7a" DDECODE[122] = "\x79\x41\x2f" DDECODE[123] = "\x37\x3d\x5f" DDECODE[124] = "\x60\x5f\x4b" DDECODE[125] = "\x51\x4f\x5a" DDECODE[126] = "\x20\x42\x2c" DDECODE[127] = "\x36\x65\x57" DCOMBINATION = {} DCOMBINATION[0] = 0 DCOMBINATION[1] = 1 DCOMBINATION[2] = 2 DCOMBINATION[3] = 0 DCOMBINATION[4] = 1 DCOMBINATION[5] = 2 DCOMBINATION[6] = 1 DCOMBINATION[7] = 2 DCOMBINATION[8] = 2 DCOMBINATION[9] = 1 DCOMBINATION[10] = 2 DCOMBINATION[11] = 1 DCOMBINATION[12] = 0 DCOMBINATION[13] = 2 DCOMBINATION[14] = 1 DCOMBINATION[15] = 2 DCOMBINATION[16] = 0 DCOMBINATION[17] = 2 DCOMBINATION[18] = 1 DCOMBINATION[19] = 2 DCOMBINATION[20] = 0 DCOMBINATION[21] = 0 DCOMBINATION[22] = 1 DCOMBINATION[23] = 2 DCOMBINATION[24] = 2 DCOMBINATION[25] = 1 DCOMBINATION[26] = 0 DCOMBINATION[27] = 2 DCOMBINATION[28] = 1 DCOMBINATION[29] = 2 DCOMBINATION[30] = 2 DCOMBINATION[31] = 1 DCOMBINATION[32] = 0 DCOMBINATION[33] = 0 DCOMBINATION[34] = 2 DCOMBINATION[35] = 1 DCOMBINATION[36] = 2 DCOMBINATION[37] = 1 DCOMBINATION[38] = 2 DCOMBINATION[39] = 0 DCOMBINATION[40] = 2 DCOMBINATION[41] = 0 DCOMBINATION[42] = 0 DCOMBINATION[43] = 1 DCOMBINATION[44] = 2 DCOMBINATION[45] = 0 DCOMBINATION[46] = 2 DCOMBINATION[47] = 1 DCOMBINATION[48] = 0 DCOMBINATION[49] = 2 DCOMBINATION[50] = 1 DCOMBINATION[51] = 2 DCOMBINATION[52] = 0 DCOMBINATION[53] = 0 DCOMBINATION[54] = 1 DCOMBINATION[55] = 2 DCOMBINATION[56] = 2 DCOMBINATION[57] = 0 DCOMBINATION[58] = 0 DCOMBINATION[59] = 1 DCOMBINATION[60] = 2 DCOMBINATION[61] = 0 DCOMBINATION[62] = 2 DCOMBINATION[63] = 1 class JScriptEncode: subs = (("@&", chr(10)), ("@#", chr(13)), ("@*", ">"), ("@!", "<"), ("@$", "@")) def decode(self, data): result = "" index = -1 match = re.search(r"#@~\^......==(.+)......==\^#~@", data) if not match: return result script = match.groups()[0] for p, v in self.subs: script = script.replace(p, v) for char in script: byte = ord(char) if byte < 128: index = index + 1 if ( (byte == 9 or byte > 31 and byte < 128) and byte != 60 and byte != 62 and byte != 64 ): # pylint:disable=too-many-boolean-expressions,chained-comparison char = [c for c in DDECODE[byte]][DCOMBINATION[index % 64]] # pylint:disable=unnecessary-comprehension result += char return result
5,971
Python
.py
213
25.774648
119
0.642982
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,775
MimeType.py
buffer_thug/thug/DOM/MimeType.py
#!/usr/bin/env python # # MimeType.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class MimeType(JSClass): def __init__(self, init=None): self._mimetype = {} if init is None: return for k, v in init.items(): self._mimetype[k] = v def __setitem__(self, key, value): self._mimetype[key] = value def __getitem__(self, name): return self._mimetype.get(name, None) def __delitem__(self, name): if name not in self._mimetype: return del self._mimetype[name]
1,195
Python
.py
33
31.636364
70
0.689236
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,776
w3c_bindings.py
buffer_thug/thug/DOM/w3c_bindings.py
#!/usr/bin/env python # # w3c_bindings.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from thug.DOM.W3C import Core from thug.DOM.W3C import HTML from thug.DOM.W3C import Events from thug.DOM.W3C.Style.CSS.CSSStyleDeclaration import CSSStyleDeclaration w3c_bindings = { "Attr": Core.Attr, "CDATASection": Core.CDATASection, "CharacterData": Core.CharacterData, "Comment": Core.Comment, "DOMException": Core.DOMException, # 'DOMImplementation' : Core.DOMImplementation, "Document": Core.Document, "DocumentFragment": Core.DocumentFragment, "DocumentType": Core.DocumentType, "Element": Core.Element, "NamedNodeMap": Core.NamedNodeMap, "Node": Core.Node, "NodeList": Core.NodeList, "ProcessingInstruction": Core.ProcessingInstruction, "Text": Core.Text, "AudioTrackList": HTML.AudioTrackList, "HTMLAllCollection": HTML.HTMLAllCollection, "HTMLAnchorElement": HTML.HTMLAnchorElement, "HTMLAppletElement": HTML.HTMLAppletElement, "HTMLBRElement": HTML.HTMLBRElement, "HTMLBaseElement": HTML.HTMLBaseElement, "HTMLBaseFontElement": HTML.HTMLBaseFontElement, "HTMLBodyElement": HTML.HTMLBodyElement, "HTMLButtonElement": HTML.HTMLButtonElement, "HTMLCollection": HTML.HTMLCollection, "HTMLDListElement": HTML.HTMLDListElement, "HTMLDirectoryElement": HTML.HTMLDirectoryElement, "HTMLDivElement": HTML.HTMLDivElement, "HTMLDocument": HTML.HTMLDocument, "HTMLDocumentCompatibleInfo": HTML.HTMLDocumentCompatibleInfo, "HTMLDocumentCompatibleInfoCollection": HTML.HTMLDocumentCompatibleInfoCollection, "HTMLElement": HTML.HTMLElement, "HTMLFieldSetElement": HTML.HTMLFieldSetElement, "HTMLFontElement": HTML.HTMLFontElement, "HTMLFormElement": HTML.HTMLFormElement, "HTMLFrameElement": HTML.HTMLFrameElement, "HTMLFrameSetElement": HTML.HTMLFrameSetElement, "HTMLHRElement": HTML.HTMLHRElement, "HTMLHeadElement": HTML.HTMLHeadElement, "HTMLHeadingElement": HTML.HTMLHeadingElement, "HTMLHtmlElement": HTML.HTMLHtmlElement, "HTMLIFrameElement": HTML.HTMLIFrameElement, "HTMLImageElement": HTML.HTMLImageElement, "HTMLInputElement": HTML.HTMLInputElement, "HTMLIsIndexElement": HTML.HTMLIsIndexElement, "HTMLLIElement": HTML.HTMLLIElement, "HTMLLabelElement": HTML.HTMLLabelElement, "HTMLLegendElement": HTML.HTMLLegendElement, "HTMLLinkElement": HTML.HTMLLinkElement, "HTMLMediaElement": HTML.HTMLMediaElement, "HTMLMenuElement": HTML.HTMLMenuElement, "HTMLMetaElement": HTML.HTMLMetaElement, "HTMLModElement": HTML.HTMLModElement, "HTMLOListElement": HTML.HTMLOListElement, "HTMLObjectElement": HTML.HTMLObjectElement, "HTMLOptGroupElement": HTML.HTMLOptGroupElement, "HTMLOptionElement": HTML.HTMLOptionElement, "HTMLOptionsCollection": HTML.HTMLOptionsCollection, "HTMLParagraphElement": HTML.HTMLParagraphElement, "HTMLParamElement": HTML.HTMLParamElement, "HTMLPreElement": HTML.HTMLPreElement, "HTMLQuoteElement": HTML.HTMLQuoteElement, "HTMLScriptElement": HTML.HTMLScriptElement, "HTMLSelectElement": HTML.HTMLSelectElement, "HTMLSpanElement": HTML.HTMLSpanElement, "HTMLStyleElement": HTML.HTMLStyleElement, "HTMLTableCaptionElement": HTML.HTMLTableCaptionElement, "HTMLTableCellElement": HTML.HTMLTableCellElement, "HTMLTableColElement": HTML.HTMLTableColElement, "HTMLTableElement": HTML.HTMLTableElement, "HTMLTableRowElement": HTML.HTMLTableRowElement, "HTMLTableSectionElement": HTML.HTMLTableSectionElement, "HTMLTextAreaElement": HTML.HTMLTextAreaElement, "HTMLTitleElement": HTML.HTMLTitleElement, "HTMLUListElement": HTML.HTMLUListElement, "TextTrackList": HTML.TextTrackList, "TimeRanges": HTML.TimeRanges, "Event": Events.Event, "EventTarget": Events.EventTarget, "MessageEvent": Events.MessageEvent, "MouseEvent": Events.MouseEvent, "MutationEvent": Events.MutationEvent, "StorageEvent": Events.StorageEvent, "UIEvent": Events.UIEvent, "CSSStyleDeclaration": CSSStyleDeclaration, }
4,750
Python
.py
108
39.796296
86
0.774903
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,777
MIMEHandler.py
buffer_thug/thug/DOM/MIMEHandler.py
#!/usr/bin/env python # # MIMEHandler.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import os import io import types import operator import json import logging import zipfile import tempfile import bs4 import rarfile OCR_ENABLED = True try: from PIL import Image import pytesseract except ImportError: # pragma: no cover OCR_ENABLED = False log = logging.getLogger("Thug") MIMEHANDLER_PYHOOKS_NONE = 0 MIMEHANDLER_PYHOOKS_REQUIRED = 1 MIMEHANDLER_PYHOOKS_DONE = 2 class MIMEHandler(dict): """ MIMEHandler class is meant to allow registering MIME handlers the same way a real browser would do. The default handling for almost all Content-Types is to not further processing the downloaded content and this can be done by returning True from the Content-Type handler. The method `passthrough' is the default handler associated to almost all Content-Types with the few exceptions defined in the method `register_empty_handlers'. Two ways actually exist for further processing a downloaded content. The first one is returning False from the the Content-Type handler. The second one is having a None Content-Type handler which turns to be quite useful when an unknown Content-Type is served. In such case the __missing__ method will return None (thus enabling further content processing) and log the unknown Content-Type for convenience. This design is quite flexible because i.e. you can decide to instantiate your own PDF analysis system really quickly by simply defining a new application/pdf Content-Type handler. """ MB = 1024 * 1024 MIN_ZIP_FILE_SIZE = 32 MAX_ZIP_FILE_SIZE = 32 * MB MIN_RAR_FILE_SIZE = 32 MAX_RAR_FILE_SIZE = 32 * MB MIN_IMG_FILE_SIZE = 32 mimetypes = ( "application/atom+xml", "application/download", "application/envoy", "application/exe", "application/fractals", "application/futuresplash", "application/internet-property-stream", "application/java-archive", "application/mac-binhex40", "application/msword", "application/oda", "application/olescript", "application/pdf", "application/pics-rules", "application/pkcs10", "application/pkix-crl", "application/postscript", "application/rss+xml", "application/rtf", "application/set-payment-initiation", "application/set-registration-initiation", "application/vnd.android.package-archive", "application/vnd.ms-excel", "application/vnd.ms-outlook", "application/vnd.ms-pkicertstore", "application/vnd.ms-pkiseccat", "application/vnd.ms-pkistl", "application/vnd.ms-powerpoint", "application/vnd.ms-project", "application/vnd.ms-works", "application/winhlp", "application/x-bcpio", "application/x-bzip2", "application/x-cdf", "application/x-chrome-extension", "application/x-compress", "application/x-compressed", "application/x-cpio", "application/x-csh", "application/x-director", "application/x-dosexec", "application/x-dvi", "application/x-empty", "application/x-executable", "application/x-gtar", "application/x-gzip", "application/x-hdf", "application/x-internet-signup", "application/x-iphone", "application/x-latex", "application/x-msaccess", "application/x-mscardfile", "application/x-msclip", "application/x-msdos-program", "application/x-msdownload", "application/x-msmediaview", "application/x-msmetafile", "application/x-msmoney", "application/x-mspublisher", "application/x-msschedule", "application/x-msterminal", "application/x-mswrite", "application/x-netcdf", "application/x-perfmon", "application/x-pkcs12", "application/x-pkcs7-certificates", "application/x-pkcs7-certreqresp", "application/x-pkcs7-mime", "application/x-pkcs7-signature", "application/x-sh", "application/x-shar", "application/x-shockwave-flash", "application/x-silverlight-2", "application/x-stuffit", "application/x-sv4cpio", "application/x-sv4crc", "application/x-tar", "application/x-tcl", "application/x-tex", "application/x-texinfo", "application/x-troff", "application/x-troff-man", "application/x-troff-me", "application/x-troff-ms", "application/x-ustar", "application/x-wais-source", "application/x-x509-ca-cert", "application/x-xpinstall", "application/x-zip-compressed", "application/ynd.ms-pkipko", "audio/basic", "audio/mid", "audio/mpeg", "audio/x-aiff", "audio/x-mpegurl", "audio/x-ms-wma", "audio/x-pn-realaudio", "audio/x-wav", "image/bmpimage/x-bmp", "image/cis-cod", "image/ief", "image/pipeg", "image/svg+xml", "image/x-cmu-raster", "image/x-cmx", "image/x-icon", "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-rgb", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump", "message/rfc822", "text/h323", "text/iuls", "text/richtext", "text/scriptlet", "text/tab-separated-values", "text/vnd.wap.wml", "text/webviewhtml", "text/xml", "text/x-component", "text/x-setext", "text/x-vcard", "video/mp4", "video/mpeg", "video/quicktime", "video/x-la-asf", "video/x-ms-asf", "video/x-msvideo", "video/x-sgi-movie", "x-world/x-vrml", ) def __missing__(self, key): _key = key.split(";")[0].strip() if _key in self: # pragma: no cover return self[_key] log.warning("[MIMEHandler] Unknown MIME Type: %s", key) return self.passthrough def __init__(self): super().__init__() self.mimehandler_pyhooks = MIMEHANDLER_PYHOOKS_NONE for mimetype in self.mimetypes: self[mimetype] = self.passthrough self.handlers = [] self.register_empty_handlers() self.register_fallback_handlers() self.register_zip_handlers() self.register_rar_handlers() self.register_java_jnlp_handlers() self.register_json_handlers() self.register_image_handlers() def init_pyhooks(self): self.mimehandler_pyhooks = MIMEHANDLER_PYHOOKS_DONE hooks = log.PyHooks.get("MIMEHandler", None) if hooks is None: return get_method_function = operator.attrgetter("__func__") get_method_self = operator.attrgetter("__self__") for label, hook in hooks.items(): name = f"{label}_hook" _hook = get_method_function(hook) if get_method_self(hook) else hook method = types.MethodType(_hook, MIMEHandler) setattr(self, name, method) hook = getattr(self, "handle_image_hook", None) self.image_hook_enabled = hook is not None def register_empty_handlers(self): self["application/hta"] = None self["application/javascript"] = None self["application/x-javascript"] = None self["text/css"] = None self["text/html"] = None self["text/javascript"] = None def register_fallback_handlers(self): self["text/plain"] = self.handle_fallback self["application/octet-stream"] = self.handle_fallback def register_handler(self, mimetype, handler): self[mimetype] = handler self.handlers.append(handler) def register_zip_handlers(self): self.register_handler("application/zip", self.handle_zip) def register_rar_handlers(self): self.register_handler("application/rar", self.handle_rar) self.register_handler("application/x-rar-compressed", self.handle_rar) def register_java_jnlp_handlers(self): self["application/x-java-jnlp-file"] = self.handle_java_jnlp def register_json_handlers(self): self["application/json"] = self.handle_json def register_image_handlers(self): self.image_ocr_enabled = OCR_ENABLED self.image_hook_enabled = False self.mimehandler_pyhooks = MIMEHANDLER_PYHOOKS_REQUIRED self["image/bmp"] = self.handle_image self["image/gif"] = self.handle_image self["image/jpeg"] = self.handle_image self["image/png"] = self.handle_image self["image/svg+xml"] = self.handle_svg_xml self["image/tiff"] = self.handle_image def handle_fallback(self, url, content): for handler in self.handlers: try: if handler(url, content): return True except Exception: # pragma: no cover,pylint:disable=broad-except pass return False def handle_image(self, url, content): if not log.ThugOpts.image_processing: return False # pragma: no cover if not self.image_ocr_enabled and not self.image_hook_enabled: return False # pragma: no cover if len(content) < self.MIN_IMG_FILE_SIZE: return False # pragma: no cover if self.image_ocr_enabled: self.perform_ocr_analysis(url, content) if self.image_hook_enabled: hook = getattr(self, "handle_image_hook") hook( ( url, content, ) ) return True def do_perform_ocr_analysis(self, url, img): try: ocr_result = pytesseract.image_to_string(img) if ocr_result: log.ThugLogging.log_image_ocr(url, ocr_result) log.ImageClassifier.classify(url, ocr_result) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[OCR] Error: %s", str(e)) return False return True def perform_ocr_analysis(self, url, content): try: fp = io.BytesIO(content) img = Image.open(fp) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[OCR] Error: %s", str(e)) return if not self.do_perform_ocr_analysis(url, img): self.do_perform_ocr_analysis(url, img.convert()) # pragma: no cover def handle_zip(self, url, content): if isinstance(content, list): content = bytearray(content) if len(content) < self.MIN_ZIP_FILE_SIZE: # pragma: no cover return False if len(content) > self.MAX_ZIP_FILE_SIZE: # pragma: no cover return False fp = io.BytesIO(content) if not zipfile.is_zipfile(fp): log.warning("[MIMEHANDLER (ZIP)][ERROR] Invalid ZIP file") return False try: zipdata = zipfile.ZipFile(fp) # pylint: disable=consider-using-with except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (ZIP)][ERROR] %s", str(e)) return False log.ThugLogging.log_file(content, url, sampletype="ZIP") for filename in zipdata.namelist(): sample = None try: data = zipdata.read(filename) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (ZIP)][ERROR] %s", str(e)) continue if not data: # pragma: no cover continue if filename.lower().endswith(".js"): window = getattr(self, "window", None) if window: try: with window.context as ctxt: ctxt.eval(data) except ( Exception ) as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (ZIP)][ERROR] %s", str(e)) sample = log.ThugLogging.log_file(data, url, sampletype="JS") if sample is None: # pragma: no cover sample = log.ThugLogging.log_file(data, url) if sample is None: # pragma: no cover continue try: md5 = sample["md5"] except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (ZIP)][ERROR] %s", str(e)) continue unzipped = os.path.join(log.ThugLogging.baseDir, "unzipped") log.ThugLogging.store_content(unzipped, md5, data) return True def handle_rar(self, url, content): if len(content) < self.MIN_RAR_FILE_SIZE: # pragma: no cover return False if len(content) > self.MAX_RAR_FILE_SIZE: # pragma: no cover return False _, rfile = tempfile.mkstemp() with open(rfile, "wb") as fd: fd.write(content) try: rardata = rarfile.RarFile(rfile) except Exception as e: # pylint:disable=broad-except log.warning("[MIMEHANDLER (RAR)][ERROR] %s", str(e)) os.remove(rfile) return False log.ThugLogging.log_file(content, url, sampletype="RAR") for filename in rardata.namelist(): try: data = rardata.read(filename) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (RAR)][ERROR] %s", str(e)) continue if not data: # pragma: no cover continue sample = log.ThugLogging.log_file(data, url) if sample is None: # pragma: no cover continue try: md5 = sample["md5"] except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (RAR)][ERROR] %s", str(e)) continue unzipped = os.path.join(log.ThugLogging.baseDir, "unzipped") log.ThugLogging.store_content(unzipped, md5, data) os.remove(rfile) return True @property def javaWebStartUserAgent(self): javaplugin = log.ThugVulnModules._javaplugin.split(".") last = javaplugin.pop() version = f"{'.'.join(javaplugin)}_{last}" return f"JNLP/6.0 javaws/{version} (b04) Java/{version}" def handle_java_jnlp(self, url, data): headers = {} headers["Connection"] = "keep-alive" try: soup = bs4.BeautifulSoup(data, "lxml") except Exception: # pragma: no cover,pylint:disable=broad-except return jnlp = soup.find("jnlp") if jnlp is None: # pragma: no cover return codebase = jnlp.attrs["codebase"] if "codebase" in jnlp.attrs else "" log.ThugLogging.add_behavior_warn( description="[JNLP Detected]", method="Dynamic Analysis" ) jars = soup.find_all("jar") if not jars: # pragma: no cover return headers["User-Agent"] = self.javaWebStartUserAgent for jar in jars: try: url = f"{codebase}{jar.attrs['href']}" log.DFT.window._navigator.fetch( url, headers=headers, redirect_type="JNLP" ) except Exception: # pragma: no cover,pylint:disable=broad-except pass def handle_svg_xml( self, url, data ): # pragma: no cover,pylint:disable=unused-argument try: soup = bs4.BeautifulSoup(data, "xml") except Exception: # pragma: no cover,pylint:disable=broad-except return scripts = soup.find_all("script") if not scripts: return # pragma: no cover window = getattr(self, "window", None) if not window: return # pragma: no cover for script in scripts: with window.context as ctxt: try: ctxt.eval(script.text) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[MIMEHANDLER (SVG+XML)][ERROR] %s", str(e)) def handle_json(self, url, data): # pylint:disable=unused-argument try: content = json.loads(data) except Exception: # pragma: no cover,pylint:disable=broad-except return False if not isinstance(content, dict): # pragma: no cover return False headers = {} headers["Connection"] = "keep-alive" for key in content.keys(): if key.lower() in ("@content.downloadurl",): try: log.DFT.window._navigator.fetch( content[key], headers=headers, redirect_type="JSON" ) except Exception: # pylint:disable=broad-except pass return True def passthrough(self, url, data): # pylint:disable=unused-argument """ The method passthrough is the default handler associated to almost all Content-Types with the few exceptions defined in register_empty_handlers. """ return True def get_handler(self, key): if self.mimehandler_pyhooks in (MIMEHANDLER_PYHOOKS_REQUIRED,): self.init_pyhooks() return self[key.split(";")[0]]
18,644
Python
.py
472
29.633475
86
0.599723
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,778
MimeTypes.py
buffer_thug/thug/DOM/MimeTypes.py
#!/usr/bin/env python # # MimeTypes.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .MimeType import MimeType from .Plugin import Plugin log = logging.getLogger("Thug") class MimeTypes(dict): def __init__(self): super().__init__() if not log.ThugVulnModules.acropdf_disabled: self["application/pdf"] = MimeType( { "description": "Adobe Acrobat Plug-In", "suffixes": "pdf", "filename": "npctrl.dll", "type": "application/pdf", "enabledPlugin": Plugin( { "name": "Adobe Acrobat", "version": f"{log.ThugVulnModules.acropdf_pdf}", "description": "Adobe Acrobat Plug-In", } ), "enabled": True, } ) if not log.ThugVulnModules.shockwave_flash_disabled: self["application/x-shockwave-flash"] = MimeType( { "description": "Shockwave Flash", "suffixes": "swf", "filename": f'Flash32_' f'{"_".join(log.ThugVulnModules.shockwave_flash.split("."))}.ocx', "type": "application/x-shockwave-flash", "enabledPlugin": Plugin( { "name": f"Shockwave Flash " f"{log.ThugVulnModules.shockwave_flash}", "version": f"{log.ThugVulnModules.shockwave_flash}", "description": f"Shockwave Flash " f"{log.ThugVulnModules.shockwave_flash}", } ), "enabled": True, } ) if not log.ThugVulnModules.javaplugin_disabled: self["application/x-java-applet"] = MimeType( { "description": "Java Applet", "suffixes": "jar", "filename": "npjp2.dll", "type": f"application/x-java-applet;jpi-version=" f"{log.ThugVulnModules._javaplugin}", "enabledPlugin": Plugin( { "name": f"Java {log.ThugVulnModules._javaplugin}", "version": f"{log.ThugVulnModules._javaplugin}", "description": "Java", } ), "enabled": True, } ) if log.ThugOpts.Personality.isWindows(): self["application/x-ms-wmz"] = MimeType( { "description": "Windows Media Player", "suffixes": "wmz", "filename": "npdsplay.dll", "type": "application/x-ms-wmz", "enabledPlugin": Plugin( { "name": "Windows Media Player 7", "version": "7", "description": "Windows Media Player 7", } ), "enabled": True, } ) def __getitem__(self, key): try: key = int(key) return self.item(key) except ValueError: return dict.__getitem__(self, key) if key in self else MimeType() @property def length(self): return len(self) def item(self, index): if index >= self.length: return MimeType() return list(self.values())[index] def namedItem(self, key): return dict.__getitem__(self, key) if key in self else MimeType()
4,504
Python
.py
111
25.333333
86
0.47968
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,779
MozConnection.py
buffer_thug/thug/DOM/MozConnection.py
#!/usr/bin/env python # # MozConnection.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class mozConnection(JSClass): def __init__(self): pass
782
Python
.py
21
35.52381
70
0.771768
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,780
JSInspector.py
buffer_thug/thug/DOM/JSInspector.py
#!/usr/bin/env python # # JSInspector.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import ast import logging log = logging.getLogger("Thug") class JSInspector: def __init__(self, window, ctxt, script): self.window = window self.script = script self.ctxt = ctxt @property def dump_url(self): if log.ThugOpts.local: return log.ThugLogging.url url = getattr(log, "last_url", None) return url if url else self.window.url def dump_eval(self): name, saved = log.ThugLogging.eval_symbol if not getattr(self.ctxt, "locals", None): # pragma: no cover return scripts = getattr(self.ctxt.locals, name, None) if scripts is None: return for script in scripts: if not isinstance(script, str): continue if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_eval_count() try: log.ThugLogging.add_behavior_warn( f"[eval] Deobfuscated argument: {script}" ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[JSInspector] dump_eval warning: %s", str(e)) log.JSClassifier.classify(self.dump_url, script) log.ThugLogging.add_code_snippet( script, language="Javascript", relationship="eval argument", check=True, force=True, ) delattr(self.ctxt.locals, name) delattr(self.ctxt.locals, saved) def dump_write(self): name, saved = log.ThugLogging.write_symbol if not getattr(self.ctxt, "locals", None): # pragma: no cover return htmls = getattr(self.ctxt.locals, name, None) if htmls is None: return for html in htmls: if not isinstance(html, str): continue try: log.ThugLogging.add_behavior_warn( f"[document.write] Deobfuscated argument: {html}" ) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[JSInspector] dump_write warning: %s", str(e)) log.HTMLClassifier.classify(self.dump_url, html) log.ThugLogging.add_code_snippet( html, language="HTML", relationship="document.write argument", check=True, force=True, ) delattr(self.ctxt.locals, name) delattr(self.ctxt.locals, saved) def dump(self): self.dump_eval() self.dump_write() def run(self): result = None try: result = self.ctxt.eval(self.script) except (UnicodeDecodeError, TypeError): if "\\u" in self.script: # pragma: no cover try: result = self.ctxt.eval(self.script.replace("\\u", "%u")) except Exception as e: # pylint:disable=broad-except log.warning("[JSInspector] %s", str(e)) except SyntaxError: try: result = self.ctxt.eval(ast.literal_eval(f"'{self.script}'")) except Exception as e: # pylint:disable=broad-except log.warning("[JSInspector] %s", str(e)) except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[JSInspector] %s", str(e)) try: self.dump() except Exception as e: # pragma: no cover,pylint:disable=broad-except log.warning("[JSInspector] Dumping failed (%s)", str(e)) return result
4,398
Python
.py
110
29.509091
82
0.590802
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,781
Personality.py
buffer_thug/thug/DOM/Personality.py
#!/usr/bin/env python # # Personality.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import sys import os import json import logging log = logging.getLogger("Thug") class Personality(dict): def __init__(self): super().__init__() personalities = log.personalities_path if personalities is None: # pragma: no cover log.warning("[CRITICAL] Thug personalities not found! Exiting") sys.exit(0) for root, _dir, files in os.walk(personalities): # pylint:disable=unused-variable for f in files: if not f.endswith(".json"): continue name = f.split(".json")[0] with open( os.path.join(root, f), encoding="utf-8", mode="r" ) as personality: self[name] = json.load(personality) # Shell variables are case insensitive, will process them # to make sure all keys in the dict are lowercase. for k, v in self[name].pop("shellVariables", {}).items(): if "shellVariables" not in self[name]: self[name]["shellVariables"] = {} self[name]["shellVariables"][k.lower()] = v # Special folder names are case insensitive, will process them # to make sure all keys in the dict are lowercase. for k, v in self[name].pop("specialFolders", {}).items(): if "specialFolders" not in self[name]: self[name]["specialFolders"] = {} self[name]["specialFolders"][k.lower()] = v @property def userAgent(self): return self[log.ThugOpts.useragent]["userAgent"] @property def javaUserAgent(self): return self[log.ThugOpts.useragent]["javaUserAgent"] @property def browserVersion(self): return self[log.ThugOpts.useragent]["version"] @property def platform(self): return self[log.ThugOpts.useragent]["platform"] @property def browserMajorVersion(self): return int(self.browserVersion.split(".")[0]) @property def cc_on(self): return self[log.ThugOpts.useragent]["cc_on"] def isIE(self): return self[log.ThugOpts.useragent]["browserTag"].startswith("ie") def isEdge(self): return self[log.ThugOpts.useragent]["browserTag"].startswith("edge") def isWindows(self): return log.ThugOpts.useragent.startswith("win") def isFirefox(self): return self[log.ThugOpts.useragent]["browserTag"].startswith("firefox") def isChrome(self): return self[log.ThugOpts.useragent]["browserTag"].startswith("chrome") def isSafari(self): return self[log.ThugOpts.useragent]["browserTag"].startswith("safari") def ScriptEngineMajorVersion(self): return self[log.ThugOpts.useragent]["ScriptEngineMajorVersion"] def ScriptEngineMinorVersion(self): return self[log.ThugOpts.useragent]["ScriptEngineMinorVersion"] def ScriptEngineBuildVersion(self): return self[log.ThugOpts.useragent]["ScriptEngineBuildVersion"] def getShellVariable(self, variableName): return ( self[log.ThugOpts.useragent] .get("shellVariables", {}) .get(variableName.strip("%").lower(), "") ) def getSpecialFolder(self, folderName): return ( self[log.ThugOpts.useragent] .get("specialFolders", {}) .get(folderName.lower(), "") )
4,191
Python
.py
98
33.959184
90
0.637549
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,782
Console.py
buffer_thug/thug/DOM/Console.py
#!/usr/bin/env python # # Console.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from .JSClass import JSClass log = logging.getLogger("Thug") class Console(JSClass): def __init__(self): self._counter = 0 self._label_counter = {} self.__init_console_personality() def __init_console_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_console_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_console_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_console_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_console_personality_Safari() return def __init_console_personality_IE(self): self.__methods__["assert"] = self._assert self.clear = self._clear self.count = self._count if log.ThugOpts.Personality.browserMajorVersion > 7: self.info = self._info self.log = self._log self.warn = self._warn self.__methods__["error"] = self._error if log.ThugOpts.Personality.browserMajorVersion > 10: self.group = self._group self.groupCollapsed = self._groupCollapsed self.groupEnd = self._groupEnd self.time = self._time self.timeEnd = self._timeEnd self.trace = self._trace def __init_console_personality_Firefox(self): if log.ThugOpts.Personality.browserMajorVersion > 3: self.group = self._group self.groupCollapsed = self._groupCollapsed self.groupEnd = self._groupEnd self.info = self._info self.log = self._log self.warn = self._warn self.__methods__["error"] = self._error if log.ThugOpts.Personality.browserMajorVersion > 9: self.time = self._time self.timeEnd = self._timeEnd self.trace = self._trace if log.ThugOpts.Personality.browserMajorVersion > 27: self.__methods__["assert"] = self._assert if log.ThugOpts.Personality.browserMajorVersion > 29: self.count = self._count if log.ThugOpts.Personality.browserMajorVersion > 47: # pragma: no cover self.clear = self._clear def __init_console_personality_Chrome(self): self.clear = self._clear self.count = self._count self.group = self._group self.groupCollapsed = self._groupCollapsed self.groupEnd = self._groupEnd self.info = self._info self.log = self._log self.warn = self._warn self.time = self._time self.timeEnd = self._timeEnd self.trace = self._trace self.__methods__["assert"] = self._assert self.__methods__["error"] = self._error def __init_console_personality_Safari(self): self.clear = self._clear self.count = self._count self.info = self._info self.log = self._log self.warn = self._warn self.__methods__["assert"] = self._assert self.__methods__["error"] = self._error if log.ThugOpts.Personality.browserMajorVersion > 3: self.time = self._time self.timeEnd = self._timeEnd self.trace = self._trace if log.ThugOpts.Personality.browserMajorVersion > 4: self.group = self._group self.groupCollapsed = self._groupCollapsed self.groupEnd = self._groupEnd def _assert(self, expression, statement): log.warning("[Console] assert(%s, '%s')", expression is False, statement) def _clear(self): log.warning("[Console] clear()") def _count(self, label=None): if not label: self._counter += 1 log.warning("[Console] count() = %s", self._counter) return if label not in self._label_counter: self._label_counter[label] = 0 self._label_counter[label] += 1 log.warning("[Console] count('%s') = %s", label, self._label_counter[label]) def debug(self, *args): pass def _error(self, *args): for message in args: log.warning("[Console] error('%s')", message) def _group(self): log.warning("[Console] group()") def _groupCollapsed(self): log.warning("[Console] groupCollapsed()") def _groupEnd(self): log.warning("[Console] groupEnd()") def _info(self, *args): for message in args: log.warning("[Console] info('%s')", message) def _log(self, *args): for message in args: log.warning("[Console] log('%s')", message) def _time(self, label=None): pass def _timeEnd(self, label=None): pass def _trace(self, label=None): pass def _warn(self, *args): for message in args: log.warning("[Console] warn('%s')", message)
5,685
Python
.py
142
31.21831
84
0.612252
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,783
Crypto.py
buffer_thug/thug/DOM/Crypto.py
#!/usr/bin/env python # # Crypto.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class Crypto(JSClass): def __init__(self): pass @property def enableSmartCardEvents(self): return False @property def version(self): return "2.4" def disableRightClick(self): pass def importUserCertificates(self, nickname, cmmfResponse, forceToBackUp): # pylint:disable=unused-argument return "" def logout(self): pass
1,113
Python
.py
33
30.060606
110
0.735075
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,784
Location.py
buffer_thug/thug/DOM/Location.py
#!/usr/bin/env python # # Location.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging from urllib.parse import urlparse from urllib.parse import urlunparse from thug.DOM.W3C import w3c from .JSClass import JSClass log = logging.getLogger("Thug") class Location(JSClass): def __init__(self, window): self._window = window def toString(self): # pragma: no cover return self._window.url @property def parts(self): return urlparse(self._window.url) @property def origin(self): return f"{self.parts.scheme}://{self.parts.netloc}" def get_href(self): return self._window.url def set_href(self, url): if log.HTTPSession.is_data_uri(url): # pragma: no cover log.DFT._handle_data_uri(url) return referer = self._window.url if log.HTTPSession.check_equal_urls(url, referer): log.warning("Skipping location redirection from %s to %s", referer, url) return for p in log.ThugOpts.Personality: if ( log.ThugOpts.Personality[p]["userAgent"] == self._window._navigator.userAgent ): break url = log.HTTPSession.normalize_url(self._window, url) log.ThugLogging.log_href_redirect(referer, url) doc = w3c.parseString("") window = log.Window(referer, doc, personality=p) # pylint:disable=undefined-loop-variable window = window.open(url) if not window: return from .DFT import DFT # self._window.url = url dft = DFT(window) dft.run() href = property(get_href, set_href) def get_protocol(self): return f"{self.parts.scheme}:" def set_protocol(self, protocol): if protocol.endswith(":"): protocol = protocol[:-1] if protocol in (self.parts.scheme,): return self.set_href(urlunparse(self.parts._replace(scheme=protocol))) protocol = property(get_protocol, set_protocol) def get_host(self): return self.parts.netloc def set_host(self, host): if host in (self.parts.netloc,): return self.set_href(urlunparse(self.parts._replace(netloc=host))) host = property(get_host, set_host) def get_hostname(self): return self.parts.hostname def set_hostname(self, hostname): snetloc = self.parts.netloc.split(":") if len(snetloc) and hostname in (snetloc[0],): return host = f"{hostname}:{snetloc[1]}" if len(snetloc) > 1 else hostname self.set_host(host) hostname = property(get_hostname, set_hostname) def get_port(self): return self.parts.port def set_port(self, port): snetloc = self.parts.netloc.split(":") if len(snetloc) > 1 and str(port) in (snetloc[1],): return host = f"{snetloc[0]}:{port}" self.set_host(host) port = property(get_port, set_port) def get_pathname(self): return self.parts.path def set_pathname(self, pathname): if pathname in (self.parts.path,): return self.set_href(urlunparse(self.parts._replace(path=pathname))) pathname = property(get_pathname, set_pathname) def get_search(self): return self.parts.query def set_search(self, search): if search in (self.parts.query,): return self.set_href(urlunparse(self.parts._replace(query=search))) search = property(get_search, set_search) def get_hash(self): return self.parts.fragment def set_hash(self, fragment): if fragment in (self.parts.fragment,): return self.set_href(urlunparse(self.parts._replace(fragment=fragment))) hash = property(get_hash, set_hash) def assign(self, url): """Loads a new HTML document.""" self._window.open(url) def reload(self, force=False): # pylint:disable=unused-argument """Reloads the current page.""" self._window.open(self._window.url) def replace(self, url): """Replaces the current document by loading another document at the specified URL.""" self._window.open(url)
4,873
Python
.py
126
31.166667
98
0.647497
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,785
HTTPSessionException.py
buffer_thug/thug/DOM/HTTPSessionException.py
#!/usr/bin/env python # # HTTPSession.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import requests class AboutBlank(requests.RequestException): pass class FetchForbidden(requests.RequestException): pass class InvalidUrl(requests.RequestException): pass class ThresholdExpired(requests.RequestException): pass
932
Python
.py
26
33.884615
70
0.797101
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,786
Utils.py
buffer_thug/thug/DOM/Utils.py
#!/usr/bin/env python # # Utils.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA from .JSClass import JSClass class Utils(JSClass): def __init__(self): pass
766
Python
.py
21
34.761905
70
0.766846
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,787
DOMParser.py
buffer_thug/thug/DOM/W3C/DOMParser.py
#!/usr/bin/env python import logging log = logging.getLogger("Thug") class DOMParser: def parseFromString(self, s, type_): parser = "lxml" if "xml" in type_ else "html.parser" return log.DOMImplementation(log.HTMLInspector.run(s, parser))
274
Python
.py
7
33.142857
71
0.69112
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,788
w3c.py
buffer_thug/thug/DOM/W3C/w3c.py
#!/usr/bin/env python import logging import bs4 log = logging.getLogger("Thug") def getDOMImplementation(dom=None, **kwds): return log.DOMImplementation(dom if dom else bs4.BeautifulSoup("", "lxml"), **kwds) def parseString(html, **kwds): soup = log.HTMLInspector.run(html, "html.parser") return log.DOMImplementation(soup, **kwds)
365
Python
.py
9
35.888889
88
0.723837
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,789
DOMTokenList.py
buffer_thug/thug/DOM/W3C/DOMTokenList.py
#!/usr/bin/env python import logging log = logging.getLogger("Thug") class DOMTokenList: def __init__(self, supported, tokens=None): self.tokens = [] if tokens is None else tokens self.__init_supported(supported) def __init_supported(self, supported): self.supported = [] for support in supported: if support not in self.supported: self.supported.append(support) nosupport = f"no{support}" if nosupport not in self.supported: self.supported.append(nosupport) @property def length(self): return len(self.tokens) def item(self, index): return self.tokens[index] if index in range(0, len(self.tokens)) else None def contains(self, token): return token in self.tokens def add(self, token): if token in self.supported and token not in self.tokens: self.tokens.append(token) def remove(self, token): if token in self.tokens: self.tokens.remove(token) def toggle(self, token): if token in self.tokens: self.tokens.remove(token) return self.tokens.append(token) def replace(self, oldToken, newToken): self.remove(oldToken) self.add(newToken) def supports(self, token): return token in self.supported @property def value(self): return " ".join(self.tokens)
1,453
Python
.py
41
27
82
0.630108
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,790
CSSStyleDeclaration.py
buffer_thug/thug/DOM/W3C/Style/CSS/CSSStyleDeclaration.py
#!/usr/bin/env python import logging from thug.DOM.JSClass import JSClass log = logging.getLogger("Thug") class CSSStyleDeclaration(JSClass): def __init__(self, style): self.props = {} for prop in [p for p in style.split(";") if p]: k, v = prop.strip().split(":") self.props[k.strip()] = v.strip() @property def cssText(self): css_text = "; ".join([f"{k}: {v}" for k, v in self.props.items()]) return css_text + ";" if css_text else "" def getPropertyValue(self, name): return self.props.get(name, "") def removeProperty(self, name): return self.props.pop(name, "") @property def length(self): return len(self.props) def item(self, index): if index < 0 or index >= len(self.props): return "" return list(self.props.keys())[index] def __getattr__(self, name): if ( log.ThugOpts.Personality.isIE() and log.ThugOpts.Personality.browserMajorVersion < 7 and name in ("maxHeight",) ): raise AttributeError(name) return self.getPropertyValue(name) def __setattr__(self, name, value): if name in ("props",): super().__setattr__(name, value) else: self.props[name] = value
1,339
Python
.py
38
27
74
0.575428
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,791
ElementCSSInlineStyle.py
buffer_thug/thug/DOM/W3C/Style/CSS/ElementCSSInlineStyle.py
#!/usr/bin/env python class ElementCSSInlineStyle: def __init__(self, doc, tag): self.doc = doc self.tag = tag self._style = None @property def style(self): if self._style is None: from .CSSStyleDeclaration import CSSStyleDeclaration self._style = CSSStyleDeclaration( self.tag["style"] if self.tag.has_attr("style") else "" ) return self._style
456
Python
.py
14
23.714286
71
0.587156
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,792
File.py
buffer_thug/thug/DOM/W3C/File/File.py
#!/usr/bin/env python # # File.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # File API # https://w3c.github.io/FileAPI/ import logging from .Blob import Blob log = logging.getLogger("Thug") class File(Blob): def __init__(self, bits, name, options=None): self.name = name Blob.__init__(self, bits, options) self.__handle() def __handle_zip(self): content = bytearray() for item in self.blob: content.extend(item) log.ThugLogging.log_file(bytes(content), self.name, sampletype="ZIP") def __handle(self): _type = self.options.get("type", None) if _type is None: return # pragma: no cover if _type.lower() in ("application/zip",): self.__handle_zip()
1,377
Python
.py
38
31.789474
77
0.688253
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,793
__init__.py
buffer_thug/thug/DOM/W3C/File/__init__.py
__all__ = ["Blob", "File"] from .Blob import Blob from .File import File
74
Python
.py
3
23.333333
26
0.671429
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,794
Blob.py
buffer_thug/thug/DOM/W3C/File/Blob.py
#!/usr/bin/env python # # Blob.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # File API # https://w3c.github.io/FileAPI/ from promise import Promise import STPyV8 from thug.DOM.JSClass import JSClass from thug.DOM.W3C.Core.DOMException import DOMException class Blob(JSClass): def __init__(self, array=None, options=None): self.array = STPyV8.JSArray() if array is None else array if options is None: options = {} try: self.options = dict(options) except ValueError: raise DOMException(DOMException.NOT_SUPPORTED_ERR) # pylint: disable=raise-missing-from @staticmethod def __convert(obj): if isinstance(obj, STPyV8.JSArray): return [Blob.__convert(v) for v in obj] if isinstance(obj, STPyV8.JSObject): return [Blob.__convert(obj.__getattr__(str(k))) for k in obj.__dir__()] if isinstance(obj, Blob): return [Blob.__convert(v) for v in obj.array] return obj @property def blob(self): return [j for i in self.__convert(self.array) for j in i] @property def size(self): return len(self.blob) @property def type(self): return self.options.get("type", "").lower() @property def endings(self): return self.options.get("endings", "transparent").lower() def text(self): return Promise(lambda resolve, reject: resolve("".join(self.blob))) def arrayBuffer(self): return Promise(lambda resolve, reject: resolve(self.array)) def slice(self, start=0, end=None, contentType=""): options = {} options["type"] = contentType end = self.size if end is None else end return Blob(self.blob[start:end], options)
2,380
Python
.py
62
32.693548
100
0.678121
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,795
AbstractView.py
buffer_thug/thug/DOM/W3C/Views/AbstractView.py
#!/usr/bin/env python import logging log = logging.getLogger("Thug") # Introduced in DOM Level 2 class AbstractView: def __init__(self): pass @property def document(self): return None
217
Python
.py
10
17.4
31
0.678218
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,796
DocumentView.py
buffer_thug/thug/DOM/W3C/Views/DocumentView.py
#!/usr/bin/env python # Introduced in DOM Level 2 class DocumentView: def __init__(self, doc): self.doc = doc @property def defaultView(self): return getattr(self, "window", None)
211
Python
.py
8
21.5
44
0.65
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,797
Document.py
buffer_thug/thug/DOM/W3C/Core/Document.py
#!/usr/bin/env python import copy import logging import bs4 from thug.DOM.W3C.Events.DocumentEvent import DocumentEvent from thug.DOM.W3C.Views.DocumentView import DocumentView from .Node import Node log = logging.getLogger("Thug") class Document(Node, DocumentEvent, DocumentView): def __init__(self, doc, tag): Node.__init__(self, doc, tag) DocumentEvent.__init__(self, doc) DocumentView.__init__(self, doc) self.__init_document_personality() def __init_document_personality(self): self.__init_characterSet() if log.ThugOpts.Personality.isIE(): self.__init_document_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_document_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_document_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_document_personality_Safari() return def __init_characterSet(self): self._character_set = "" for meta in self.doc.find_all("meta"): if "charset" in meta.attrs: self._characterSet = meta.attrs["charset"].upper() def __init_document_personality_IE(self): self.defaultCharset = self._defaultCharset if log.ThugOpts.Personality.browserMajorVersion > 7: self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector if log.ThugOpts.Personality.browserMajorVersion > 8: self.getElementsByClassName = self._getElementsByClassName self.characterSet = self._characterSet self.inputEncoding = self._inputEncoding else: self.charset = self._characterSet if log.ThugOpts.Personality.browserMajorVersion > 10: self.__proto__ = None def __init_document_personality_Firefox(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector self.getElementsByClassName = self._getElementsByClassName self.characterSet = self._characterSet self.inputEncoding = self._inputEncoding def __init_document_personality_Chrome(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector self.getElementsByClassName = self._getElementsByClassName self.characterSet = self._characterSet self.inputEncoding = self._inputEncoding def __init_document_personality_Safari(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector self.getElementsByClassName = self._getElementsByClassName self.characterSet = self._characterSet self.inputEncoding = self._inputEncoding def _querySelectorAll(self, selectors): from .NodeList import NodeList try: s = self.doc.select(selectors) except Exception: # pragma: no cover,pylint:disable=broad-except return NodeList(self.doc, []) return NodeList(self.doc, s) def _querySelector(self, selectors): try: s = self.doc.select(selectors) except Exception: # pragma: no cover,pylint:disable=broad-except return None return ( log.DOMImplementation.createHTMLElement(self, s[0]) if s and s[0] else None ) # Introduced in DOM Level 3 @property def textContent(self): return None @property def nodeType(self): return Node.DOCUMENT_NODE @property def nodeName(self): return "#document" @property def nodeValue(self): return None @property def childNodes(self): from .NodeList import NodeList return NodeList(self.doc, self.doc.contents) @property def doctype(self): from .DocumentType import DocumentType _doctype = getattr(self, "_doctype", None) if _doctype: return _doctype tags = [t for t in self.doc if isinstance(t, bs4.Doctype)] if not tags: return None # pragma: no cover self._doctype = DocumentType(self.doc, tags[0]) return self._doctype @property def implementation(self): return self def getCharacterSet(self): return self._character_set def setCharacterSet(self, value): self._character_set = value _characterSet = property(getCharacterSet, setCharacterSet) @property def _inputEncoding(self): for meta in self.doc.find_all("meta"): if "charset" in meta.attrs: return meta.attrs["charset"].upper() return "" @property def _defaultCharset(self): return "Windows-1252" def createElement(self, tagname, tagvalue=None): # pylint:disable=unused-argument if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_createelement_count() # Internet Explorer 8 and below also support the syntax # document.createElement('<P>') if ( log.ThugOpts.Personality.isIE() and log.ThugOpts.Personality.browserMajorVersion < 9 ): if tagname.startswith("<") and ">" in tagname: tagname = tagname[1:].split(">")[0] return log.DOMImplementation.createHTMLElement( self, bs4.Tag(parser=self.doc, name=tagname) ) def createDocumentFragment(self): from .DocumentFragment import DocumentFragment if log.ThugOpts.features_logging: log.ThugLogging.Features.increase_createdocumentfragment_count() return DocumentFragment(self) def createTextNode(self, data): from .Text import Text return Text(self, bs4.NavigableString(data)) def createComment(self, data): from .Comment import Comment return Comment(self, bs4.Comment(data)) def createCDATASection(self, data): from .CDATASection import CDATASection return CDATASection(self, bs4.CData(data)) def createProcessingInstruction(self, target, data): from .ProcessingInstruction import ProcessingInstruction return ProcessingInstruction(self, target, bs4.ProcessingInstruction(data)) def createAttribute(self, name): from .Attr import Attr return Attr(self, None, name) def createEntityReference(self, name): from .EntityReference import EntityReference return EntityReference(self, name) def getElementsByTagName(self, tagname): from .NodeList import NodeList if tagname in ("*",): return NodeList(self.doc, self.doc.find_all(string=False)) return NodeList(self.doc, self.doc.find_all(tagname.lower())) def _getElementsByClassName(self, classname): from .NodeList import NodeList return NodeList(self.doc, self.doc.find_all(class_=classname)) # Introduced in DOM Level 2 def getElementById(self, elementId): if ( log.ThugOpts.Personality.isIE() and log.ThugOpts.Personality.browserMajorVersion < 8 ): return self._getElementById_IE67(elementId) return self._getElementById(elementId) def _getElementById(self, elementId): tag = self.doc.find(id=elementId) return log.DOMImplementation.createHTMLElement(self, tag) if tag else None # Internet Explorer 6 and 7 getElementById is broken and returns # elements with 'id' or 'name' attributes equal to elementId def _getElementById_IE67(self, elementId): def _match_tag(tag, p): return p in tag.attrs and tag.attrs[p] == elementId def match_tag(tag, _id): if _match_tag(tag, _id): return True return False def filter_tags_id(tag): return tag.has_attr("id") def filter_tags_name(tag): return tag.has_attr("name") for tag in self.doc.find_all(filter_tags_id): if match_tag(tag, "id"): return log.DOMImplementation.createHTMLElement(self, tag) for tag in self.doc.find_all(filter_tags_name): if match_tag(tag, "name"): return log.DOMImplementation.createHTMLElement(self, tag) return None # Introduced in DOM Level 2 def importNode(self, importedNode, deep=False): # pylint:disable=unused-argument return copy.copy(importedNode) # Modified in DOM Level 2 @property def ownerDocument(self): return None def execCommand(self, commandIdentifier, userInterface=False, value=None): # pylint:disable=unused-argument return False
8,842
Python
.py
209
33.272727
112
0.661796
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,798
Notation.py
buffer_thug/thug/DOM/W3C/Core/Notation.py
#!/usr/bin/env python from .Node import Node class Notation(Node): # pragma: no cover @property def publicId(self): return None @property def systemId(self): return None @property def nodeName(self): pass @property def nodeType(self): return Node.NOTATION_NODE @property def nodeValue(self): return None # Introduced in DOM Level 3 @property def textContent(self): return None
486
Python
.py
22
16.181818
41
0.640351
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
12,799
DocumentFragment.py
buffer_thug/thug/DOM/W3C/Core/DocumentFragment.py
#!/usr/bin/env python import logging import bs4 from .Node import Node log = logging.getLogger("Thug") class DocumentFragment(Node): def __init__(self, doc): tag = bs4.Tag(parser=doc, name="documentfragment") Node.__init__(self, doc, tag) self.__init_documentfragment_personality() def __init_documentfragment_personality(self): if log.ThugOpts.Personality.isIE(): self.__init_documentfragment_personality_IE() return if log.ThugOpts.Personality.isFirefox(): self.__init_documentfragment_personality_Firefox() return if log.ThugOpts.Personality.isChrome(): self.__init_documentfragment_personality_Chrome() return if log.ThugOpts.Personality.isSafari(): self.__init_documentfragment_personality_Safari() return def __init_documentfragment_personality_IE(self): if log.ThugOpts.Personality.browserMajorVersion > 7: self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector def __init_documentfragment_personality_Firefox(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector def __init_documentfragment_personality_Chrome(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector def __init_documentfragment_personality_Safari(self): self.querySelectorAll = self._querySelectorAll self.querySelector = self._querySelector def _querySelectorAll(self, selectors): from .NodeList import NodeList try: s = self.tag.select(selectors) except Exception: # pragma: no cover,pylint:disable=broad-except return NodeList(self.doc, []) return NodeList(self.doc, s) def _querySelector(self, selectors): try: s = self.tag.select(selectors) except Exception: # pragma: no cover,pylint:disable=broad-except return None return ( log.DOMImplementation.createHTMLElement(self, s[0]) if s and s[0] else None ) @property def nodeName(self): return "#document-fragment" @property def nodeType(self): return Node.DOCUMENT_FRAGMENT_NODE @property def nodeValue(self): return None
2,422
Python
.py
60
31.75
87
0.667236
buffer/thug
978
204
0
GPL-2.0
9/5/2024, 5:11:50 PM (Europe/Amsterdam)