View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2013-2024, VU University Amsterdam
    7                              CWI, Amsterdam
    8                              SWI-Prolog Solutions b.v
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(sandbox,
   38          [ safe_goal/1,                % :Goal
   39            safe_call/1                 % :Goal
   40          ]).   41:- use_module(library(apply_macros),[expand_phrase/2]).   42:- use_module(library(apply),[maplist/2]).   43:- use_module(library(assoc),[empty_assoc/1,get_assoc/3,put_assoc/4]).   44:- use_module(library(debug),[debug/3,debugging/1]).   45:- use_module(library(error),
   46              [ must_be/2,
   47                instantiation_error/1,
   48                type_error/2,
   49                permission_error/3
   50              ]).   51:- use_module(library(lists),[append/3]).   52:- use_module(library(prolog_format),[format_types/2]).   53
   54:- multifile
   55    safe_primitive/1,               % Goal
   56    safe_meta_predicate/1,          % Name/Arity
   57    safe_meta/2,                    % Goal, Calls
   58    safe_meta/3,                    % Goal, Context, Calls
   59    safe_global_variable/1,         % Name
   60    safe_directive/1,               % Module:Goal
   61    safe_prolog_flag/2.             % +Name, +Value
   62
   63% :- debug(sandbox).

Sandboxed Prolog code

Prolog is a full-featured Turing complete programming language in which it is easy to write programs that can harm your computer. On the other hand, Prolog is a logic based query language which can be exploited to query data interactively from, e.g., the web. This library provides safe_goal/1, which determines whether it is safe to call its argument.

See also
- http://www.swi-prolog.org/pldoc/package/pengines.html
To be done
- Handling of ^ and // meta predicates
- Complete set of whitelisted predicates
   79:- meta_predicate
   80    safe_goal(:),
   81    safe_call(0).
 safe_call(:Goal)
Call Goal if it complies with the sandboxing rules. Before calling Goal, it performs expand_goal/2, followed by safe_goal/1. Expanding is done explicitly because situations in which safe_call/1 typically concern goals that are not known at compile time.
See also
- safe_goal/1.
   93safe_call(Goal0) :-
   94    expand_goal(Goal0, Goal),
   95    safe_goal(Goal),
   96    call(Goal).
 safe_goal(:Goal) is det
True if calling Goal provides no security risc. This implies that:
Errors
- instantiation_error if the analysis encounters a term in a callable position that is insufficiently instantiated to determine the predicate called.
- permission_error(call, sandboxed, Goal) if Goal is in the call-tree and not white-listed.
  120safe_goal(M:Goal) :-
  121    empty_assoc(Safe0),
  122    catch(safe(Goal, M, [], Safe0, _), E, true),
  123    !,
  124    nb_delete(sandbox_last_error),
  125    (   var(E)
  126    ->  true
  127    ;   throw(E)
  128    ).
  129safe_goal(_) :-
  130    nb_current(sandbox_last_error, E),
  131    !,
  132    nb_delete(sandbox_last_error),
  133    throw(E).
  134safe_goal(G) :-
  135    debug(sandbox(fail), 'safe_goal/1 failed for ~p', [G]),
  136    throw(error(instantiation_error, sandbox(G, []))).
 safe(+Goal, +Module, +Parents, +Safe0, -Safe) is semidet
Is true if Goal can only call safe code.
  143safe(V, _, Parents, _, _) :-
  144    var(V),
  145    !,
  146    Error = error(instantiation_error, sandbox(V, Parents)),
  147    nb_setval(sandbox_last_error, Error),
  148    throw(Error).
  149safe(M:G, _, Parents, Safe0, Safe) :-
  150    !,
  151    must_be(atom, M),
  152    must_be(callable, G),
  153    known_module(M:G, Parents),
  154    (   predicate_property(M:G, imported_from(M2))
  155    ->  true
  156    ;   M2 = M
  157    ),
  158    (   (   safe_primitive(M2:G)
  159        ;   safe_primitive(G),
  160            predicate_property(G, iso)
  161        )
  162    ->  Safe = Safe0
  163    ;   (   predicate_property(M:G, exported)
  164        ;   predicate_property(M:G, public)
  165        ;   predicate_property(M:G, multifile)
  166        ;   predicate_property(M:G, iso)
  167        ;   memberchk(M:_, Parents)
  168        )
  169    ->  safe(G, M, Parents, Safe0, Safe)
  170    ;   throw(error(permission_error(call, sandboxed, M:G),
  171                    sandbox(M:G, Parents)))
  172    ).
  173safe(G, _, Parents, _, _) :-
  174    debugging(sandbox(show)),
  175    length(Parents, Level),
  176    debug(sandbox(show), '[~D] SAFE ~q?', [Level, G]),
  177    fail.
  178safe(G, _, Parents, Safe, Safe) :-
  179    catch(safe_primitive(G),
  180          error(instantiation_error, _),
  181          rethrow_instantition_error([G|Parents])),
  182    predicate_property(G, iso),
  183    !.
  184safe(G, M, Parents, Safe, Safe) :-
  185    known_module(M:G, Parents),
  186    (   predicate_property(M:G, imported_from(M2))
  187    ->  true
  188    ;   M2 = M
  189    ),
  190    (   catch(safe_primitive(M2:G),
  191              error(instantiation_error, _),
  192              rethrow_instantition_error([M2:G|Parents]))
  193    ;   predicate_property(M2:G, number_of_rules(0))
  194    ),
  195    !.
  196safe(G, M, Parents, Safe0, Safe) :-
  197    predicate_property(G, iso),
  198    safe_meta_call(G, M, Called),
  199    !,
  200    add_iso_parent(G, Parents, Parents1),
  201    safe_list(Called, M, Parents1, Safe0, Safe).
  202safe(G, M, Parents, Safe0, Safe) :-
  203    (   predicate_property(M:G, imported_from(M2))
  204    ->  true
  205    ;   M2 = M
  206    ),
  207    safe_meta_call(M2:G, M, Called),
  208    !,
  209    safe_list(Called, M, Parents, Safe0, Safe).
  210safe(G, M, Parents, Safe0, Safe) :-
  211    goal_id(M:G, Id, Gen),
  212    (   get_assoc(Id, Safe0, _)
  213    ->  Safe = Safe0
  214    ;   put_assoc(Id, Safe0, true, Safe1),
  215        (   Gen == M:G
  216        ->  safe_clauses(Gen, M, [Id|Parents], Safe1, Safe)
  217        ;   catch(safe_clauses(Gen, M, [Id|Parents], Safe1, Safe),
  218                  error(instantiation_error, Ctx),
  219                  unsafe(Parents, Ctx))
  220        )
  221    ),
  222    !.
  223safe(G, M, Parents, _, _) :-
  224    debug(sandbox(fail),
  225          'safe/1 failed for ~p (parents:~p)', [M:G, Parents]),
  226    fail.
  227
  228unsafe(Parents, Var) :-
  229    var(Var),
  230    !,
  231    nb_setval(sandbox_last_error,
  232              error(instantiation_error, sandbox(_, Parents))),
  233    fail.
  234unsafe(_Parents, Ctx) :-
  235    Ctx = sandbox(_,_),
  236    nb_setval(sandbox_last_error,
  237              error(instantiation_error, Ctx)),
  238    fail.
  239
  240rethrow_instantition_error(Parents) :-
  241    throw(error(instantiation_error, sandbox(_, Parents))).
  242
  243safe_clauses(G, M, Parents, Safe0, Safe) :-
  244    predicate_property(M:G, interpreted),
  245    def_module(M:G, MD:QG),
  246    \+ compiled(MD:QG),
  247    !,
  248    findall(Ref-Body, clause(MD:QG, Body, Ref), Bodies),
  249    safe_bodies(Bodies, MD, Parents, Safe0, Safe).
  250safe_clauses(G, M, [_|Parents], _, _) :-
  251    predicate_property(M:G, visible),
  252    !,
  253    throw(error(permission_error(call, sandboxed, G),
  254                sandbox(M:G, Parents))).
  255safe_clauses(_, _, [G|Parents], _, _) :-
  256    throw(error(existence_error(procedure, G),
  257                sandbox(G, Parents))).
  258
  259compiled(system:(@(_,_))).
  260
  261known_module(M:_, _) :-
  262    current_module(M),
  263    !.
  264known_module(M:G, Parents) :-
  265    throw(error(permission_error(call, sandboxed, M:G),
  266                sandbox(M:G, Parents))).
  267
  268add_iso_parent(G, Parents, Parents) :-
  269    is_control(G),
  270    !.
  271add_iso_parent(G, Parents, [G|Parents]).
  272
  273is_control((_,_)).
  274is_control((_;_)).
  275is_control((_->_)).
  276is_control((_*->_)).
  277is_control(\+(_)).
 safe_bodies(+Bodies, +Module, +Parents, +Safe0, -Safe)
