Python Forum
Why, TypeError: expected string or bytes-like object ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why, TypeError: expected string or bytes-like object ?
#1
The method below aims to receive parameters in order to detect xss threat. I could not identify an error in the code below but only on the return of the method I get the error (TypeError: expected string or bytes-like object), does anyone know why ?

# Native Module, Import : re, regex
import re, json

# Name Class : CrositeScript
class CrositeScript:

    def m_post(o_output, v_url, v_inp):

        # Regex Condition - exist if check
        if re.search(
            r"FSCommand|onAbort|onActivate|onAfterPrint|onAfterUpdate|onBeforeActivate|"
            r"onBeforeCopy|onBeforeCut|onBeforeDeactivate|onBeforeEditFocus|onBeforePaste|"
            r"onBeforePrint|onBeforeUnload|onBeforeUpdate|onBegin|onBlur|onBounce|onCellChange|"
            r"onChange|onClick|onContextMenu|onControlSelect|onCopy|onCut|onDataAvailable|"
            r"onDataSetChanged|onDataSetComplete|onDblClick|onDeactivate|onDrag|onDragEnd|"
            r"onDragLeave|onDragEnter|onDragOver|onDragDrop|onDragStart|onDrop|onEnd|onError|"
            r"onErrorUpdate|onFilterChange|onFinish|onFocus|onFocusIn|onFocusOut|onHashChange|"
            r"onHelp|onInput|onKeyDown|onKeyPress|onKeyUp|onLayoutComplete|onLoad|onLoseCapture|"
            r"onMediaComplete|onMediaError|onMessage|onMouseDown|onMouseEnter|onMouseLeave|"
            r"onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMouseWheel|onMove|onMoveEnd|onMoveStart|"
            r"onOffline|onOnline|onOutOfSync|onPaste|onPause|onPopState|onProgress|onPropertyChange|"
            r"onReadyStateChange|onRedo|onRepeat|onReset|onResize|onResizeEnd|onResizeStart|onResume|"
            r"onReverse|onRowsEnter|onRowExit|onRowDelete|onRowInserted|onScroll|onSeek|onSelect|"
            r"onSelectionChange|onSelectStart|onStart|onStop|onStorage|onSyncRestored|onSubmit|onTimeError|"
            r"onTrackChange|onUndo|onUnload|onURLFlip|seekSegmentTime|bgsound|xss|rocks|noxss|"
            r"<script>|</script>|script|livescript|vbscript|alert|[(]|[)]|>|<|;|&#|[*]|`",
            v_url, re.IGNORECASE
        ):
            # Variable : obtem status de resposta para client browser :
            status = "200 OK"
            # Variable : obtem cabeçalho http para o browser do client
            headers = [("Content-type", "application/json; charset=utf-8")]
            # Function : Envio de variable para o client browser :
            o_output(status, headers)
            # Output :
            return "Hacker Attempt: True, Threat : Cross-Site Scripting, Syntax: " + v_url

        else:
            # Regex Condition - exist if check
            if re.search(
                r"FSCommand|onAbort|onActivate|onAfterPrint|onAfterUpdate|onBeforeActivate|"
                r"onBeforeCopy|onBeforeCut|onBeforeDeactivate|onBeforeEditFocus|onBeforePaste|"
                r"onBeforePrint|onBeforeUnload|onBeforeUpdate|onBegin|onBlur|onBounce|onCellChange|"
                r"onChange|onClick|onContextMenu|onControlSelect|onCopy|onCut|onDataAvailable|"
                r"onDataSetChanged|onDataSetComplete|onDblClick|onDeactivate|onDrag|onDragEnd|"
                r"onDragLeave|onDragEnter|onDragOver|onDragDrop|onDragStart|onDrop|onEnd|onError|"
                r"onErrorUpdate|onFilterChange|onFinish|onFocus|onFocusIn|onFocusOut|onHashChange|"
                r"onHelp|onInput|onKeyDown|onKeyPress|onKeyUp|onLayoutComplete|onLoad|onLoseCapture|"
                r"onMediaComplete|onMediaError|onMessage|onMouseDown|onMouseEnter|onMouseLeave|"
                r"onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMouseWheel|onMove|onMoveEnd|onMoveStart|"
                r"onOffline|onOnline|onOutOfSync|onPaste|onPause|onPopState|onProgress|onPropertyChange|"
                r"onReadyStateChange|onRedo|onRepeat|onReset|onResize|onResizeEnd|onResizeStart|onResume|"
                r"onReverse|onRowsEnter|onRowExit|onRowDelete|onRowInserted|onScroll|onSeek|onSelect|"
                r"onSelectionChange|onSelectStart|onStart|onStop|onStorage|onSyncRestored|onSubmit|onTimeError|"
                r"onTrackChange|onUndo|onUnload|onURLFlip|seekSegmentTime|bgsound|xss|rocks|noxss|"
                r"<script>|</script>|script|livescript|vbscript|alert|[(]|[)]|>|<|;|&#|[*]|`",
                v_inp, re.IGNORECASE
            ):
                # Variable : obtem status de resposta para client browser :
                status = "200 OK"
                # Variable : obtem cabeçalho http para o browser do client
                headers = [("Content-type", "application/json; charset=utf-8")]
                # Function : Envio de variable para o client browser :
                o_output(status, headers)
                # Output :
                return "Hacker Attempt: True, Threat : Cross-Site Scripting, Syntax: " + v_inp

            else:

                v_keo = v_inp.getvalue("v_query")
                # Converte para dicionario
                o_data = dict()
                # Pre-estrutura para o formato json
                o_data["term"] = "O termo pesquisado - " + v_keo
                # Da a saida no formato json
                v_json = json.dumps(o_data)

                # Variable : obtem status de resposta para client browser :
                status = "200 OK"
                # Variable : obtem cabeçalho http para o browser do client
                headers = [("Content-type", "application/json; charset=utf-8")]
                # Function : Envio de variable para o client browser :
                o_output(status, headers)
                # Method Return Instruction :
                return v_json
