Ruby 2.0.0p247(2013-06-27revision41674)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

safe.c
Go to the documentation of this file.
1 /**********************************************************************
2
3 safe.c -
4
5 $Author: nobu $
6 created at: Tue Sep 23 09:44:32 JST 2008
7
8 Copyright (C) 2008 Yukihiro Matsumoto
9
10 **********************************************************************/
11
12 /* safe-level:
13 0 - strings from streams/environment/ARGV are tainted (default)
14 1 - no dangerous operation by tainted value
15 2 - process/file operations prohibited
16 3 - all generated objects are tainted
17 4 - no global (non-tainted) variable modification/no direct output
18 */
19
20 #define SAFE_LEVEL_MAX 4
21
22 #include "ruby/ruby.h"
23 #include "vm_core.h"
24
25 /* $SAFE accessor */
26
27 int
28 rb_safe_level(void)
29 {
30 return GET_THREAD()->safe_level;
31 }
32
33 void
34 rb_set_safe_level_force(int safe)
35 {
36 GET_THREAD()->safe_level = safe;
37 }
38
39 void
40 rb_set_safe_level(int level)
41 {
42 rb_thread_t *th = GET_THREAD();
43
44 if (level > th->safe_level) {
45 if (level > SAFE_LEVEL_MAX) {
46 level = SAFE_LEVEL_MAX;
47 }
48 th->safe_level = level;
49 }
50 }
51
52 static VALUE
53 safe_getter(void)
54 {
55 return INT2NUM(rb_safe_level());
56 }
57
58 static void
59 safe_setter(VALUE val)
60 {
61 int level = NUM2INT(val);
62 rb_thread_t *th = GET_THREAD();
63
64 if (level < th->safe_level) {
65 rb_raise(rb_eSecurityError,
66 "tried to downgrade safe level from %d to %d",
67 th->safe_level, level);
68 }
69 if (level == 3) {
70 rb_warning("$SAFE=3 does no sandboxing; you might want to use $SAFE=4");
71 }
72 if (level > SAFE_LEVEL_MAX) {
73 level = SAFE_LEVEL_MAX;
74 }
75 th->safe_level = level;
76 }
77
78 void
79 rb_secure(int level)
80 {
81 if (level <= rb_safe_level()) {
82 if (rb_frame_callee()) {
83 rb_raise(rb_eSecurityError, "Insecure operation `%s' at level %d",
84 rb_id2name(rb_frame_callee()), rb_safe_level());
85 }
86 else {
87 rb_raise(rb_eSecurityError, "Insecure operation at level %d",
88 rb_safe_level());
89 }
90 }
91 }
92
93 void
94 rb_secure_update(VALUE obj)
95 {
96 if (!OBJ_TAINTED(obj))
97 rb_secure(4);
98 }
99
100 void
101 rb_insecure_operation(void)
102 {
103 if (rb_frame_callee()) {
104 rb_raise(rb_eSecurityError, "Insecure operation - %s",
105 rb_id2name(rb_frame_callee()));
106 }
107 else {
108 rb_raise(rb_eSecurityError, "Insecure operation: -r");
109 }
110 }
111
112 void
113 rb_check_safe_obj(VALUE x)
114 {
115 if (rb_safe_level() > 0 && OBJ_TAINTED(x)) {
116 rb_insecure_operation();
117 }
118 rb_secure(4);
119 }
120
121 void
122 rb_check_safe_str(VALUE x)
123 {
124 rb_check_safe_obj(x);
125 if (!RB_TYPE_P(x, T_STRING)) {
126 rb_raise(rb_eTypeError, "wrong argument type %s (expected String)",
127 rb_obj_classname(x));
128 }
129 }
130
131 void
132 Init_safe(void)
133 {
134 rb_define_virtual_variable("$SAFE", safe_getter, safe_setter);
135 }
136