{
    "content": [
        {
            "type": "text",
            "text": "# Safe (man)\n\n## NAME\n\nSafe - Compile and execute code in restricted compartments\n\n## SYNOPSIS\n\nuse Safe;\n$compartment = new Safe;\n$compartment->permit(qw(time sort :browse));\n$result = $compartment->reval($unsafecode);\n\n## DESCRIPTION\n\nThe Safe extension module allows the creation of compartments in which perl code can be\nevaluated. Each compartment has\n\n## TLDR\n\n> Interact with HashiCorp Vault.\n\n- Add a safe target:\n  `safe target {{vault_addr}} {{target_name}}`\n- Authenticate the CLI client against the Vault server, using an authentication token:\n  `safe auth {{authentication_token}}`\n- Print the environment variables describing the current target:\n  `safe env`\n- Display a tree hierarchy of all reachable keys for a given path:\n  `safe tree {{path}}`\n- Move a secret from one path to another:\n  `safe move {{path/to/old_secret}} {{path/to/new_secret}}`\n- Generate a new 2048-bit SSH key-pair and store it:\n  `safe ssh {{2048}} {{path/to/secret}}`\n- Set non-sensitive keys for a secret:\n  `safe set {{path/to/secret}} {{key}}={{value}}`\n- Set auto-generated password in a secret:\n  `safe gen {{path/to/secret}} {{key}}`\n\n*Source: tldr-pages*\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **WARNING**\n- **METHODS** (9 subsections)\n- **RISKS**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Safe",
        "section": "",
        "mode": "man",
        "summary": "Safe - Compile and execute code in restricted compartments",
        "synopsis": "use Safe;\n$compartment = new Safe;\n$compartment->permit(qw(time sort :browse));\n$result = $compartment->reval($unsafecode);",
        "tldr_summary": "Interact with HashiCorp Vault.",
        "tldr_examples": [
            {
                "description": "Add a safe target",
                "command": "safe target {{vault_addr}} {{target_name}}"
            },
            {
                "description": "Authenticate the CLI client against the Vault server, using an authentication token",
                "command": "safe auth {{authentication_token}}"
            },
            {
                "description": "Print the environment variables describing the current target",
                "command": "safe env"
            },
            {
                "description": "Display a tree hierarchy of all reachable keys for a given path",
                "command": "safe tree {{path}}"
            },
            {
                "description": "Move a secret from one path to another",
                "command": "safe move {{path/to/old_secret}} {{path/to/new_secret}}"
            },
            {
                "description": "Generate a new 2048-bit SSH key-pair and store it",
                "command": "safe ssh {{2048}} {{path/to/secret}}"
            },
            {
                "description": "Set non-sensitive keys for a secret",
                "command": "safe set {{path/to/secret}} {{key}}={{value}}"
            },
            {
                "description": "Set auto-generated password in a secret",
                "command": "safe gen {{path/to/secret}} {{key}}"
            }
        ],
        "tldr_source": "official",
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 8,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 42,
                "subsections": []
            },
            {
                "name": "WARNING",
                "lines": 14,
                "subsections": []
            },
            {
                "name": "METHODS",
                "lines": 14,
                "subsections": [
                    {
                        "name": "permit (OP, ...)",
                        "lines": 9
                    },
                    {
                        "name": "deny (OP, ...)",
                        "lines": 7
                    },
                    {
                        "name": "trap (OP, ...), untrap (OP, ...)",
                        "lines": 2
                    },
                    {
                        "name": "share (NAME, ...)",
                        "lines": 26
                    },
                    {
                        "name": "varglob (VARNAME)",
                        "lines": 13
                    },
                    {
                        "name": "reval (STRING, STRICT)",
                        "lines": 52
                    },
                    {
                        "name": "rdo (FILENAME)",
                        "lines": 5
                    },
                    {
                        "name": "root (NAMESPACE)",
                        "lines": 6
                    },
                    {
                        "name": "mask (MASK)",
                        "lines": 27
                    }
                ]
            },
            {
                "name": "RISKS",
                "lines": 24,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 9,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Safe - Compile and execute code in restricted compartments\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use Safe;\n\n$compartment = new Safe;\n\n$compartment->permit(qw(time sort :browse));\n\n$result = $compartment->reval($unsafecode);\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "The Safe extension module allows the creation of compartments in which perl code can be\nevaluated. Each compartment has\n\na new namespace\nThe \"root\" of the namespace (i.e. \"main::\") is changed to a different package and\ncode evaluated in the compartment cannot refer to variables outside this namespace,\neven with run-time glob lookups and other tricks.\n\nCode which is compiled outside the compartment can choose to place variables into (or\nshare variables with) the compartment's namespace and only that data will be visible\nto code evaluated in the compartment.\n\nBy default, the only variables shared with compartments are the \"underscore\"\nvariables $ and @ (and, technically, the less frequently used %, the  filehandle\nand so on). This is because otherwise perl operators which default to $ will not\nwork and neither will the assignment of arguments to @ on subroutine entry.\n\nan operator mask\nEach compartment has an associated \"operator mask\". Recall that perl code is compiled\ninto an internal format before execution.  Evaluating perl code (e.g. via \"eval\" or\n\"do 'file'\") causes the code to be compiled into an internal format and then,\nprovided there was no error in the compilation, executed.  Code evaluated in a\ncompartment compiles subject to the compartment's operator mask. Attempting to\nevaluate code in a compartment which contains a masked operator will cause the\ncompilation to fail with an error. The code will not be executed.\n\nThe default operator mask for a newly created compartment is the ':default' optag.\n\nIt is important that you read the Opcode module documentation for more information,\nespecially for detailed definitions of opnames, optags and opsets.\n\nSince it is only at the compilation stage that the operator mask applies, controlled\naccess to potentially unsafe operations can be achieved by having a handle to a\nwrapper subroutine (written outside the compartment) placed into the compartment. For\nexample,\n\n$cpt = new Safe;\nsub wrapper {\n# vet arguments and perform potentially unsafe operations\n}\n$cpt->share('&wrapper');\n",
                "subsections": []
            },
            "WARNING": {
                "content": "The Safe module does not implement an effective sandbox for evaluating untrusted code with\nthe perl interpreter.\n\nBugs in the perl interpreter that could be abused to bypass Safe restrictions are not treated\nas vulnerabilities. See perlsecpolicy for additional information.\n\nThe authors make no warranty, implied or otherwise, about the suitability of this software\nfor safety or security purposes.\n\nThe authors shall not in any case be liable for special, incidental, consequential, indirect\nor other similar damages arising from the use of this software.\n\nYour mileage will vary. If in any doubt do not use it.\n",
                "subsections": []
            },
            "METHODS": {
                "content": "To create a new compartment, use\n\n$cpt = new Safe;\n\nOptional argument is (NAMESPACE), where NAMESPACE is the root namespace to use for the\ncompartment (defaults to \"Safe::Root0\", incremented for each new compartment).\n\nNote that version 1.00 of the Safe module supported a second optional parameter, MASK.  That\nfunctionality has been withdrawn pending deeper consideration. Use the permit and deny\nmethods described below.\n\nThe following methods can then be used on the compartment object returned by the above\nconstructor. The object argument is implicit in each case.\n",
                "subsections": [
                    {
                        "name": "permit (OP, ...)",
                        "content": "Permit the listed operators to be used when compiling code in the compartment (in addition to\nany operators already permitted).\n\nYou can list opcodes by names, or use a tag name; see \"Predefined Opcode Tags\" in Opcode.\n\npermitonly (OP, ...)\nPermit only the listed operators to be used when compiling code in the compartment (no other\noperators are permitted).\n"
                    },
                    {
                        "name": "deny (OP, ...)",
                        "content": "Deny the listed operators from being used when compiling code in the compartment (other\noperators may still be permitted).\n\ndenyonly (OP, ...)\nDeny only the listed operators from being used when compiling code in the compartment (all\nother operators will be permitted, so you probably don't want to use this method).\n"
                    },
                    {
                        "name": "trap (OP, ...), untrap (OP, ...)",
                        "content": "The trap and untrap methods are synonyms for deny and permit respectfully.\n"
                    },
                    {
                        "name": "share (NAME, ...)",
                        "content": "This shares the variable(s) in the argument list with the compartment.  This is almost\nidentical to exporting variables using the Exporter module.\n\nEach NAME must be the name of a non-lexical variable, typically with the leading type\nidentifier included. A bareword is treated as a function name.\n\nExamples of legal names are '$foo' for a scalar, '@foo' for an array, '%foo' for a hash,\n'&foo' or 'foo' for a subroutine and '*foo' for a glob (i.e.  all symbol table entries\nassociated with \"foo\", including scalar, array, hash, sub and filehandle).\n\nEach NAME is assumed to be in the calling package. See sharefrom for an alternative method\n(which \"share\" uses).\n\nsharefrom (PACKAGE, ARRAYREF)\nThis method is similar to share() but allows you to explicitly name the package that symbols\nshould be shared from. The symbol names (including type characters) are supplied as an array\nreference.\n\n$safe->sharefrom('main', [ '$foo', '%bar', 'func' ]);\n\nNames can include package names, which are relative to the specified PACKAGE.  So these two\ncalls have the same effect:\n\n$safe->sharefrom('Scalar::Util', [ 'reftype' ]);\n$safe->sharefrom('main', [ 'Scalar::Util::reftype' ]);\n"
                    },
                    {
                        "name": "varglob (VARNAME)",
                        "content": "This returns a glob reference for the symbol table entry of VARNAME in the package of the\ncompartment. VARNAME must be the name of a variable without any leading type marker. For\nexample:\n\n${$cpt->varglob('foo')} = \"Hello world\";\n\nhas the same effect as:\n\n$cpt = new Safe 'Root';\n$Root::foo = \"Hello world\";\n\nbut avoids the need to know $cpt's package name.\n"
                    },
                    {
                        "name": "reval (STRING, STRICT)",
                        "content": "This evaluates STRING as perl code inside the compartment.\n\nThe code can only see the compartment's namespace (as returned by the root method). The\ncompartment's root package appears to be the \"main::\" package to the code inside the\ncompartment.\n\nAny attempt by the code in STRING to use an operator which is not permitted by the\ncompartment will cause an error (at run-time of the main program but at compile-time for the\ncode in STRING).  The error is of the form \"'%s' trapped by operation mask...\".\n\nIf an operation is trapped in this way, then the code in STRING will not be executed. If such\na trapped operation occurs or any other compile-time or return error, then $@ is set to the\nerror message, just as with an eval().\n\nIf there is no error, then the method returns the value of the last expression evaluated, or\na return statement may be used, just as with subroutines and eval(). The context (list or\nscalar) is determined by the caller as usual.\n\nIf the return value of reval() is (or contains) any code reference, those code references are\nwrapped to be themselves executed always in the compartment. See \"wrapcoderefswithin\".\n\nThe formerly undocumented STRICT argument sets strictness: if true 'use strict;' is used,\notherwise it uses 'no strict;'. Note: if STRICT is omitted 'no strict;' is the default.\n\nSome points to note:\n\nIf the entereval op is permitted then the code can use eval \"...\" to 'hide' code which might\nuse denied ops. This is not a major problem since when the code tries to execute the eval it\nwill fail because the opmask is still in effect. However this technique would allow clever,\nand possibly harmful, code to 'probe' the boundaries of what is possible.\n\nAny string eval which is executed by code executing in a compartment, or by code called from\ncode executing in a compartment, will be eval'd in the namespace of the compartment. This is\npotentially a serious problem.\n\nConsider a function foo() in package pkg compiled outside a compartment but shared with it.\nAssume the compartment has a root package called 'Root'. If foo() contains an eval statement\nlike eval '$foo = 1' then, normally, $pkg::foo will be set to 1.  If foo() is called from the\ncompartment (by whatever means) then instead of setting $pkg::foo, the eval will actually set\n$Root::pkg::foo.\n\nThis can easily be demonstrated by using a module, such as the Socket module, which uses eval\n\"...\" as part of an AUTOLOAD function. You can 'use' the module outside the compartment and\nshare an (autoloaded) function with the compartment. If an autoload is triggered by code in\nthe compartment, or by any code anywhere that is called by any means from the compartment,\nthen the eval in the Socket module's AUTOLOAD function happens in the namespace of the\ncompartment. Any variables created or used by the eval'd code are now under the control of\nthe code in the compartment.\n\nA similar effect applies to all runtime symbol lookups in code called from a compartment but\nnot compiled within it.\n"
                    },
                    {
                        "name": "rdo (FILENAME)",
                        "content": "This evaluates the contents of file FILENAME inside the compartment.  It uses the same rules\nas perl's built-in \"do\" to locate the file, poossibly using @INC.\n\nSee above documentation on the reval method for further details.\n"
                    },
                    {
                        "name": "root (NAMESPACE)",
                        "content": "This method returns the name of the package that is the root of the compartment's namespace.\n\nNote that this behaviour differs from version 1.00 of the Safe module where the root module\ncould be used to change the namespace. That functionality has been withdrawn pending deeper\nconsideration.\n"
                    },
                    {
                        "name": "mask (MASK)",
                        "content": "This is a get-or-set method for the compartment's operator mask.\n\nWith no MASK argument present, it returns the current operator mask of the compartment.\n\nWith the MASK argument present, it sets the operator mask for the compartment (equivalent to\ncalling the denyonly method).\n\nwrapcoderef (CODEREF)\nReturns a reference to an anonymous subroutine that, when executed, will call CODEREF with\nthe Safe compartment 'in effect'.  In other words, with the package namespace adjusted and\nthe opmask enabled.\n\nNote that the opmask doesn't affect the already compiled code, it only affects any further\ncompilation that the already compiled code may try to perform.\n\nThis is particularly useful when applied to code references returned from reval().\n\n(It also provides a kind of workaround for RT#60374: \"Safe.pm sort {} bug with -Dusethreads\".\nSee <https://rt.perl.org/rt3//Public/Bug/Display.html?id=60374> for much more detail.)\n\nwrapcoderefswithin (...)\nWraps any CODE references found within the arguments by replacing each with the result of\ncalling \"wrapcoderef\" on the CODE reference. Any ARRAY or HASH references in the arguments\nare inspected recursively.\n\nReturns nothing.\n"
                    }
                ]
            },
            "RISKS": {
                "content": "This section is just an outline of some of the things code in a compartment might do\n(intentionally or unintentionally) which can have an effect outside the compartment.\n\nMemory  Consuming all (or nearly all) available memory.\n\nCPU     Causing infinite loops etc.\n\nSnooping\nCopying private information out of your system. Even something as simple as your user\nname is of value to others. Much useful information could be gleaned from your\nenvironment variables for example.\n\nSignals Causing signals (especially SIGFPE and SIGALARM) to affect your process.\n\nSetting up a signal handler will need to be carefully considered and controlled.\nWhat mask is in effect when a signal handler gets called?  If a user can get an\nimported function to get an exception and call the user's signal handler, does that\nuser's restricted mask get re-instated before the handler is called?  Does an\nimported handler get called with its original mask or the user's one?\n\nState Changes\nOps such as chdir obviously effect the process as a whole and not just the code in\nthe compartment. Ops such as rand and srand have a similar but more subtle effect.\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Originally designed and implemented by Malcolm Beattie.\n\nReworked to use the Opcode module and other changes added by Tim Bunce.\n\nCurrently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.\n\n\n\nperl v5.34.0                                 2025-07-25                                  Safe(3perl)",
                "subsections": []
            }
        }
    }
}