Verify the safety of bodies. If a clause was compiled with a qualified module, we consider execution of the body in a different module not a cross-module call.
  286safe_bodies([], _, _, Safe, Safe).
  287safe_bodies([Ref-H|T], M, Parents, Safe0, Safe) :-
  288    (   H = M2:H2, nonvar(M2),
  289        clause_property(Ref, module(M2))
  290    ->  copy_term(H2, H3),
  291        CM = M2
  292    ;   copy_term(H, H3),
  293        CM = M
  294    ),
  295    safe(H3, CM, Parents, Safe0, Safe1),
  296    safe_bodies(T, M, Parents, Safe1, Safe).
  297
  298def_module(M:G, MD:QG) :-
  299    predicate_property(M:G, imported_from(MD)),
  300    !,
  301    meta_qualify(MD:G, M, QG).
  302def_module(M:G, M:QG) :-
  303    meta_qualify(M:G, M, QG).
 safe_list(+Called, +Module, +Parents, +Safe0, -Safe)
Processed objects called through meta predicates. If the called object is in our current context we remove the module qualification to avoid the cross-module check.
  311safe_list([], _, _, Safe, Safe).
  312safe_list([H|T], M, Parents, Safe0, Safe) :-
  313    (   H = M2:H2,
  314        M == M2                             % in our context
  315    ->  copy_term(H2, H3)
  316    ;   copy_term(H, H3)                    % cross-module call
  317    ),
  318    safe(H3, M, Parents, Safe0, Safe1),
  319    safe_list(T, M, Parents, Safe1, Safe).
 meta_qualify(:G, +M, -QG) is det
