forked from yang/notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurity.page
More file actions
1708 lines (1508 loc) · 72.6 KB
/
Copy pathSecurity.page
File metadata and controls
1708 lines (1508 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
TODO Nemesis: Preventing Authentication & Access Control Vulnerabilities in Web Applications -zeldovich
resources
- magic string from skipfish: `-->">'>'"<sfi000142v524891>`
- <http://www.cs.berkeley.edu/~daw/teaching/cs261-f08/>
everything you need to know about cryptography in 1 hour (talk by collin
percival)
- hashing
- ideal hash function: collision-resistant & one-way; nothing else
- collision-resistant: hard to find 2 inputs w same hash
- one-way: hard to find input given hash
- nothing else: in particular, knowing $H(x)$ may let attacker compute
$H(y)$ for some $y$, so simple hashing in itself is unsuitable for
authentication/signing
- don't use for symmetric signing
- use SHA-256 (SHA-2); consider SHA-3; avoid MD2, MD4, MD5, SHA-1, RIPEMD
- symmetric authentication aka symmetric signing: uses MACs
- ideal MAC $f_k(x)$ uses key $k$ to map any-len input to $n$-bit output
such that even if you know a $(x, f_k(x))$ pair, it's hard to generate
another $(y, f_k(y))$, unlike in hashing
- avoid having 2 msgs result in same data being input to MAC; ie take care
w delimiters, don't simply concatenate things
- use HMAC-SHA256; avoid CBC-MAC, Poly1305
- don't leak timing side channels when verifying signatures (no early
returns)
- side channels: timing, EM emissions (TEMPEST), power consumption, microarch
features (caches, HyperThreading)
- block ciphers: TODO
- TODO finish
- <http://www.bsdcan.org/2010/schedule/attachments/135_crypto1hr.pdf>
- <http://blip.tv/file/3627639>
people
- michal zalewski: google security person, wrote browsersec book among tons of
other literature/tools
- jeremiah grossman: prominent web security blogger; leader of whitehat
security, purveyor of web application firewalls
- theo de raadt: openssl, openbsd
- mark dowd: amazing; ibm x-force team; taossa book; nacl exploits; flash null
ptr exploit
- mark miller: exploits, reveng, rootkits; joined windows 8/2008
- james whittaker: testing; joined windows 5/2006; joined google 6/2009
- crispin cowan: stackguard, immunix, subdomain, apparmor; joined windows from
novell 1/2008
- michael howard: windows security team lead
- niels provos: principal engr at google; libevent, libio, openssh privsep;
malware work
industry
- infrastructure (network/host) vs (web) application security
- infrastructure: $9.1B to secure $98.5B assets (9.23%)
- application: $750M to secure $64.4B assets (1.2%)
- <http://jeremiahgrossman.blogspot.com/2010/02/infrastructure-vs-application-security.html>
vulnerability databases
- MITRE Common Vulnerabilities and Exposures (CVE)
misc terms
- _side-channel attack_: exploits physical implementation (vs. brute force or theoretical weakness); in crypto
- _covert channel_: channel that draws BW from another channel; in info theory
- eg timing attacks: latency tells you whether logged in, whether query
succeeds/fails (document contains term), how much of password you match
(page-aligning password), etc
- _drive-by download_: browser (or extension) exploit triggered on simply
displaying a page
- security assurance techniques: pentesting, code review, platform defenses,
training, architectural/design analysis
- advanced persistent threat (APT): eg chinese gov attacking google
security models
- clark-wilson integrity model: semi-formal model
- 2 categories of data, known-good (trusted) and unknown (untrusted)
- mandatory checks to filter data before moving it from unknown to known-good
- mandatory checks that data must be in the known-good state before it can
participate in sensitive ops
- eg: virus scanner than forces checking of all files as they're opened
- bell-lapuda (BPL) privacy model: formal model and policy
- "data diode": info only flows in not out; useful for eg CIA
- label-based access control; formal models of security allow for proofs
- hugely influential in academic security research
- biba integrity model: dual of BPL model, for integrity instead
high level exploit classification
- confused deputy: fool a privileged process to do things for you
- arbitrary code execution: take over and do things yourself
access control
- _discretionary access control (DAC)_: subjects can xfer perms to others;
decentralized
- commonly in practice: objs have owners who controls perms
- capability systems: subjects can xfer perms to others
- _mandatory access control (MAC)_: policy controlled by admin only; centralized
- _role-based (RBAC)_: restrict system access to authorized users
- newer alt to MAC/DAC; can sim MAC/DAC
- users are assigned particular roles; roles are assigned permissions
- basically, roles are a level of indirection
- qualitatively/typically, more fine-grained than ACLs, enumerating specific
high-level operations
integrity control TODO
security
- confidentiality: aka privacy, secrecy
- integrity: eg phishing, MITM, hijacking, forgery
- availability: eg DOS
incorrect/missing MIME type exploits
- from <http://code.google.com/p/skipfish/wiki/KnownIssues>
> Missing or mismatched MIME types on any files with user-controlled contents
> may easily lead to cross-site scripting flaws. This is because of browser
> content sniffing logic, a problem is particularly pronounced in Microsoft
> Internet Explorer - where even something as subtle as returning image/jpeg
> on a GIF file may cause HTML detection to be attempted, possibly
> interpreting any HTML stuffed in the EXIF fields of an otherwise valid
> image.
- example from <http://osvdb.org/show/osvdb/54773>
> Simple Machines Forum contains a flaw that allows a remote cross site
> scripting attack. This flaw exists because the application uses the
> incorrect MIME type 'image/bmp'. The unknown header triggers MIME sniffing
> in Internet Explorer, allowing an image to be falsely identified as
> text/html. This could allow a user to create a specially crafted image
> that would execute arbitrary code in a user's browser within the trust
> relationship between the browser and the server, leading to a loss of
> integrity.
S/MIME: TODO
- http://en.wikipedia.org/wiki/S/MIME
- http://weblog.infoworld.com/udell/2004/03/23.html
C++
- new/delete[]: if eg you have an array created with new[] and then
accidentally delete[] a pointer not pointing to the head, then you can
overwrite in the previous element the mem that delete[] treats as the length
field
- gcc: delete[] consults vtable of each object indepdently
- msvc: delete[] consults vtable of first object only
- harder on msvc, but can still do interesting things if eg dtor itself does
anything interesting with the object data, eg free a pointer or set a value
- new[]/delete: you can cause coalescing by setting the `prev` bit in the
malloc header, among other things
high-level code injection, encoding/parsing vulns
- unescaped input
- unicode: bad multibyte chars can bypass poor standard-library
escapers/filters and validators/scanners unscathed
- dynamic langs like sql and html/js
- specific case of parser errors
- eg: UTF-7
- can encode ascii, eg `+ADw-` for `<`
- IE interprets html/javascript using UTF-7 by default, and others use
UTF-7 if a UTF-7 encoding appears anywhere early on (hence, `title`,
`meta`, etc are targets)
- need to check that all places handling this interpret it/escape it
correctly, eg need to specify UTF-7 to php escaper `htmlentities()`
- <http://shiflett.org/blog/2005/dec/google-xss-example>
- eg: multi-byte encoding
- eg, adding slashes (php `addslashes()`) is insufficient
- `addslashes("\xbf27")` is '\xbf5c27', and '\xbf5c' is a valid char in
GBK, swallowing the slash/letting the quote work
- <http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string>
- parser errors: unhandled cases leading to unesacped input
sandboxing pitfalls
- ptrace: race conditions
- ptrace behavior: suspends thread; mon reads args (regs, mem) separately
- monitor can rewrite syscalls
- multi-threaded arg race (TOCTTOU)
- A syscalls; monitor checks; B changes args
- works only on args that are not in regs, eg ptrs to other mem (file paths)
- heavy-handed soln: prohibit multithreading
- soln: suspend all threads
- only for syscalls that use such ptrs ("volatile" syscalls)
- if block all syscalls, then deadlock
- devs use syscalls for sync (eg read and write)
- authors don't know of any such pair of syscalls where one is volatile
- another process could modify args via shared mem
- heavy-handed soln: prohibit forking, shared mem
- soln: or suspend all processes
- fork-attach race
- sandbox doesn't immediately attach to a forked child (!)
- forked child can secretly fork another child monitor won't know about
- soln: change call from fork to clone; has option to start in ptraced mode
- FS race: trickiest; use symlinks to break security
- prisoner does syscall involving path
- monitor looks up path, following symlinks, to verify
- another process/thread replaces a component in path with symlink to
secure region in FS (eg user's $HOME)
- soln: suspend threads
- signals TODO
- avoid by denying signals
- alts to syscalls
- lcall7 and lcall27 call gates; removed from most modern linuxes
- MITRE CVE has over 40 ptrace-related items
- refs
- <http://iacoma.cs.uiuc.edu/~greskamp/pdfs/598cz.pdf>
- NaCl
- chroot
- TODO
- (obv) can still make arbitrary syscalls; FS is only one part of sandboxing
web
- flash: `<embed...allowScriptAccess="always">` instead of `"sameDomain"`
- _HTTP parameter pollution (HPP)_ variants: multi-value, OOO value, malformed
value, malformed request methods
- clickjacking: tricking the user into clicking something on a target site
- eg by loading target in transparent iframe overlaid atop an enticing
button, with a form submission button positioned exactly at the right place
- mitigations: framekiller or framebuster: check `top==self`
low-level exploits
- buffer overflow
- defenses
- stack canaries: choose random int at process start and insert before
return addr
- random xor canaries: xor with the return addr to make sure it's not
tampered with
- propolice: gcc's impl; enhanced version of stackguard (never officially
impl'd in gcc)
- visual studio: /gs
- nonexecutable stack: in windows, called Data Execution Prevention
- NX bit: in page table entries; XD bit in intel, enhanced virus
protection in amd
- segments can be readable/writeable/executable, but modern OS's use flat
memory model (pages instead of segments)
- address space layout randomization (ASLR): randomize codes, heap, stacks
- against return-to-libc (arbitrary code can still detect things)
- null pointer exploits: TODO
- heap overflow: overwrite eg a struct's function pointer or malloc block
header
- heap spray: give you a place to place executable code, eg if stack is NX or
your overriding return addr is constrained somehow
- spray it everywhere to increase chances of landing in it
- common in web browser js engines
- nozzle: msr project that uses sled detection then reduces false positive
rate with "global heap health metric"
- parser errors: unhandled cases
- format string attacks: eg printf(untrusted_input())
- eg use %s and %x to print data from stack or other memory locations
- defenses: statically check format strings
- integer overflow: unexpected number, either negative or large
- eg size header in messages
- controls things like strncpy/memcpy for overwrites
- controls allocations (malloc) for large, unrealizeable mallocs that return
null
- also, arithm overflow
- null pointers
- as write vector: use bad alloc to get ptr = null, where app later does
*(ptr + offset) = value (where offset and value are user-controlled) to
write a function ptr (flash exploit)
- if the ptr is dereferenced and fields are accessed, first prep by writing
to those fields
- return-to-libc: execute existing code via return ptr, circumventing NX
- eg `system("bash")`
- ASLR defends against this
- techniques to make multiple function calls:
- `%esp` lifting: for `-fomit-frame-pointer`
- functions end in `addl $LOCAL_VARS_SIZE, %esp; ret`
- after args to function, pad enough so that next function ptr is where
%esp would point and thus the system would return to
- frame faking: for programs w frame pointer
- functions end in `leave; ret`
- put in fake `ebp`s (frame ptrs) that point to function, followed by a
ptr to a `leave;ret`
- the very first return should point to a `leave;ret`
return oriented programming
- _continuation of execution_: resume app normally after exploit payload
same-origin policy (SOP)
- policies
- for DOM access: scripts can access another page's functions/data iff from
same site (in another frame/window)
- scripts run in context of includer, not source; can't xhr or DOM-manip
google
- for XHR: only time when SOP restrict doc retrieval; html elements can
source any domain
- for cookies
- for flash
- `crossdomain.xml`: primarily protects access to the host containing the
`crossdomain.xml`, specified with `allow-access-from`
- careless wildcard usage opens up holes; eg flickr's api (since isolated
to a separate domain)
- can make same-origin HTTP reqs
- can make same-host TCP conns on any high port
- for java: applets can only see site it's downloaded from
- can interact with the embedding page via JSObject API iff `mayscript` set
in `applet` tag
- DOMService API allows cross-site embedding pages to be accessed freely!
with no `mayscript` opt-in, directly contradicting JSObject API
- ability to send same-origin HTTP reqs using browser stack via
URLConnection API; can even set `Host` headers or conflicting caching
directives
- unconstrained TCP connections back to originating host
- for silverlight: mimicks flash
- attacks against SOP: XSRF, XSS, DNS rebinding
- rules
- match: (domain name, app layer protocol (http/ftp), tcp port)
- opt to communicate by setting `document.domain` to same right-hand fragment
of current host name (eg en.example.com and fr.example.com set to
example.com)
- corollary: all subdomains are implicitly granted accessed to parent domain
- workarounds
- google analytics works by issuing a single-pixel image request containing
all collected information
- google maps api works by dynamically creating script tags that load
on-demand javascript (data can be in JSON)
- flash: permits cross-domain requests if allowed by crossdomain.xml on
target webserver
- threat model: defend against impersonation of user and impersonation of site
- some operations still allowed
- include scripts across domains
- submit POST forms across domains
- mitigation practices
- escaping/filtering
- input validation
- http responses are variations
- http request smuggling
ways to do cross-site communication in web apps
- dynamically create script tags to get data
- unsafe: response can do arbitrary code execution
- Mozilla cross-window messaging via `window.postMessage`
- receiver gets `message` DOM event; msg contains data, domain, uri, source
- allows cross-site communication
- requires explicit msg handling on target page, so less susceptible to
problems than unchecked shared DOM access (pre-SOP)
- JSONRequest: obsoleted by CS-XHR
- like form.submit, but no auth data or cookies
- IE XDomainRequest (XDR) and W3C Cross-Origin Resource Sharing (CORS)
- modern alt to JSONP (but works with reqs besides GET)
- send `Origin` in req (like `Referer` but no path)
- require `Access-Control-Allow-Origin` in response; must be `*` or the exact
page URL
- CORS is for XmlHttpRequest Level 2, namely the Cross Site-XHR (CS-XHR) part
(XHR2 bundles many features)
- IE team criticizes CS-XHR in favor of XDR
- spec says JSONRequest doesn't address their requirements
- Flash, Silverlight: similar server-side sandboxing as XDR/CORS using
`crossdomain.xml`
- <http://blogs.msdn.com/ie/archive/2008/06/23/securing-cross-site-xmlhttprequest.aspx>
web application security
- mozilla content security policy (CSP)
- no inline scripts, only included script files from whitelisted sites
- no code from strings: eval, setTimeout-with-string, etc.
- specify where content allowed from/where requests can be sent
- see examples on <https://wiki.mozilla.org/Security/CSP/Spec>
- html5 sandboxing
- sandbox tag treats its contents as different-origin
- session attacks to obtain session ids
- prediction
- capture
- fixation: get user to use an attacker-chosen sid
- web application firewalls (WAFs)
- a type of IDS/IPS
- modsecurity: for apache; supports negative & positive rule models; has core
rule set; non-learning
- very simple rules that give rise to false positives
- users expected to tweak rules and initially use as IDS only
- CRS
- http compliance
- automation detection
- owasp top 10 attacks (sql, xss, os cmds, filenames, cf/asp/php, email,
response splitting, pdf)
- comm w trojans/backdoors that have already broken in
- app error hiding
- external patching
secure javascript
- caja
- secure ecmascript: <http://ses.json.org/>
javascript
- ESAPI: an encoding lib that uses declarative rules and whitelists of allowed
chars
XSS (cross-site scripting)
- exploits the trust that a user has for a particular site
- name origins: malicious site loads another site in a frame/window, then use
js to read/write data; blocked by SOP
- now: code (html/js) injection into pages (eg forum) viewed by others (to
read/write data)
- frequently: hijack session key; send by embedding in (eg) img url
- types
- non-persistent aka reflected: request is instantly and transiently used
(not stored) to return result, eg search engine box
- only affects the requester, but social engineering (eg send link)
- most common, but importance is arguable (due to soc eng requirement)
- persistent aka stored aka second-order: request is stored & later
displayed (to others)
- DOM-based aka local: TODO
- orthogonal to persistence
- 80% of all sec vulns in 2007 -symantec
XSRF (cross-site request forgery)
- exploits the trust that a site has for a particular user
- before SOP, easy for evil.com to use XHRs to send requests to bank.com that
carry cookies and auth data
- make user's browser send request to a site that user has active credentials
on
- examples
- malicious site contains form that entices user to submit
- POSTs to bank site withdrawing money
- requires user to be authenticated
- post img to bank site forum whose src is a GET that (eg) withdraws money
- fixes
- referer checking: subject to SOP implementation vulnerabilities, but more
importantly referer-filtering (many enable this for privacy)
- use nonces to make each http response-http request a challenge-response
- as long as you use something secret to the outside world, you're fine
- so you can either generate random numbers
- or you can use the session ID (or a hash of it to reduce the chances that
it gets leaked)
- GET requests are tricky because you can read the URL out of the location
bar
pluggable authentication module (PAM)
- first in linux (linux-pam from RH), but on other systems now
PKI
- TLS/SSL certificates
- standard: cheaper, faster; just shows padlock
- extended: more rigorous issuing policy; also shows company name
- CAs sell packages: single domain, $n$ domains, wildcard (subdomains)
- only one https virtual host per IP, since SSL is before the `Host:` header
- SNI: extension to TLS that enables virtual hosting
- client requests name of virtual domain during TLS nego
- certificate revocation list (CRL)
- published by the issuing CA on some periodic schedule
- clients download, cache, check against it
- online certificate status protocol (OCSP): check online if cert still good
- less BW (don't DL all), real-time
- impl'd in major browsers
- X509 certificate formats
- pem: base64, with "BEGIN/END CERTIFICATE"; for DEM certs; originally for
privacy enhanced mail
- cer, crt, der: usually in binary DER format
- p12: PKCS12, may contain both public and private keys; published by RSA
- protected with password-based symmetric key
- successor to PFX from MS, criticized for complexity
- renego vulnerabilities: when upgrading an insecure connection to a secure one
(e.g. STARTTLS) already-buffered plaintext data can slip through
- attacker can inject prefixes into the data stream
- eg for HTTP, everything starting from the second GET is from the client
(and encrypted):
GET /path/to/resource.jsp HTTP/1.0
Dummy-Header: GET /index.jsp HTTP/1.0
Cookie: sessionCookie=Token
MAC and Hashes
- MAC: integrity and authenticity; protect against chosen-plaintext attacks
- message authentication code (MAC): keyed hash; TODO
- message integrity code (MIC): TODO
- hash-based MAC (HMAC)
- uses 1-way hash (eg SHA), but incorporates shared secret key (for
authenticity) and re-hashing the hash of the key + message (to prevent
append attacks)
- masks key with consts ipad (0x3636..) and opad (0x5c5c..)
- hmac(key, msg) = hash((key xor opad) + hash((key xor ipad) + msg))
- <http://dev.ionous.net/2009/03/hmac-vs-raw-sha-1.html>
- cryptographic hash functions: TODO
- diffie-hellman key exchange
- allow 2 parties w no prior knowledge of ea other to establish shared secret
key over insecure channel
- uses discrete logarithm problem: compute discrete logs module an
appropriate prime (a bit harder/slower than factoring "hard" ints of same
size)
- followed shortly by RSA
- secure remote password (SRP)
- structurally similar to D-H
authentication encryption
- middle option is the only secure one:
- Encrypt and MAC: encrypt the plaintext, compute the MAC of the plaintext,
and append the MAC of the pltaintext to the ciphertext
- Encrypt then MAC: encrypt the plaintext, compute the MAC of the ciphertext,
and append the MAC of the ciphertext to the ciphertext
- MAC then Encrypt: MAC the plaintext, append the MAC to the plaintext, then
encrypt the plaintext and the MAC
- <http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken>
- <http://www.daemonology.net/blog/2009-06-24-encrypt-then-mac.html>
- salting: decorating a password (eg prefix/suffix) and hashing that as the
"password" (for storage/comparison); similar to nonce
- defends against rainbow table attacks (since each user)
- variations
- site-wide, static hash (hardcoded)
- hash of user info; lacks entropy, still can be predicted (only so many
usernames)
- generate and store random salt
- combo of above: static + user info hash + stored hash
network attacks
- sockstress: syn-synack-ack flood (local iptables configured to not be
affected)
- ping of death: icmp packet that's >64KB in length
- teardrop: mangled IP fragments with overlapping, over-sized payloads
network reconnaissance
- idle scan aka zombie scan: port scan that doesn't reveal scanner's IP to
target by using intermediate node ("zombie")
- attacker sends SYNACK to zombie to get its IP ID (eg 31337)
- attacker sends SYN to target spoofed from zombie; if port is open, target
sends SYNACK to zombie
- zombie sends RST to target since that's what TCP does on unsolicited
SYNACK; this has IP ID 31338
- attacker sends SYNACK to zombie again to get its new IP ID 31339
- if port wasn't open, attacker's subsequent SYNACK would get 31338
anti-IDS HTTP scanning
- libwhisker: Perl scanner with anti-IDS techniques
- IDSs look for certain things; avoid them
- GET -> HEAD, URL encoding, double slashes, .. traversal, . traversal, \ on
Windows, `\0`, case sensitivity on Windows
- premature request ending: to fool smart IDS systems that try to decode
too aggressively; `GET / HTTP/1.0\r\n...` -> `GET /%20HTTP/1.0%0D%0A`
- param hiding: `foo.cgi?...` -> `foo.cgi%3F...`
- misformatting: eg Apache tolerates tabs in the GET line instead of spaces
- long URLs to bump off what the IDS scans
- splice session across multiple packets
- <http://www.wiretrip.net/rfp/txt/whiskerids.html>
network security tools
- nessus: vuln scanner
- wireshark: packet analyzer
- netcat: swiss army knife
- metasploit: dev framework for exploits
- hping, nmap: network probing
- kismet: wifi sniffer
- tcpdump: packet capture
- cain & abel: windows password recovery
- john the ripper: unix password recovery
- <http://sectools.org/>
IDS/IPS
- snort: network-based; has GUIs (BASE, ACID) built on LAMP
- requires promiscuous sniffing off ethernet hubs or configure to SPAN
(Switched Port Analyzer) a switch port via port mirroring
- ossec: host-based
- file integrity checking, log monitoring, rootkit detection, active response
network hijacking
- TCP hijacking
- if on same segment: easy to just observe seqno and spoof it
- if on diff segment: need to guess initial seqno
- IP/BGP/prefix hijacking: take over groups of IPs by corrupting Internet
routing tables
- announce a prefix that it you don't actually own
- announce a more specific prefix than the true owner's prefix
- announce that you have a shorter route to the target AS
- "black holing": ??
- must hijack BGP TCP session
- DNS cache poisoning: tricking NS into thinking it got authentic info
- specify attacker's choosing of authority NS for either requested domain or
unrelated domains
- bugs in eg BIND allowed the above to slip by; now fixed
- still, no signing means easy to do MITM
- DNSSEC signs responses with PKI-like infrastructure
- DNS rebinding: trick browser into combining diff hosts into 1 origin
- circumvent firewalls; access internal sites
- steps
- register domain
- use own DNS server; set short TTL (1s)
- attract traffic (run ads)
- serve page w JS that issues another request to domain after TTL (2s),
triggering DNS query
- rebind hostname to internal IP (10.10.10.10)
- send response to attacker
- DNS pinning: some browsers (IE) cache for add'l min time (30m)
- still re-queries if can't connect to host
- hence, after initial page load, firewall off the client; rebind works
- wifi
- karma: listen for wifi client probes so that you can eg pretend to be a
familiar AP
- airdrop-ng: deauthorization tool to disassociate APs and clients
- dhcp exhaustion: silence the orig dhcp server, then become mitm dhcp server
that dishes out your own gateway, dns, etc; there's a metasploit module
- DNSSEC: includes hashes ('fingerprints') of cert or full cert chain
- <http://www.imperialviolet.org/2010/08/16/dnssectls.html>
brute-force DOS
- flooding
- DDOS
- easy to detect (? TODO)
sophisticated DOS
- app bugs: eg buffer overflows
- fragmentation of data structures: eg hash tables
- algorithm worst cases, eg regexes
public key crypto
- rsa
- dsa
- elliptic curve
- attractive for mobile/wireless env's
- vs RSA: equiv security with smaller key sizes (faster, less resources)
- use ECDSA
secure ciphers
- rely on bit manip "networks"
- AES uses substitution-permutation network (SPN)
- SPN is simplest way to achieve confusion & diffusion; easily implemented
in HW
- DES uses feistel network
- Shannon properties
- confusion: relationship btwn key & ciphertext as complex/involved as
possible
- diffusion: redundancy in the plaintext statistics is "dissipated" in
ciphertext
- non-uniformity dist in plaintext should be redistributed (somehow)
- ciphertext bits should depend on input bits in very complex way
- changing 1 plaintext bit should completely change ciphertext in
pseudorandom way
block ciphers vs. stream ciphers
- distinction not always clear cut; block ciphers sometimes act effectively as
stream ciphers
- stream ciphers usu. faster, but serious sec problems if used incorrectly
(esp: same starting state must never be reused)
stream ciphers
- _stream cipher_: symmetric key cypher where plaintext is combined with
pseudorandom cipher bit stream called _keystream_, typically xor
- plaintext bits encrypted one at a time
- xform varies during encryption
- rc4: by ron rivest; in (eg) WEP, WPA (default), TLS/SSL (opt), BT, ssh (opt),
RDP, KRB (opt), PDF
- a5/1: in GSM; in US, EU; leaked, rev-eng'd; numerous weaknesses
- can decrypt GSM phone calls in real time
- <http://www.schneier.com/blog/archives/2008/02/cryptanalysis_o_1.html>
- a5/2: a5/1 with deliberate weakening for certain export regions
block ciphers
- _block cipher_: operate on large blocks of digits with a fixed, unvarying
xformation
- eg 128-bit blocks of plaintext -> 128-bit blocks of ciphertext
- des: early highly influential; ibm; 1997; insecure to brute force
- EFF DES cracker aka "deep crack": cracking machine
- with distributed.net, decryted challenge 3 after just 22h
- controversy over NSA's opaque involvement in design
- 3des: 1998; applies des 3x per block; used by electronic payments industry
- simply increases key size 3x to defend against brute force
- pseudocde: des_enc(k1) -> des_dec(k2) -> des_enc(k3)
- blowfish: bruce schneier; 1993; fast; no known cryptanalysis; widely used,
but aes overshadows it
- rc5: rivest cipher
- AES finalists: RC6, twofish, rijndael, serpent, MARS
- aes aka rijndael: successor to des; 2001
- 128, 192, 256 bit key sizes; all 128 bit block sizes
- KASUMI aka a5/3 in GSM aka GEA3 in GPRS: no known weaknesses, but GSM is vuln
(can avoid a5/3)
security status of cryptographic tools
- insecure: MD5, SHA1
- secure: AES, RSA, SHA-2 (SHA-256, SHA-512), SHA-3
- note eg HMAC-MD5 not vuln to MD5 vulns
- HMAC strength depends on secret key len
- brute force is most common attack; less affected by collisions than
underlying hash fns alone
cryptographic hash fns
- SHA: NIST-approved
- SHA-3: SHA-3-512
- blowfish: bruce shneier
- expensive key setup phase
crypt
- uses hash fn, encodes salt, records which hash fn used
- by default, uses DES on data=0, key=truncated pass
- other versions exist that use md5, blowfish, sha
- eksblowfish (provos, mazieres, 1999)
- take adv of expensive key setup phase of blowfish
- introduce configurable # rounds to make validation arbitrary expensive
block cipher modes
- insecure: electronic codebook (ECB)
- output feedback (OFB), cipher feedback (CFB), counter (CTR)
- don't repeat _initialization vector (IV)_ for same encryption key
- turns block ciphers into self-synchronizing stream cipher
- CFB: identical to CBC encryption done in reverse
- OFB: gen keystream blocks that are XORed w plaintext blocks
- cipher block chaining (CBC), propagating CBC (PCBC)
- each plaintext block XORed w prev ciphertext block before encryption
- encryption sequential, but decryption *can* parallelize
- PCBC: also XOR the prev plaintext block
- use this if msg authenticity is not an issue
- authenticated encryption (AE): simultaneously protect confidentiality and
integrity
- AE with associated data (AEAD): block cipher modes
- CCM, CWC, OCB, EAX, GCM
programming
- don't use expert interfaces: OpenSSL, Crypto++, CommonCrypto, CryptoAPI, etc
- use NACL, keyczar if you really need crypto
- otherwise try using PGP/GPG for data-at-rest or TLS for data-in-motion
VPNs
- point-to-point tunneling protocol (PPTP): microsoft's default VPN
protocol
- remains popular
- protoco-independent, but main usage: TCP control stream, GRE data stream
(many firewalls don't support GRE)
- there are alts eg RADIUS but PPTP is default for client back-compat
- doesn't require PKI, unlike L2TP/IPsec
- provides confidentiality, not integrity or authentication
- encapsulates PPP
- layer 2 tunneling protocol (L2TP)
- derived from PPTP
- combines control & data channels
- protocol-indep, but mainly used over UDP 500
- standards bodies attn shifting toward L2TP from PPTP
- uses IPsec ESP by default
- also provides user auth
- encapsulates PPP
- IPsec
- provides confidentiality, integrity, authentication
- uses PKI and machine-level certs
- doesn't provide user auth
- TODO
- secure sockets tunneling protocol (SSTP): tunnels over HTTPS (TCP 443)
- provides confidentiality, integrity, authentication
- encapsulates PPP
- IKEv2: uses IPsec
- provides confidentiality, integrity, authentication
- supports the latest ipsec encryption algos
- supports mobility (MOBIKE); resilient to changing network connectivity; can
switch APs or even wired/wireless
- OpenVPN ALS: web-based SSL VPN server written in Java; derived from Adito,
SSL-Explorer
- provides in-browser HTTPS client access with java applets for tunneling
- misc
- PPTP, L2TP, SSTP depend heavily on features orig for PPP
- built in to windows: PPTP2, L2TP/IPsec, SSTP, IKEv2
- SSTP, IKEv2, maybe others: don't require client-side PKI deployment or pre-shared key
- SSTP, IKEv2, maybe others: integrate well w EAP
- refs
- <http://www.intranetjournal.com/foundation/tunneling.shtml>
- <http://technet.microsoft.com/en-us/library/dd469817(WS.10).aspx>
- <http://blogs.technet.com/rrasblog/archive/2009/02/10/do-we-still-need-pptp-l2tp-ipsec-after-windows-7.aspx>
authentication protocols
- EAP
- authentication framework, not specific mechanism; over 40 methods
- used in wireless networks and point-to-point conns
- adopted by WPA, WPA2
- challenge handshake authentication protocol (MS-CHAPv2)
- the only authentication protocol for windows PPTP
- uses DES
- weaknesses known by 1999; bruce schneier and l0pht wrote a
cryptanalysis
- username is in plaintext
- lightweight extensible authentication protocol (LEAP): cisco-proprietary
extension of EAP; in cisco ap's
- uses modified version of MS-CHAP
- newer: EAP-FAST, PEAP, EAP-TLS
- EAP-TLS: TODO
- u-prove: maintain privacy while proving that i can pay
- TODO can't tell if same person made txns?
wifi
- WEP: can be sniffed by any user
- WPA/WPA2: diff link key per user, unless they can capture initial handshake
- pre-shared key (PSK) means this link key can be recovered trivially from initial handshake
- <http://serverfault.com/questions/149888/wep-wpa-wpa2-and-wifi-sniffing>
windows security
- 2 ways windows stores acct credentials: LAN Manager and NTLM
- LAN Manager: weak; brute force, rainbow tables
- NTLM: time-memory tradeoff attacks
cracking techniques
- brute force
- rainbow tables: sets of precomputed hashes as a time-memory tradeoff
cracking tools
- MS-CHAPv2, LEAP, PPTP
- ASLEAP: cracks LEAP and PPTP; updated to crack MS-CHAPv2
- given MS-CHAPv2 challenge and response, return last 2 bytes of password
hash (username already in plaintext)
- CUPP: common user password profiler; wizard-like dictionary generator
that asks for info about user
- genkeys: generates hashes of a wordlist using DES
- cowpatty: cracks pre-shared key (PSK) WPA networks based on the TKIP
protocol
- MD5
- BarsWF: CUDA-based MD5 cracker; 4B hashes/s with quad SLI;
<http://3.14.by/en/md5>
- windows: LAN Manager, NTLM
- pwdump: outputs LM and NTLM account password hashes from the Security
Account Manager (SAM)
- CUDA-based NTLM brute forcer for linux:
<http://3.14.by/forum/viewtopic.php?f=8&t=60&>
- ophcrack: crack windows passwords using rainbow tables
- usbophcrack: downloads some rainbow tables and creates boot usb
- advise using ophcrack's rainbow tables instead
- <http://revision3.com/hak5/asleap>
windows system security
- ASLR
- DEP: uses NX if avail or software emulation with limited, almost-unrelated
protection with SafeSEH (simply checks that an exception is registered in a
function table for the app)
- common exploit techniques TODO <http://www.hick.org/~mmiller/shellcode/win32/generic.c>
- PEB
- SEH
- steadystate/pc safeguard
- applied only to std accounts; rolls back all reg, fs changes
windows 7 UAC design flaws
- auto-elevating executables: to reduce annoyance
- but anyone can run them; at one pt rundll32 was auto-elevating
- auto-elevating components
- work only when caller is ms-signed exe, eg explorer
- but procs can inject code into ea other as long as same user
- <http://arstechnica.com/microsoft/news/2009/03/opinion-ms-should-kill-win7-uac.ars>
selinux (nsa 2000; merged mainline 2003)
- supplements unix DAC with MAC
- selinux is an implementation of FLASK for linux
- hybrid of concepts and capabilities from MAC, MIC, RBAC
- hard to config
- applies labels to files
- identifies files by inodes
- perms
- specify specific ops (creat, rename, unlink, etc)
- allow, deny, auditallow, auditdeny
linux apparmor (novell 2005)
- supplements unix DAC with MAC
- manually specify profiles for apps
- "learning mode" logs holes that are opened and creates profiles from that
- alternative to selinux
- identifies files by paths instead of inodes
- can make use of FSs with no support for extended file attributes, eg NFS
SFI
---
TODO
efficient software-based fault isolation (wahbe, sosp93)
- [aka "classical SFI"]
- isolate software modules without relying on MMU
- naive custom compiler approach: on a write or indirect branch/jump, check that addr is in current module's range
- slow
- circumventable; eg, indirect branch to own write that skips the checks before it
- use a dedicated reg to hold an addr
- all writes must be performed to the addr in the reg
- reg must always point to valid addr in current module
- if any instr invalidates this, program must fail or fix by the next write/indir jump
- to jump outside, use local jump table; system allows only this table to point outside
- allows indir jumps to be very simple: only check for local
- switch stacks
- callee-save regs: call stub saves regs in case callee does not preserve regs
- opts
- checks can be made into a simple bitmask as long as ranges can be identified by bit prefixes
- stack writes use $esp + small static offsets; hence just validate $esp when it's changed, and pad module space with guard regions that are bigger than biggest offsets
- overhead: 0-12% (avg 4.3%); if also checking reads, avg 21.8%
- [depends on large trusted compiler for correctness; later works like pittsfield use smaller verifier on machine code]
- [not used in practice, maybe bc depends on RISC features like reserving certain regs, maybe bc no robust product]
- [pittsfield, vx32 apply to x86 and have more robust prototypes]
- [vx32 creatively exploits legacy hardware being phased out]
- [SFI has a useful fault iso model that deserves HW support]
- <http://papersincomputerscience.org/2009/12/19/efficient-software-based-fault-isolation/>
pittsfield (stephen mccamant, greg morrisett, TR/usenix 2005)
- SF vs pittsfield: write/jump sandboxing vs full read/write/jump isolation
vx32 (bryan ford, russ cox, TR 2008)
- x86, linux/freebsd
linux containers (lxc)
- can evade lxc as root in lxc by eg sysfs <http://blog.bofh.it/debian/id_413>
- will be fixed upon support for labeling files with user namespaces
- user namespaces: allow normal user to unshare namespaces
- The most glaring reason is that user namespaces are not yet being enforced at
most user id comparisons, including at file system. That means that user id
X in one user namespace will be deemed owner of a file created by user id X
in another user namespace. Toss in root and virtual filesystems like /proc
and /sys, and root in a container can do what he likes with the host. MAC can
help mitigate this, but user namespaces are still being developed to provide
the real solution.
- Another reason, fwiw, is simply that it shares the same kernel as the host.
So any exploits in any system calls can likely be exploited by the container
to gain privilege and escape the host. The worst offenses are usually in
newer system calls, so some hope is being placed in seccomp2 to mitigate this
concern.
- <http://s3hh.wordpress.com/2011/05/31/escaping-chroots/>
engineering
-----------
<http://www.matasano.com/log/989/thoughts-on-ten-years-of-qmail-security/> (DJB 2007)
- directions of progress
- eliminating bugs
- eliminating code
- eliminating trusted code
- distractions
- chasing attackers
- minimizing privilege: vs minimizing TCB
- ["privileges" here are superficial OS level privileges]
- speed
- eliminating bugs
- enforcing explicit data flow: process isolation, PL support
- simplifying integer semantics: used big num lib, PL support
- avoid parsing: anything with strings; quoting; printf bugs
- generalizing from errors to inputs: insert testable abstractions
- eliminating code
- identifying common functions
- automatically handling temporary errors [exceptions better than error checking]
- reusing network tools [like `inetd`]
- reusing access controls: eg assuming a user's uid
- reusing the file system: as an associative array (instead of parsing a
single config file)
- eliminating trusted code
- accurately measuring the TCB: hard
- isolating single-source xforms
- eg jpegtopnm: after jailing, attacker can only produce any img he wants,
but he could've done this in the first place
- sandbox recipe
- Prohibit new files, new sockets, etc., by setting the current and
maximum RLIMIT_NOFILE limits to 0.
- Prohibit filesystem access: chdir and chroot to an empty directory.
- Choose a uid dedicated to this process ID. This can be as simple as
adding the process ID to a base uid, as long as other
system-administration tools stay away from the same uid range.
- Ensure that nothing is running under the uid: fork a child to run
setuid(targetuid), kill(-1,SIGKILL), and _exit(0), and then check that
the child exited normally.
- Prohibit kill(), ptrace(), etc., by setting gid and uid to the target
uid.
- Prohibit fork(), by setting the current and maximum RLIMIT_NPROC limits
to 0.
- Set the desired limits on memory allocation and other resource