Reply
#2
Please show how you call this and the complete error message (with all the traceback).
Reply
#3
(May-07-2020, 11:52 PM)bowlofred Wrote: Please show how you call this and the complete error message (with all the traceback).

Ok :
Error:
(wse) assistant@webstrucs:~/PycharmProjects/kosmos$ python runwsgi.py Running Kosmos Application Browser Access - http://127.0.0.1:8000 Crl+c for exit command or Crl+z for stop 127.0.0.1 - - [07/May/2020 23:23:47] "GET / HTTP/1.1" 200 2815 127.0.0.1 - - [07/May/2020 23:23:47] "GET /release/assets/css/custom.css HTTP/1.1" 200 634 127.0.0.1 - - [07/May/2020 23:23:47] "GET /release/assets/cod/query.js HTTP/1.1" 200 944 Traceback (most recent call last): File "/usr/local/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "runwsgi.py", line 35, in apps return [str(PostEntry.m_parser(o_output, v_url, v_inp)).encode("utf-8")] File "/home/assistant/PycharmProjects/kosmos/corework/response/postentry.py", line 11, in m_parser return ThreatDetect.m_post(o_output, v_url, v_inp) File "/home/assistant/PycharmProjects/kosmos/corework/security/threatdetect.py", line 41, in m_post return CrositeScript.m_post(o_output, v_url, v_inp) File "/home/assistant/PycharmProjects/kosmos/corework/security/crositescript.py", line 103, in m_post v_inp, re.IGNORECASE File "/home/assistant/.virtualenvs/wse/lib/python3.7/re.py", line 183, in search return _compile(pattern, flags).search(string) [b]TypeError: expected string or bytes-like object[/b] 127.0.0.1 - - [07/May/2020 23:23:53] "POST /release/runcode/query HTTP/1.1" 500 59
Reply
#4
You're passing v_inp as the string to examine for a pattern match via re.search(). But what you've posted doesn't show where that comes from (the actual function call). If what is passed in is not a string, then regex method will not like it.

>>> s1 = "foobar"  # a string
>>> s2 = 85        # not a string
>>> re.search(r"foo", s1)
<_sre.SRE_Match object; span=(0, 3), match='foo'>
>>> re.search(r"foo", s2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/re.py", line 182, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
You could possibly force it by coercing it to a string, but it's probably better to see what's calling it and if it's passing the right object.

>>> re.search(r"foo", str(s2))
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: cannot pickle ‘_asyncio.Future’ object Abdul_Rafey 1 268 Mar-07-2024, 03:40 PM
Last Post: deanhystad
  error in class: TypeError: 'str' object is not callable akbarza 2 444 Dec-30-2023, 04:35 PM
Last Post: deanhystad
Bug TypeError: 'NoneType' object is not subscriptable TheLummen 4 679 Nov-27-2023, 11:34 AM
Last Post: TheLummen
  TypeError: 'NoneType' object is not callable akbarza 4 920 Aug-24-2023, 05:14 PM
Last Post: snippsat
  [NEW CODER] TypeError: Object is not callable iwantyoursec 5 1,261 Aug-23-2023, 06:21 PM
Last Post: deanhystad
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,165 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  boto3 - Error - TypeError: string indices must be integers kpatil 7 1,182 Jun-09-2023, 06:56 PM
Last Post: kpatil
  "TypeError: string indices must be integers, not 'str'" while not using any indices bul1t 2 1,931 Feb-11-2023, 07:03 PM
Last Post: deanhystad
  TypeError: 'float' object is not callable #1 isdito2001 1 1,045 Jan-21-2023, 12:43 AM
Last Post: Yoriz
  TypeError: a bytes-like object is required ZeroX 13 3,838 Jan-07-2023, 07:02 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020