Perform meta-qualification of the goal-argument
  325meta_qualify(MD:G, M, QG) :-
  326    predicate_property(MD:G, meta_predicate(Head)),
  327    !,
  328    G =.. [Name|Args],
  329    Head =.. [_|Q],
  330    qualify_args(Q, M, Args, QArgs),
  331    QG =.. [Name|QArgs].
  332meta_qualify(_:G, _, G).
  333
  334qualify_args([], _, [], []).
  335qualify_args([H|T], M, [A|AT], [Q|QT]) :-
  336    qualify_arg(H, M, A, Q),
  337    qualify_args(T, M, AT, QT).
  338
  339qualify_arg(S, M, A, Q) :-
  340    q_arg(S),
  341    !,
  342    qualify(A, M, Q).
  343qualify_arg(_, _, A, A).
  344
  345q_arg(I) :- integer(I), !.
  346q_arg(:).
  347q_arg(^).
  348q_arg(//).
  349
  350qualify(A, M, MZ:Q) :-
  351    strip_module(M:A, MZ, Q).
 goal_id(:Goal, -Id, -Gen) is nondet
Generate an identifier for the goal proven to be safe. We first try to prove the most general form of the goal. If this fails, we try to prove more specific versions.
To be done
- Do step-by-step generalisation instead of the current two levels (most general and most specific).
- We could also use variant_sha1 for the goal ids.
  363goal_id(M:Goal, M:Id, Gen) :-
  364    !,
  365    goal_id(Goal, Id, Gen).
  366goal_id(Var, _, _) :-
  367    var(Var),
  368    !,
  369    instantiation_error(Var).
  370goal_id(Atom, Atom, Atom) :-
  371    atom(Atom),
  372    !.
  373goal_id(Term, _, _) :-
  374    \+ compound(Term),
  375    !,
  376    type_error(callable, Term).
  377goal_id(Term, Skolem, Gen) :-           % most general form
  378    compound_name_arity(Term, Name, Arity),
  379    compound_name_arity(Skolem, Name, Arity),
  380    compound_name_arity(Gen, Name, Arity),
  381    copy_goal_args(1, Term, Skolem, Gen),
  382    (   Gen =@= Term
  383    ->  !                           % No more specific one; we can commit
  384    ;   true
  385    ),
  386    numbervars(Skolem, 0, _).
  387goal_id(Term, Skolem, Term) :-          % most specific form
  388    debug(sandbox(specify), 'Retrying with ~p', [Term]),
  389    copy_term(Term, Skolem),
  390    numbervars(Skolem, 0, _).
 copy_goal_args(+I, +Term, +Skolem, +Gen) is det
Create the most general form, but keep module qualified arguments because they will likely be called anyway.
  397copy_goal_args(I, Term, Skolem, Gen) :-
  398    arg(I, Term, TA),
  399    !,
  400    arg(I, Skolem, SA),
  401    arg(I, Gen, GA),
  402    copy_goal_arg(TA, SA, GA),
  403    I2 is I + 1,
  404    copy_goal_args(I2, Term, Skolem, Gen).
  405copy_goal_args(_, _, _, _).
  406
  407copy_goal_arg(Arg, SArg, Arg) :-
  408    copy_goal_arg(Arg),
  409    !,
  410    copy_term(Arg, SArg).
  411copy_goal_arg(_, _, _).
  412
  413copy_goal_arg(Var) :- var(Var), !, fail.
  414copy_goal_arg(_:_).
 verify_safe_declaration(+Decl)
See whether a safe declaration makes sense. That is, the predicate must be defined (such that the attacker cannot define the predicate), must be sufficiently instantiated and only ISO declared predicates may omit a module qualification.
To be done
- Verify safe_meta/2 declarations. It is a bit less clear what the rules are.
  426term_expansion(safe_primitive(Goal), Term) :-
  427    (   verify_safe_declaration(Goal)
  428    ->  Term = safe_primitive(Goal)
  429    ;   Term = []
  430    ).
  431term_expansion((safe_primitive(Goal) :- Body), Term) :-
  432    (   verify_safe_declaration(Goal)
  433    ->  Term = (safe_primitive(Goal) :- Body)
  434    ;   Term = []
  435    ).
  436
  437system:term_expansion(sandbox:safe_primitive(Goal), Term) :-
  438    \+ current_prolog_flag(xref, true),
  439    (   verify_safe_declaration(Goal)
  440    ->  Term = sandbox:safe_primitive(Goal)
  441    ;   Term = []
  442    ).
  443system:term_expansion((sandbox:safe_primitive(Goal) :- Body), Term) :-
  444    \+ current_prolog_flag(xref, true),
  445    (   verify_safe_declaration(Goal)
  446    ->  Term = (sandbox:safe_primitive(Goal) :- Body)
  447    ;   Term = []
  448    ).
  449
  450verify_safe_declaration(Var) :-
  451    var(Var),
  452    !,
  453    instantiation_error(Var).
  454verify_safe_declaration(Module:Goal) :-
  455    !,
  456    must_be(atom, Module),
  457    must_be(callable, Goal),
  458    (   ok_meta(Module:Goal)
  459    ->  true
  460    ;   (   predicate_property(Module:Goal, visible)
  461        ->  true
  462        ;   predicate_property(Module:Goal, foreign)
  463        ),
  464        \+ predicate_property(Module:Goal, imported_from(_)),
  465        \+ predicate_property(Module:Goal, meta_predicate(_))
  466    ->  true
  467    ;   permission_error(declare, safe_goal, Module:Goal)
  468    ).
  469verify_safe_declaration(Goal) :-
  470    must_be(callable, Goal),
  471    (   predicate_property(system:Goal, iso),
  472        \+ predicate_property(system:Goal, meta_predicate())
  473    ->  true
  474    ;   permission_error(declare, safe_goal, Goal)
  475    ).
  476
  477ok_meta(system:assert(_)).
  478ok_meta(system:load_files(_,_)).
  479ok_meta(system:use_module(_,_)).
  480ok_meta(system:use_module(_)).
  481ok_meta('$syspreds':predicate_property(_,_)).
  482
  483verify_predefined_safe_declarations :-
  484    forall(clause(safe_primitive(Goal), _Body, Ref),
  485           ( E = error(F,_),
  486             catch(verify_safe_declaration(Goal), E, true),
  487             (   nonvar(F)
  488             ->  clause_property(Ref, file(File)),
  489                 clause_property(Ref, line_count(Line)),
  490                 print_message(error, bad_safe_declaration(Goal, File, Line))
  491             ;   true
  492             )
  493           )).
  494
  495:- initialization(verify_predefined_safe_declarations, now).
 safe_primitive(?Goal) is nondet
True if Goal is safe to call (i.e., cannot access dangerous system-resources and cannot upset other parts of the Prolog process). There are two types of facts. ISO built-ins are declared without a module prefix. This is safe because it is not allowed to (re-)define these primitives (i.e., give them an unsafe implementation) and the way around (redefine_system_predicate/1) is unsafe. The other group are module-qualified and only match if the system infers that the predicate is imported from the given module.
  509% First, all ISO system predicates that are considered safe
  510
  511safe_primitive(true).
  512safe_primitive(fail).
  513safe_primitive(system:false).
  514safe_primitive(repeat).
  515safe_primitive(!).
  516                                        % types
  517safe_primitive(var(_)).
  518safe_primitive(nonvar(_)).
  519safe_primitive(system:attvar(_)).
  520safe_primitive(integer(_)).
  521safe_primitive(float(_)).
  522:- if(current_predicate(rational/1)).  523safe_primitive(system:rational(_)).
  524safe_primitive(system:rational(_,_,_)).
  525:- endif.  526safe_primitive(number(_)).
  527safe_primitive(atom(_)).
  528safe_primitive(system:blob(_,_)).
  529safe_primitive(system:string(_)).
  530safe_primitive(atomic(_)).
  531safe_primitive(compound(_)).
  532safe_primitive(callable(_)).
  533safe_primitive(ground(_)).
  534safe_primitive(system:nonground(_,_)).
  535safe_primitive(system:cyclic_term(_)).
  536safe_primitive(acyclic_term(_)).
  537safe_primitive(system:is_stream(_)).
  538safe_primitive(system:is_address(_)).
  539safe_primitive(system:'$is_char'(_)).
  540safe_primitive(system:'$is_char_code'(_)).
  541safe_primitive(system:'$is_char_list'(_,_)).
  542safe_primitive(system:'$is_code_list'(_,_)).
  543                                        % ordering
  544safe_primitive(@>(_,_)).
  545safe_primitive(@>=(_,_)).
  546safe_primitive(==(_,_)).
  547safe_primitive(@<(_,_)).
  548safe_primitive(@=<(_,_)).
  549safe_primitive(compare(_,_,_)).
  550safe_primitive(sort(_,_)).
  551safe_primitive(keysort(_,_)).
  552safe_primitive(system: =@=(_,_)).
  553safe_primitive(system:'$btree_find_node'(_,_,_,_,_)).
  554
  555                                        % unification and equivalence
  556safe_primitive(=(_,_)).
  557safe_primitive(\=(_,_)).
  558safe_primitive(system:'?='(_,_)).
  559safe_primitive(system:unifiable(_,_,_)).
  560safe_primitive(unify_with_occurs_check(_,_)).
  561safe_primitive(\==(_,_)).
  562                                        % arithmetic
  563safe_primitive(is(_,_)).
  564safe_primitive(>(_,_)).
  565safe_primitive(>=(_,_)).
  566safe_primitive(=:=(_,_)).
  567safe_primitive(=\=(_,_)).
  568safe_primitive(=<(_,_)).
  569safe_primitive(<(_,_)).
  570:- if(current_prolog_flag(bounded, false)).  571safe_primitive(system:nth_integer_root_and_remainder(_,_,_,_)).
  572:- endif.  573safe_primitive(system:current_arithmetic_function(_)).
  574safe_primitive(system:bounded_number(_,_,_)).
  575safe_primitive(system:float_class(_,_)).
  576safe_primitive(system:float_parts(_,_,_,_)).
  577
  578                                        % term-handling
  579safe_primitive(arg(_,_,_)).
  580safe_primitive(system:setarg(_,_,_)).
  581safe_primitive(system:nb_setarg(_,_,_)).
  582safe_primitive(system:nb_linkarg(_,_,_)).
  583safe_primitive(functor(_,_,_)).
  584safe_primitive(system:functor(_,_,_,_)).
  585safe_primitive(_ =.. _).
  586safe_primitive(system:compound_name_arity(_,_,_)).
  587safe_primitive(system:compound_name_arguments(_,_,_)).
  588safe_primitive(system:'$filled_array'(_,_,_,_)).
  589safe_primitive(copy_term(_,_)).
  590safe_primitive(system:copy_term(_,_,_,_)).
  591safe_primitive(system:duplicate_term(_,_)).
  592safe_primitive(system:copy_term_nat(_,_)).
  593safe_primitive(system:size_abstract_term(_,_,_)).
  594safe_primitive(numbervars(_,_,_)).
  595safe_primitive(system:numbervars(_,_,_,_)).
  596safe_primitive(subsumes_term(_,_)).
  597safe_primitive(system:term_hash(_,_)).
  598safe_primitive(system:term_hash(_,_,_,_)).
  599safe_primitive(system:variant_sha1(_,_)).
  600safe_primitive(system:variant_hash(_,_)).
  601safe_primitive(system:'$term_size'(_,_,_)).
  602
  603                                        % dicts
  604safe_primitive(system:is_dict(_)).
  605safe_primitive(system:is_dict(_,_)).
  606safe_primitive(system:get_dict(_,_,_)).
  607safe_primitive(system:get_dict(_,_,_,_,_)).
  608safe_primitive(system:'$get_dict_ex'(_,_,_)).
  609safe_primitive(system:dict_create(_,_,_)).
  610safe_primitive(system:dict_pairs(_,_,_)).
  611safe_primitive(system:put_dict(_,_,_)).
  612safe_primitive(system:put_dict(_,_,_,_)).
  613safe_primitive(system:del_dict(_,_,_,_)).
  614safe_primitive(system:select_dict(_,_,_)).
  615safe_primitive(system:b_set_dict(_,_,_)).
  616safe_primitive(system:nb_set_dict(_,_,_)).
  617safe_primitive(system:nb_link_dict(_,_,_)).
  618safe_primitive(system:(:<(_,_))).
  619safe_primitive(system:(>:<(_,_))).
  620                                        % atoms
  621safe_primitive(atom_chars(_, _)).
  622safe_primitive(atom_codes(_, _)).
  623safe_primitive(sub_atom(_,_,_,_,_)).
  624safe_primitive(atom_concat(_,_,_)).
  625safe_primitive(atom_length(_,_)).
  626safe_primitive(char_code(_,_)).
  627safe_primitive(system:name(_,_)).
  628safe_primitive(system:atomic_concat(_,_,_)).
  629safe_primitive(system:atomic_list_concat(_,_)).
  630safe_primitive(system:atomic_list_concat(_,_,_)).
  631safe_primitive(system:downcase_atom(_,_)).
  632safe_primitive(system:upcase_atom(_,_)).
  633safe_primitive(system:char_type(_,_)).
  634safe_primitive(system:normalize_space(_,_)).
  635safe_primitive(system:sub_atom_icasechk(_,_,_)).
  636                                        % numbers
  637safe_primitive(number_codes(_,_)).
  638safe_primitive(number_chars(_,_)).
  639safe_primitive(system:atom_number(_,_)).
  640safe_primitive(system:code_type(_,_)).
  641                                        % strings
  642safe_primitive(system:atom_string(_,_)).
  643safe_primitive(system:number_string(_,_)).
  644safe_primitive(system:string_chars(_, _)).
  645safe_primitive(system:string_codes(_, _)).
  646safe_primitive(system:string_code(_,_,_)).
  647safe_primitive(system:sub_string(_,_,_,_,_)).
  648safe_primitive(system:split_string(_,_,_,_)).
  649safe_primitive(system:atomics_to_string(_,_,_)).
  650safe_primitive(system:atomics_to_string(_,_)).
  651safe_primitive(system:string_concat(_,_,_)).
  652safe_primitive(system:string_length(_,_)).
  653safe_primitive(system:string_lower(_,_)).
  654safe_primitive(system:string_upper(_,_)).
  655safe_primitive(system:term_string(_,_)).
  656                                        % Lists
  657safe_primitive(length(_,_)).
  658                                        % exceptions
  659safe_primitive(throw(Ball)) :- safe_ball(Ball).
  660safe_primitive(system:abort).
  661                                        % misc
  662safe_primitive(current_prolog_flag(_,_)).
  663safe_primitive(current_op(_,_,_)).
  664safe_primitive(system:sleep(_)).
  665safe_primitive(system:thread_self(_)).
  666safe_primitive(system:get_time(_)).
  667safe_primitive(system:statistics(_,_)).
  668:- if(current_prolog_flag(threads,true)).  669safe_primitive(system:thread_statistics(Id,_,_)) :-
  670    (   var(Id)
  671    ->  instantiation_error(Id)
  672    ;   thread_self(Id)
  673    ).
  674safe_primitive(system:thread_property(Id,_)) :-
  675    (   var(Id)
  676    ->  instantiation_error(Id)
  677    ;   thread_self(Id)
  678    ).
  679:- endif.  680safe_primitive(system:format_time(_,_,_)).
  681safe_primitive(system:format_time(_,_,_,_)).
  682safe_primitive(system:date_time_stamp(_,_)).
  683safe_primitive(system:stamp_date_time(_,_,_)).
  684safe_primitive(system:strip_module(_,_,_)).
  685safe_primitive(system:import_module(_,_)).
  686safe_primitive(system:file_base_name(_,_)).
  687safe_primitive(system:file_directory_name(_,_)).
  688safe_primitive(system:file_name_extension(_,_,_)).
  689
  690safe_primitive(clause(H,_)) :- safe_clause(H).
  691safe_primitive(asserta(X)) :- safe_assert(X).
  692safe_primitive(assertz(X)) :- safe_assert(X).
  693safe_primitive(retract(X)) :- safe_assert(X).
  694safe_primitive(retractall(X)) :- safe_assert(X).
  695safe_primitive(current_predicate(X)) :- safe_current_predicate(X).
  696safe_primitive('$dcg':dcg_translate_rule(_,_)).
  697safe_primitive('$syspreds':predicate_property(Pred, _)) :-
  698    nonvar(Pred),
  699    Pred \= (_:_).
  700
  701% We need to do data flow analysis to find the tag of the
  702% target key before we can conclude that functions on dicts
  703% are safe.
  704safe_primitive('$dicts':'.'(_,K,_)) :- atom(K).
  705safe_primitive('$dicts':'.'(_,K,_)) :-
  706    (   nonvar(K)
  707    ->  dict_built_in(K)
  708    ;   instantiation_error(K)
  709    ).
  710
  711dict_built_in(get(_)).
  712dict_built_in(get(_,_)).
  713dict_built_in(put(_)).
  714dict_built_in(put(_,_)).
  715
  716% The non-ISO system predicates.  These can be redefined, so we must
  717% be careful to ensure the system ones are used.
  718
  719safe_primitive(system:false).
  720safe_primitive(system:cyclic_term(_)).
  721safe_primitive(system:msort(_,_)).
  722safe_primitive(system:sort(_,_,_,_)).
  723safe_primitive(system:between(_,_,_)).
  724safe_primitive(system:succ(_,_)).
  725safe_primitive(system:plus(_,_,_)).
  726safe_primitive(system:float_class(_,_)).
  727safe_primitive(system:term_singletons(_,_)).
  728safe_primitive(system:term_variables(_,_)).
  729safe_primitive(system:term_variables(_,_,_)).
  730safe_primitive(system:'$term_size'(_,_,_)).
  731safe_primitive(system:atom_to_term(_,_,_)).
  732safe_primitive(system:term_to_atom(_,_)).
  733safe_primitive(system:atomic_list_concat(_,_,_)).
  734safe_primitive(system:atomic_list_concat(_,_)).
  735safe_primitive(system:downcase_atom(_,_)).
  736safe_primitive(system:upcase_atom(_,_)).
  737safe_primitive(system:is_list(_)).
  738safe_primitive(system:memberchk(_,_)).
  739safe_primitive(system:'$skip_list'(_,_,_)).
  740safe_primitive(system:'$seek_list'(_, _, _, _)).
  741                                        % attributes
  742safe_primitive(system:get_attr(_,_,_)).
  743safe_primitive(system:get_attrs(_,_)).
  744safe_primitive(system:term_attvars(_,_)).
  745safe_primitive(system:del_attr(_,_)).
  746safe_primitive(system:del_attrs(_)).
  747safe_primitive('$attvar':copy_term(_,_,_)).
  748                                        % globals
  749safe_primitive(system:b_getval(_,_)).
  750safe_primitive(system:b_setval(Var,_)) :-
  751    safe_global_var(Var).
  752safe_primitive(system:nb_getval(_,_)).
  753safe_primitive(system:nb_setval(Var,_)) :-
  754    safe_global_var(Var).
  755safe_primitive(system:nb_linkval(Var,_)) :-
  756    safe_global_var(Var).
  757safe_primitive(system:nb_current(_,_)).
  758                                        % database
  759safe_primitive(system:assert(X)) :-
  760    safe_assert(X).
  761                                        % Output
  762safe_primitive(system:writeln(_)).
  763
  764                                        % Stack limits (down)
  765safe_primitive('$syspreds':set_prolog_stack(Stack, limit(ByteExpr))) :-
  766    nonvar(Stack),
  767    stack_name(Stack),
  768    catch(Bytes is ByteExpr, _, fail),
  769    prolog_stack_property(Stack, limit(Current)),
  770    Bytes =< Current.
  771
  772stack_name(global).
  773stack_name(local).
  774stack_name(trail).
  775
  776safe_primitive('$tabling':abolish_all_tables).
  777safe_primitive('$tabling':'$wrap_tabled'(Module:_Head, _Mode)) :-
  778    prolog_load_context(module, Module),
  779    !.
  780safe_primitive('$tabling':'$moded_wrap_tabled'(Module:_Head,_,_,_,_)) :-
  781    prolog_load_context(module, Module),
  782    !.
  783
  784
  785% use_module/1.  We only allow for .pl files that are loaded from
  786% relative paths that do not contain /../
  787
  788safe_primitive(system:use_module(Spec, _Import)) :-
  789    safe_primitive(system:use_module(Spec)).
  790safe_primitive(system:load_files(Spec, Options)) :-
  791    safe_primitive(system:use_module(Spec)),
  792    maplist(safe_load_file_option, Options).
  793safe_primitive(system:use_module(Spec)) :-
  794    ground(Spec),
  795    (   atom(Spec)
  796    ->  Path = Spec
  797    ;   Spec =.. [_Alias, Segments],
  798        phrase(segments_to_path(Segments), List),
  799        atomic_list_concat(List, Path)
  800    ),
  801    safe_relative_path(Path),
  802    absolute_file_name(Spec, AbsFile,
  803                       [ access(read),
  804                         file_type(prolog),
  805                         file_errors(fail)
  806                       ]),
  807    file_name_extension(_, Ext, AbsFile),
  808    save_extension(Ext).
  809
  810% support predicates for safe_primitive, validating the safety of
  811% arguments to certain goals.
  812
  813segments_to_path(A/B) -->
  814    !,
  815    segments_to_path(A),
  816    [/],
  817    segments_to_path(B).
  818segments_to_path(X) -->
  819    [X].
  820
  821save_extension(pl).
  822
  823safe_load_file_option(if(changed)).
  824safe_load_file_option(if(not_loaded)).
  825safe_load_file_option(must_be_module(_)).
  826safe_load_file_option(optimise(_)).
  827safe_load_file_option(silent(_)).
 safe_assert(+Term) is semidet
True if assert(Term) is safe, which means it asserts in the current module. Cross-module asserts are considered unsafe. We only allow for adding facts. In theory, we could also allow for rules if we prove the safety of the body.
  836safe_assert(C) :- cyclic_term(C), !, fail.
  837safe_assert(X) :- var(X), !, fail.
  838safe_assert(_Head:-_Body) :- !, fail.
  839safe_assert(_:_) :- !, fail.
  840safe_assert(_).
 safe_clause(+Head) is semidet
Consider a call to clause safe if it does not try to cross a module boundary. Cross-module usage of clause/2 can extract private information from other modules.
  848safe_clause(H) :- var(H), !.
  849safe_clause(_:_) :- !, fail.
  850safe_clause(_).
 safe_global_var(+Name) is semidet
True if Name is a global variable to which assertion is considered safe.
  858safe_global_var(Name) :-
  859    var(Name),
  860    !,
  861    instantiation_error(Name).
  862safe_global_var(Name) :-
  863    safe_global_variable(Name).
 safe_global_variable(Name) is semidet
Declare the given global variable safe to write to.
 safe_current_predicate(+X)
current_predicate/1 is safe when not used with qualification.
  873safe_current_predicate(X) :-
  874    nonvar(X),
  875    X = _:_, !,
  876    fail.
  877safe_current_predicate(_).
 safe_meta(+Goal, -Called:list(callable)) is semidet
Hook. True if Goal is a meta-predicate that is considered safe iff all elements in Called are safe.
  884safe_meta(system:put_attr(V,M,A), Called) :-
  885    !,
  886    (   atom(M)
  887    ->  attr_hook_predicates([ attr_unify_hook(A, _),
  888                               attribute_goals(V,_,_),
  889                               project_attributes(_,_)
  890                             ], M, Called)
  891    ;   instantiation_error(M)
  892    ).
  893safe_meta(system:with_output_to(Output, G), [G]) :-
  894    safe_output(Output),
  895    !.
  896safe_meta(system:write_term(_Term, Options), Calls) :-
  897    write_options_calls(Options, Calls).
  898safe_meta('$syspreds':term_string(_Term, _String, Options), Calls) :-
  899    write_options_calls(Options, Calls).
  900safe_meta('$messages':print_message(_Kind, Msg), Calls) :-
  901    message_calls(Msg, Calls).
  902safe_meta('$messages':message_to_string(Msg, _String), Calls) :-
  903    message_calls(Msg, Calls).
  904safe_meta(system:format(Format, Args), Calls) :-
  905    format_calls(Format, Args, Calls).
  906safe_meta(system:format(Output, Format, Args), Calls) :-
  907    safe_output(Output),
  908    format_calls(Format, Args, Calls).
  909safe_meta(prolog_debug:debug(_Term, Format, Args), Calls) :-
  910    format_calls(Format, Args, Calls).
  911safe_meta(system:set_prolog_flag(Flag, Value), []) :-
  912    atom(Flag),
  913    safe_prolog_flag(Flag, Value).
  914safe_meta('$attvar':freeze(_Var,Goal), [Goal]).
  915safe_meta(phrase(NT,Xs0,Xs), [Goal]) :- % phrase/2,3 and call_dcg/2,3
  916    expand_nt(NT,Xs0,Xs,Goal).
  917safe_meta(phrase(NT,Xs0), [Goal]) :-
  918    expand_nt(NT,Xs0,[],Goal).
  919safe_meta('$dcg':call_dcg(NT,Xs0,Xs), [Goal]) :-
  920    expand_nt(NT,Xs0,Xs,Goal).
  921safe_meta('$dcg':call_dcg(NT,Xs0), [Goal]) :-
  922    expand_nt(NT,Xs0,[],Goal).
  923safe_meta('$tabling':abolish_table_subgoals(V), []) :-
  924    \+ qualified(V).
  925safe_meta('$tabling':current_table(V, _), []) :-
  926    \+ qualified(V).
  927safe_meta('$tabling':tnot(G), [G]).
  928safe_meta(catch(G, Catcher, Recover), [G, Recover1]) :-
  929    caught(Catcher, Recover, Recover1).
  930safe_meta(system:setup_call_catcher_cleanup(S, G, Catcher, Cleanup),
  931          [S, G, Cleanup1]) :-
  932    caught(Catcher, Cleanup, Cleanup1).
  933safe_meta('$tabling':not_exists(G), [G]).
  934
  935qualified(V) :-
  936    nonvar(V),
  937    V = _:_.
 caught(+Catcher, +Handler, -Handler1) is det
Handler1 is a copy of Handler where the variables of Catcher are bound to '$sandbox_caught'. A caught exception is either raised by a system predicate or by throw/1 inside the analysed goal, which is verified by safe_ball/1. This allows for e.g. catch(G, E, (print_message(error, E), throw(E))).
  947caught(Catcher, Handler, Handler1) :-
  948    copy_term(Catcher-Handler, Catcher1-Handler1),
  949    term_variables(Catcher1, Vars),
  950    maplist(=('$sandbox_caught'), Vars).
 attr_hook_predicates(+Hooks0, +Module, -Hooks) is det
Filter the defined hook implementations. This is safe because (1) calling an undefined predicate is not a safety issue, (2) the user an only assert in the current module and only predicates that have a safe body. This avoids the need to define attribute hooks solely for the purpose of making them safe.
  960attr_hook_predicates([], _, []).
  961attr_hook_predicates([H|T], M, Called) :-
  962    (   predicate_property(M:H, defined)
  963    ->  Called = [M:H|Rest]
  964    ;   Called = Rest
  965    ),
  966    attr_hook_predicates(T, M, Rest).
 expand_nt(+NT, ?Xs0, ?Xs, -NewGoal)
Similar to expand_phrase/2, but we do throw errors instead of failing if NT is not sufficiently instantiated.
  974expand_nt(NT, _Xs0, _Xs, _NewGoal) :-
  975    strip_module(NT, _, Plain),
  976    var(Plain),
  977    !,
  978    instantiation_error(Plain).
  979expand_nt(NT, Xs0, Xs, NewGoal) :-
  980    dcg_translate_rule((pseudo_nt --> NT),
  981                       (pseudo_nt(Xs0c,Xsc) :- NewGoal0)),
  982    (   var(Xsc), Xsc \== Xs0c
  983    ->  Xs = Xsc, NewGoal1 = NewGoal0
  984    ;   NewGoal1 = (NewGoal0, Xsc = Xs)
  985    ),
  986    (   var(Xs0c)
  987    ->  Xs0 = Xs0c,
  988        NewGoal = NewGoal1
  989    ;   NewGoal = ( Xs0 = Xs0c, NewGoal1 )
  990    ).
 safe_meta_call(+Goal, +Context, -Called:list(callable)) is semidet
True if Goal is a meta-predicate that is considered safe iff all elements in Called are safe.
  997safe_meta_call(Goal, _, _Called) :-
  998    debug(sandbox(meta), 'Safe meta ~p?', [Goal]),
  999    fail.
 1000safe_meta_call(Goal, Context, Called) :-
 1001    (   safe_meta(Goal, Called)
 1002    ->  true
 1003    ;   safe_meta(Goal, Context, Called)
 1004    ),
 1005    !.     % call hook
 1006safe_meta_call(Goal, _, Called) :-
 1007    Goal = M:Plain,
 1008    compound(Plain),
 1009    compound_name_arity(Plain, Name, Arity),
 1010    safe_meta_predicate(M:Name/Arity),
 1011    predicate_property(Goal, meta_predicate(Spec)),
 1012    !,
 1013    called(Spec, Plain, Called).
 1014safe_meta_call(M:Goal, _, Called) :-
 1015    !,
 1016    generic_goal(Goal, Gen),
 1017    safe_meta(M:Gen),
 1018    called(Gen, Goal, Called).
 1019safe_meta_call(Goal, _, Called) :-
 1020    generic_goal(Goal, Gen),
 1021    safe_meta(Gen),
 1022    called(Gen, Goal, Called).
 1023
 1024called(Gen, Goal, Called) :-
 1025    compound_name_arity(Goal, _, Arity),
 1026    called(1, Arity, Gen, Goal, Called).
 1027
 1028called(I, Arity, Gen, Goal, Called) :-
 1029    I =< Arity,
 1030    !,
 1031    arg(I, Gen, Spec),
 1032    (   calling_meta_spec(Spec)
 1033    ->  arg(I, Goal, Called0),
 1034        extend(Spec, Called0, G),
 1035        Called = [G|Rest]
 1036    ;   Called = Rest
 1037    ),
 1038    I2 is I+1,
 1039    called(I2, Arity, Gen, Goal, Rest).
 1040called(_, _, _, _, []).
 1041
 1042generic_goal(G, Gen) :-
 1043    functor(G, Name, Arity),
 1044    functor(Gen, Name, Arity).
 1045
 1046calling_meta_spec(V) :- var(V), !, fail.
 1047calling_meta_spec(I) :- integer(I), !.
 1048calling_meta_spec(^).
 1049calling_meta_spec(//).
 1050
 1051
 1052extend(^, G, Plain) :-
 1053    !,
 1054    strip_existential(G, Plain).
 1055extend(//, DCG, Goal) :-
 1056    !,
 1057    (   expand_phrase(call_dcg(DCG,_,_), Goal)
 1058    ->  true
 1059    ;   instantiation_error(DCG)    % Ask more instantiation.
 1060    ).                              % might not help, but does not harm.
 1061extend(0, G, G) :- !.
 1062extend(I, M:G0, M:G) :-
 1063    !,
 1064    G0 =.. List,
 1065    length(Extra, I),
 1066    append(List, Extra, All),
 1067    G =.. All.
 1068extend(I, G0, G) :-
 1069    G0 =.. List,
 1070    length(Extra, I),
 1071    append(List, Extra, All),
 1072    G =.. All.
 1073
 1074strip_existential(Var, Var) :-
 1075    var(Var),
 1076    !.
 1077strip_existential(M:G0, M:G) :-
 1078    !,
 1079    strip_existential(G0, G).
 1080strip_existential(_^G0, G) :-
 1081    !,
 1082    strip_existential(G0, G).
 1083strip_existential(G, G).
 safe_meta(?Template)
 1087safe_meta((0,0)).
 1088safe_meta((0;0)).
 1089safe_meta((0->0)).
 1090safe_meta(system:(0*->0)).
 1091safe_meta(findall(*,0,*)).
 1092safe_meta('$bags':findall(*,0,*,*)).
 1093safe_meta(setof(*,^,*)).
 1094safe_meta(bagof(*,^,*)).
 1095safe_meta('$bags':findnsols(*,*,0,*)).
 1096safe_meta('$bags':findnsols(*,*,0,*,*)).
 1097safe_meta(system:call_cleanup(0,0)).
 1098safe_meta(system:setup_call_cleanup(0,0,0)).
 1099safe_meta('$attvar':call_residue_vars(0,*)).
 1100safe_meta('$syspreds':call_with_inference_limit(0,*,*)).
 1101safe_meta('$syspreds':call_with_depth_limit(0,*,*)).
 1102safe_meta('$syspreds':undo(0)).
 1103safe_meta(^(*,0)).
 1104safe_meta(\+(0)).
 1105safe_meta(call(0)).
 1106safe_meta(call(1,*)).
 1107safe_meta(call(2,*,*)).
 1108safe_meta(call(3,*,*,*)).
 1109safe_meta(call(4,*,*,*,*)).
 1110safe_meta(call(5,*,*,*,*,*)).
 1111safe_meta(call(6,*,*,*,*,*,*)).
 1112safe_meta('$tabling':start_tabling(*,0)).
 1113safe_meta('$tabling':start_tabling(*,0,*,*)).
 1114safe_meta(wfs:call_delays(0,*)).
 safe_output(+Output)
True if something is a safe output argument for with_output_to/2 and friends. We do not want writing to streams.
 1121safe_output(Output) :-
 1122    var(Output),
 1123    !,
 1124    instantiation_error(Output).
 1125safe_output(atom(_)).
 1126safe_output(string(_)).
 1127safe_output(codes(_)).
 1128safe_output(codes(_,_)).
 1129safe_output(chars(_)).
 1130safe_output(chars(_,_)).
 1131safe_output(current_output).
 1132safe_output(current_error).
 format_calls(+Format, +FormatArgs, -Calls)
Find ~@ calls from Format and Args.
 1138:- public format_calls/3,                       % used in pengines_io
 1139          write_options_calls/2. 1140
 1141format_calls(Format, Args, Calls) :-
 1142    is_list(Args),
 1143    !,
 1144    format_types(Format, Types),
 1145    (   format_callables(Types, Args, Calls)
 1146    ->  true
 1147    ;   throw(error(format_error(Format, Types, Args), _))
 1148    ).
 1149format_calls(Format, Arg, Calls) :-
 1150    format_calls(Format, [Arg], Calls).
 1151
 1152format_callables([], [], []).
 1153format_callables([callable|TT], [G|TA], [G|TG]) :-
 1154    !,
 1155    format_callables(TT, TA, TG).
 1156format_callables([list|TT], [Options|TA], TG) :-     % ~W
 1157    !,
 1158    write_options_calls(Options, TG0),
 1159    format_callables(TT, TA, TG1),
 1160    append(TG0, TG1, TG).
 1161format_callables([_|TT], [_|TA], TG) :-
 1162    !,
 1163    format_callables(TT, TA, TG).
 write_options_calls(+Options, -Calls) is det
Calls is a list of goals called by write_term/2 using Options. The option portray_goal(Goal) calls Goal with two additional arguments.
 1172write_options_calls(Options, _) :-
 1173    var(Options),
 1174    !,
 1175    instantiation_error(Options).
 1176write_options_calls([], []) :-
 1177    !.
 1178write_options_calls([H|T], Calls) :-
 1179    !,
 1180    write_option_calls(H, Calls, Calls1),
 1181    write_options_calls(T, Calls1).
 1182write_options_calls(Options, _) :-
 1183    type_error(list, Options).
 1184
 1185write_option_calls(Opt, _, _) :-
 1186    var(Opt),
 1187    !,
 1188    instantiation_error(Opt).
 1189write_option_calls(portray_goal(G), [Call|T], T) :-
 1190    !,
 1191    extend(2, G, Call).
 1192write_option_calls(portray_goal=G, [Call|T], T) :-
 1193    !,
 1194    extend(2, G, Call).
 1195write_option_calls(_, T, T).
 message_calls(+Message, -Calls) is det
Message translation for format(Fmt,Args) and debug(Fmt,Args) calls format/2.
 1202message_calls(Msg, _) :-
 1203    unbound_message(Msg),
 1204    !,
 1205    instantiation_error(Msg).
 1206message_calls(Msg, Calls) :-
 1207    message_format(Msg, Fmt, Args),
 1208    !,
 1209    format_calls(Fmt, Args, Calls0),
 1210    maplist(message_qualify, Calls0, Calls).
 1211message_calls(_, []).
 1212
 1213unbound_message(Msg) :-
 1214    var(Msg),
 1215    !.
 1216unbound_message(error(Formal, _)) :-
 1217    var(Formal).
 safe_ball(@Ball) is semidet
True if throw(Ball) is safe. Exceptions are typically printed using print_message/2 outside the sandbox. We therefore deny exception terms that are translated into a user-provided format string.
 1226safe_ball(Ball) :-
 1227    unbound_message(Ball),
 1228    !,
 1229    instantiation_error(Ball).
 1230safe_ball(Ball) :-
 1231    \+ message_format(Ball, _, _).
 1232
 1233% Message lines are formatted in the module '$messages'.
 1234message_qualify(G, G) :-
 1235    nonvar(G),
 1236    G = _:_,
 1237    !.
 1238message_qualify(G, '$messages':G).
 1239
 1240message_format(format(Fmt, Args), Fmt, Args).
 1241message_format(debug(Fmt, Args), Fmt, Args).
 1242message_format(error(Formal, _), Fmt, Args) :-
 1243    nonvar(Formal),
 1244    Formal = format(Fmt, Args).
 safe_relative_path(+Path) is semidet
True if Path is a relative path that cannot point outside the directory against which it is resolved.
 1251safe_relative_path(Path) :-
 1252    \+ is_absolute_file_name(Path),
 1253    \+ sub_atom(Path, 0, _, _, ~),
 1254    split_string(Path, "/\\", "", Segments),
 1255    \+ memberchk("..", Segments).
 1256
 1257
 1258                 /*******************************
 1259                 *    SAFE COMPILATION HOOKS    *
 1260                 *******************************/
 1261
 1262:- multifile
 1263    prolog:sandbox_allowed_directive/1,
 1264    prolog:sandbox_allowed_goal/1,
 1265    prolog:sandbox_allowed_expansion/1.
 prolog:sandbox_allowed_directive(:G) is det
Throws an exception if G is not considered a safe directive.
 1271prolog:sandbox_allowed_directive(Directive) :-
 1272    debug(sandbox(directive), 'Directive: ~p', [Directive]),
 1273    fail.
 1274prolog:sandbox_allowed_directive(Directive) :-
 1275    safe_directive(Directive),
 1276    !.
 1277prolog:sandbox_allowed_directive(M:PredAttr) :-
 1278    \+ prolog_load_context(module, M),
 1279    !,
 1280    debug(sandbox(directive), 'Cross-module directive', []),
 1281    permission_error(execute, sandboxed_directive, (:- M:PredAttr)).
 1282prolog:sandbox_allowed_directive(M:PredAttr) :-
 1283    safe_pattr(PredAttr),
 1284    !,
 1285    PredAttr =.. [Attr, Preds],
 1286    (   safe_pattr(Preds, Attr)
 1287    ->  true
 1288    ;   permission_error(execute, sandboxed_directive, (:- M:PredAttr))
 1289    ).
 1290prolog:sandbox_allowed_directive(_:Directive) :-
 1291    safe_source_directive(Directive),
 1292    !.
 1293prolog:sandbox_allowed_directive(_:Directive) :-
 1294    directive_loads_file(Directive, File),
 1295    !,
 1296    safe_path(File).
 1297prolog:sandbox_allowed_directive(G) :-
 1298    safe_goal(G).
 safe_directive(:Directive) is semidet
Hook to declare additional directives as safe. The argument is a term Module:Directive (without :- wrapper). In almost all cases, the implementation must verify that the Module is the current load context as illustrated below. This check is not performed by the system to allow for cases where particular cross-module directives are allowed.
sandbox:safe_directive(M:Directive) :-
    prolog_load_context(module, M),
    ...
 1316safe_pattr(dynamic(_)).
 1317safe_pattr(thread_local(_)).
 1318safe_pattr(volatile(_)).
 1319safe_pattr(discontiguous(_)).
 1320safe_pattr(multifile(_)).
 1321safe_pattr(public(_)).
 1322safe_pattr(meta_predicate(_)).
 1323safe_pattr(table(_)).
 1324safe_pattr(non_terminal(_)).
 1325
 1326safe_pattr(Var, _) :-
 1327    var(Var),
 1328    !,
 1329    instantiation_error(Var).
 1330safe_pattr((A,B), Attr) :-
 1331    !,
 1332    safe_pattr(A, Attr),
 1333    safe_pattr(B, Attr).
 1334safe_pattr(M:G, Attr) :-
 1335    !,
 1336    (   atom(M),
 1337        prolog_load_context(module, M)
 1338    ->  true
 1339    ;   Goal =.. [Attr,M:G],
 1340        permission_error(directive, sandboxed, (:- Goal))
 1341    ).
 1342safe_pattr(_, _).
 1343
 1344safe_source_directive(op(_,_,Name)) :-
 1345    !,
 1346    (   atom(Name)
 1347    ->  true
 1348    ;   is_list(Name),
 1349        maplist(atom, Name)
 1350    ).
 1351safe_source_directive(set_prolog_flag(Flag, Value)) :-
 1352    !,
 1353    atom(Flag), ground(Value),
 1354    safe_prolog_flag(Flag, Value).
 1355safe_source_directive(style_check(_)).
 1356safe_source_directive(initialization(_)).   % Checked at runtime
 1357safe_source_directive(initialization(_,_)). % Checked at runtime
 1358
 1359directive_loads_file(use_module(library(X)), X).
 1360directive_loads_file(use_module(library(X), _Imports), X).
 1361directive_loads_file(load_files(library(X), _Options), X).
 1362directive_loads_file(ensure_loaded(library(X)), X).
 1363directive_loads_file(include(X), X).
 1364
 1365safe_path(X) :-
 1366    var(X),
 1367    !,
 1368    instantiation_error(X).
 1369safe_path(X) :-
 1370    (   atom(X)
 1371    ;   string(X)
 1372    ),
 1373    !,
 1374    safe_relative_path(X).
 1375safe_path(A/B) :-
 1376    !,
 1377    safe_path(A),
 1378    safe_path(B).
 safe_prolog_flag(+Flag, +Value) is det
True if it is safe to set the flag Flag to Value.
To be done
- If we can avoid that files are loaded after changing this flag, we can allow for more flags. The syntax flags are safe because they are registered with the module.
 1390% misc
 1391safe_prolog_flag(generate_debug_info, _).
 1392safe_prolog_flag(optimise, _).
 1393safe_prolog_flag(occurs_check, _).
 1394safe_prolog_flag(write_attributes, _).
 1395% syntax
 1396safe_prolog_flag(var_prefix, _).
 1397safe_prolog_flag(double_quotes, _).
 1398safe_prolog_flag(back_quotes, _).
 1399safe_prolog_flag(rational_syntax, _).
 1400% arithmetic
 1401safe_prolog_flag(prefer_rationals, _).
 1402safe_prolog_flag(float_overflow, _).
 1403safe_prolog_flag(float_zero_div, _).
 1404safe_prolog_flag(float_undefined, _).
 1405safe_prolog_flag(float_underflow, _).
 1406safe_prolog_flag(float_rounding, _).
 1407safe_prolog_flag(float_rounding, _).
 1408safe_prolog_flag(max_rational_size, _).
 1409safe_prolog_flag(max_rational_size_action, _).
 1410% tabling
 1411safe_prolog_flag(max_answers_for_subgoal,_).
 1412safe_prolog_flag(max_answers_for_subgoal_action,_).
 1413safe_prolog_flag(max_table_answer_size,_).
 1414safe_prolog_flag(max_table_answer_size_action,_).
 1415safe_prolog_flag(max_table_subgoal_size,_).
 1416safe_prolog_flag(max_table_subgoal_size_action,_).
 prolog:sandbox_allowed_expansion(:G) is det
Throws an exception if G is not considered a safe expansion goal. This deals with call-backs from the compiler for

Our assumption is that external expansion rules are coded safely and we only need to be careful if the sandboxed code defines expansion rules.

 1432prolog:sandbox_allowed_expansion(M:G) :-
 1433    prolog_load_context(module, M),
 1434    !,
 1435    debug(sandbox(expansion), 'Expand in ~p: ~p', [M, G]),
 1436    safe_goal(M:G).
 1437prolog:sandbox_allowed_expansion(_,_).
 prolog:sandbox_allowed_goal(:G) is det
Throw an exception if it is not safe to call G
 1443prolog:sandbox_allowed_goal(G) :-
 1444    safe_goal(G).
 1445
 1446
 1447                 /*******************************
 1448                 *            MESSAGES          *
 1449                 *******************************/
 1450
 1451:- multifile
 1452    prolog:message//1,
 1453    prolog:message_context//1,
 1454    prolog:error_message//1. 1455
 1456prolog:message(error(instantiation_error, Context)) -->
 1457    { nonvar(Context),
 1458      Context = sandbox(_Goal,Parents),
 1459      numbervars(Context, 1, _)
 1460    },
 1461    [ 'Sandbox restriction!'-[], nl,
 1462      'Could not derive which predicate may be called from'-[]
 1463    ],
 1464    (   { Parents == [] }
 1465    ->  [ 'Search space too large'-[] ]
 1466    ;   callers(Parents, 10)
 1467    ).
 1468
 1469prolog:message_context(sandbox(_G, [])) --> !.
 1470prolog:message_context(sandbox(_G, Parents)) -->
 1471    [ nl, 'Reachable from:'-[] ],
 1472    callers(Parents, 10).
 1473
 1474callers([], _) --> !.
 1475callers(_,  0) --> !.
 1476callers([G|Parents], Level) -->
 1477    { NextLevel is Level-1
 1478    },
 1479    [ nl, '\t  ~p'-[G] ],
 1480    callers(Parents, NextLevel).
 1481
 1482prolog:message(bad_safe_declaration(Goal, File, Line)) -->
 1483    [ '~w:~d: Invalid safe_primitive/1 declaration: ~p'-
 1484      [File, Line, Goal] ].
 1485
 1486prolog:error_message(format_error(Format, Types, Args)) -->
 1487    format_error(Format, Types, Args).
 1488
 1489format_error(Format, Types, Args) -->
 1490    { length(Types, TypeLen),
 1491      length(Args, ArgsLen),
 1492      (   TypeLen > ArgsLen
 1493      ->  Problem = 'not enough'
 1494      ;   Problem = 'too many'
 1495      )
 1496    },
 1497    [ 'format(~q): ~w arguments (found ~w, need ~w)'-
 1498      [Format, Problem, ArgsLen, TypeLen]
 1499    ]