-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdatabase.xml
More file actions
499 lines (469 loc) · 20.8 KB
/
database.xml
File metadata and controls
499 lines (469 loc) · 20.8 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
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<!-- EN-Revision: 7204e2dbb9b484c8b67bb5ad4a93fa1369c5b317 Maintainer: ManueldG Status: ready -->
<chapter xml:id="security.database" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Sicurezza del Database</title>
<simpara>
Al giorno d'oggi, i database sono componenti essenziali di qualsiasi
applicazione basata sul Web, consentendo ai siti Web di fornire vari contenuti
dinamici. Poiché anche le informazioni molto sensibili o segrete possono
essere archiviate in un database, dovresti considerare seriamente di
protegere i tuoi database.
</simpara>
<simpara>
Per recuperare o archiviare qualsiasi informazione di cui hai bisogno per connetterti al database,
inviare una query legittima, recuperare il risultato e quindi chiudere la connessione.
Oggigiorno, il linguaggio di query comunemente utilizzato per questo tipo di interazione è
l'SQL (Structured Query Language). Guarda come un aggressore può <link
linkend="security.database.sql-injection">manomettere una query SQL</link>.
</simpara>
<simpara>
Come puoi immaginare, <acronym>PHP</acronym> non può proteggere il database da solo.
Le prossime sezioni mirano a essere un'introduzione di come
accedere e manipolare ai database all'interno di uno script <acronym>PHP</acronym>.
</simpara>
<simpara>
Tieni presente questa semplice regola: difesa in profondità. Più prendi provvedimenti
per aumentare la protezione del database, minore è probabilità che un utente malintenzionato
riesca a esporre o abusare di eventuali dati archiviati. Una buona progettazione
dello schema del database e dell'applicazione previene le tue più grandi paure.
</simpara>
<sect1 xml:id="security.database.design">
<title>Progetazione del database</title>
<simpara>
Il primo passo è quello di creare il database, a meno che non si voglia utilizzarne uno
di terze parti. Quando il database è stato creato, gli viene assegnato a un proprietario,
che ha eseguito l'istruzione di creazione. Di solito, solo il proprietario
(o un superuser) può fare qualsiasi cosa con gli oggetti in quel database e,
per consentire ad altri utenti di utilizzarlo, devono essere concessi dei privilegi.
</simpara>
<simpara>
Le applicazioni non dovrebbero mai connettersi al database come proprietario o
superutente, perché questi utenti possono eseguire qualsiasi query a piacimento,
ad esempio, modificando lo schema (ad esempio eliminando tabelle) o eliminandone
l'intero contenuto.
</simpara>
<simpara>
Puoi creare vari utenti del database uno per ogni funzionalità della tua applicazione
con diritti molto limitati sugli oggetti del database. Dovrebbero essere concessi
solo i privilegi necessari per evitare che lo stesso utente possa modificare
il database tramite le diverse funzionalità. Ciò significa che se gli intrusi ottengono
l'accesso al tuo database utilizzando le credenziali delle tue applicazioni,
possono apportare tante modifiche quante ne possono apportare i tuoi privilegi.
</simpara>
</sect1>
<sect1 xml:id="security.database.connection">
<title>Connessione al database</title>
<simpara>
Potresti voler stabilire connessioni SSL per crittografare le
comunicazioni client/server per una maggiore sicurezza oppure è possibile utilizzare ssh
per crittografare la connessione di rete tra i client e il server del database.
Se viene utilizzato uno di questi, monitorare il traffico e ottenere
le informazioni sul tuo database saranno difficili da parte di un potenziale utente malintenzionato.
</simpara>
<simpara>
Se il tuo server database ha il supporto SSL nativo, considera l'utilizzo di <link
linkend="ref.openssl">Funzioni OpenSSL</link> nella comunicazione tra
<acronym>PHP</acronym> e database tramite SSL.
</simpara>
</sect1>
<sect1 xml:id="security.database.storage">
<title>Modello d'archiviazione crittografato - Encrypted Storage Model</title>
<simpara>
SSL/SSH protegge i dati che viaggiano dal client al server: SSL/SSH
non protegge i dati persistenti archiviati in un database. SSL è un
protocollo on-the-wire.
</simpara>
<simpara>
Una volta che un utente malintenzionato ottiene l'accesso diretto al tuo database (aggirando il server web),
i dati sensibili memorizzati potrebbero essere esposti o utilizzati in modo improprio, a meno che
le informazioni siano protette dal database stesso. La crittografia dei dati
è un buon modo per limitare questa minaccia, ma pochissimi database offrono
questo tipo di crittografia dei dati.
</simpara>
<simpara>
Il modo più semplice per aggirare questo problema è crearne prima uno tuo
pacchetto di crittografia e quindi utilizzarlo dai nei tuoi script <acronym>PHP</acronym>. <acronym>PHP</acronym>
può aiutarti in questo con diverse estensioni, come <link
linkend="book.openssl">OpenSSL</link> e <link
linkend="book.sodium">Sodium</link>, che copre un'ampia varietà di algoritmi di crittografia.
Lo script cripta i dati prima di inserirli nel database e li decripta
durante il recupero. Vedere i riferimenti per ulteriori esempi
di come funziona la crittografia.
</simpara>
<sect2 xml:id="security.database.storage.hashing">
<title>Hashing</title>
<simpara>
Nel caso di dati veramente nascosti(privati- segreti- ), se non è necessaria la loro rappresentazione grezza(originale - )
(p.es. non dev'essere visualizzato), è necessario prendere in considerazione l'hashing.
L'esempio ben noto di hashing è la memorizzazione della password criptata tramite hashing
(è il salvataggio dell'hash della password) nel database,
invece della password stessa.
</simpara>
<simpara>
Le funzioni per <link linkend="ref.password">password</link>
possono fornire un modo conveniente per eseguire l'hashing dei dati sensibili e lavorare con questi hash.
</simpara>
<simpara>
<function>password_hash</function> viene utilizzato per eseguire l'hashing di una determinata stringa utilizzando
l'algoritmo più potente attualmente disponibile e <function>password_verify</function>
controlla se la password fornita corrisponde all'hash memorizzato nel database.
</simpara>
<example>
<title>Campo per l'Hash della password</title>
<programlisting role="php">
<![CDATA[
<?php
// storing password hash
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username),
password_hash($password, PASSWORD_DEFAULT));
$result = pg_query($connection, $query);
// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));
if ($row && password_verify($password, $row['pwd'])) {
echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}
?>
]]>
</programlisting>
</example>
</sect2>
</sect1>
<sect1 xml:id="security.database.sql-injection">
<title>SQL Injection</title>
<simpara>
L'SQL injection è una tecnica dove un utente malintenzionato sfrutta i difetti del
codice responsabile della creazione di query SQL dinamiche.
L'aggressore può accedere a sezioni privilegiate dell'applicazione,
recuperare tutte le informazioni dal database, manomettere i dati esistenti,
o addirittura eseguire comandi pericolosi a livello di sistema sul database
ospite(host). La vulnerabilità si verifica quando gli sviluppatori concatenano o
interpolano dati arbitrari nelle loro istruzioni SQL.
</simpara>
<para>
<example>
<title>
Dividere il set di risultati in pagine ... e creare superutenti
(PostgreSQL)
</title>
<simpara>
Nell'esempio seguente, l'input dell'utente viene interpolato (binding) direttamente nella
Query SQL che consente all'aggressore di ottenere un account superuser(amministratore) nel database.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$offset = $_GET['offset']; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>
]]>
</programlisting>
</example>
Di solito gli utenti usano i collegamenti "next", "previous" dove <varname>$offset</varname>
viene passato nell'<acronym>URL</acronym>. Lo script si aspetta che l'<varname>$offset</varname>
sia un numero. Tuttavia, cosa succede se qualcuno prova a craccarlo
aggiungendo quanto segue all'<acronym>URL</acronym>?
<informalexample>
<programlisting role="sql">
<![CDATA[
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--
]]>
</programlisting>
</informalexample>
Se ciò dovesse accadere, lo script fornirebbe un accesso d'amministratore all'aggressore.
Tieni presente che <literal>0;</literal> fornirebbe un offset valido alla query originale
e la terminerebbe.
</para>
<note>
<para>
È una tecnica comune per forzare il parser SQL a ignorare il resto del file
una query scritta dallo sviluppatore con <literal>--</literal> che introduce
i commenti in SQL.
</para>
</note>
<para>
Un modo possibile per ottenere le password è analizzare le pagine dei risultati di ricerca.
L'unica cosa che l'attaccante deve fare è vedere se sono presenti variabili inviate
utilizzate nelle istruzioni SQL che non vengono gestite correttamente. Questi filtri possono essere impostati
comunemente in una forma precedente per personalizzare <literal>WHERE, ORDER BY,
Clausole LIMIT</literal> e <literal>OFFSET</literal> in <literal>SELECT</literal>
dichiarazioni. Se il tuo database supporta il costrutto <literal>UNION</literal>,
l'aggressore potrebbe tentare di aggiungere un'intera query a quella originale da elencare
password da una tabella arbitraria. Si consiglia vivamente di salvare sole le secure hash delle password
anziché le password stesse.
A feasible way to gain passwords is to circumvent your search result pages.
The only thing the attacker needs to do is to see if there are any submitted variables
used in SQL statements which are not handled properly. These filters can be set
commonly in a preceding form to customize <literal>WHERE, ORDER BY,
LIMIT</literal> and <literal>OFFSET</literal> clauses in <literal>SELECT</literal>
statements. If your database supports the <literal>UNION</literal> construct,
the attacker may try to append an entire query to the original one to list
passwords from an arbitrary table. It is strongly recommended to store only
secure hashes of passwords instead of the passwords themselves.
<example>
<title>
Elenco degli articoli... e alcune password (può essere usato su qualunque server di database).
</title>
<programlisting role="php">
<![CDATA[
<?php
$query = "SELECT id, name, inserted, size FROM products
WHERE size = '$size'";
$result = odbc_exec($conn, $query);
?>
]]>
</programlisting>
</example>
La parte statica della query può essere combinata con un'altra - The static part of the query can be combined with another
<literal>SELECT</literal>dichiarazione che rivela tutte le password: - statement which reveals all passwords:
<informalexample><!--XXX tradotto ricontrollare-->
<programlisting role="sql">
<![CDATA[
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
]]>
</programlisting>
</informalexample>
</para>
<para><!--XXX tradurre-->
<literal>UPDATE</literal> and <literal>INSERT</literal> statements are also
susceptible to such attacks.
<example>
<title>
From resetting a password ... to gaining more privileges (any database server)
</title>
<programlisting role="php">
<![CDATA[
<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
]]>
</programlisting>
</example>
If a malicious user submits the value
<literal>' or uid like'%admin%</literal> to <varname>$uid</varname> to
change the admin's password, or simply sets <varname>$pwd</varname> to
<literal>hehehe', trusted=100, admin='yes</literal> to gain more
privileges, then the query will be twisted:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";
// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";
?>
]]>
</programlisting>
</informalexample>
</para>
<simpara>
While it remains obvious that an attacker must possess at least some
knowledge of the database architecture to conduct a successful
attack, obtaining this information is often very simple. For example,
the code may be part of an open-source software and be publicly available.
This information may also be divulged
by closed-source code - even if it's encoded, obfuscated, or compiled -
and even by your own code through the display of error messages.
Other methods include the use of typical table and column names. For
example, a login form that uses a 'users' table with column names
'id', 'username', and 'password'.
</simpara>
<para>
<example>
<title>Attacking the database host operating system (MSSQL Server)</title>
<simpara>
A frightening example of how operating system-level commands can be
accessed on some database hosts.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>
]]>
</programlisting>
</example>
If attacker submits the value
<literal>a%' exec master..xp_cmdshell 'net user test testpass /ADD' --</literal>
to <varname>$prod</varname>, then the <varname>$query</varname> will be:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);
?>
]]>
</programlisting>
</informalexample>
MSSQL Server executes the SQL statements in the batch including a command
to add a new user to the local accounts database. If this application
were running as <literal>sa</literal> and the MSSQLSERVER service was
running with sufficient privileges, the attacker would now have an
account with which to access this machine.
</para>
<note>
<para>
Some examples above are tied to a specific database server, but it
does not mean that a similar attack is impossible against other products.
Your database server may be similarly vulnerable in another manner.
</para>
</note>
<para>
<mediaobject>
<alt>A funny example of the issues regarding SQL injection</alt>
<imageobject>
<imagedata fileref="en/security/figures/xkcd-bobby-tables.png" format="PNG"/>
</imageobject>
<caption>
<simpara>
Image courtesy of <link xlink:href="&url.xkcd;327">xkcd</link>
</simpara>
</caption>
</mediaobject>
</para>
<sect2 xml:id="security.database.avoiding">
<title>Avoidance Techniques</title>
<para>
The recommended way to avoid SQL injection is by binding all data via
prepared statements. Using parameterized queries isn't enough to entirely
avoid SQL injection, but it is the easiest and safest way to provide input
to SQL statements. All dynamic data literals in <literal>WHERE</literal>,
<literal>SET</literal>, and <literal>VALUES</literal> clauses must be
replaced with placeholders. The actual data will be bound during the
execution and sent separately from the SQL command.
</para>
<para>
Parameter binding can only be used for data. Other dynamic parts of the
SQL query must be filtered against a known list of allowed values.
</para>
<para>
<example>
<title>Avoiding SQL injection by using PDO prepared statements</title>
<programlisting role="php">
<![CDATA[
<?php
// The dynamic SQL part is validated against expected values
$sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
$productId = $_GET['productId'];
// The SQL is prepared with a placeholder
$stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
// The value is provided with LIKE wildcards
$stmt->execute(["%{$productId}%"]);
?>
]]>
</programlisting>
</example>
</para>
<simpara>
Prepared statements are provided
<link linkend="pdo.prepared-statements">by PDO</link>,
<link linkend="mysqli.quickstart.prepared-statements">by MySQLi</link>,
and by other database libraries.
</simpara>
<simpara>
SQL injection attacks are mainly based on exploiting the code not being written
with security in mind. Never trust any input, especially
from the client side, even though it comes from a select box,
a hidden input field, or a cookie. The first example shows that such a
simple query can cause disasters.
</simpara>
<para>
A defense-in-depth strategy involves several good coding practices:
<itemizedlist>
<listitem>
<simpara>
Never connect to the database as a superuser or as the database owner.
Use always customized users with minimal privileges.
</simpara>
</listitem>
<listitem>
<simpara>
Check if the given input has the expected data type. <acronym>PHP</acronym> has
a wide range of input validating functions, from the simplest ones
found in <link linkend="ref.var">Variable Functions</link> and
in <link linkend="ref.ctype">Character Type Functions</link>
(e.g. <function>is_numeric</function>, <function>ctype_digit</function>
respectively) and onwards to the
<link linkend="ref.pcre">Perl Compatible Regular Expressions</link>
support.
</simpara>
</listitem>
<listitem>
<simpara>
If the application expects numerical input, consider verifying data
with <function>ctype_digit</function>, silently change its type
using <function>settype</function>, or use its numeric representation
by <function>sprintf</function>.
</simpara>
</listitem>
<listitem>
<simpara>
If the database layer doesn't support binding variables then
quote each non-numeric user-supplied value that is passed to the
database with the database-specific string escape function (e.g.
<function>mysql_real_escape_string</function>,
<function>sqlite_escape_string</function>, etc.).
Generic functions like <function>addslashes</function> are useful only
in a very specific environment (e.g. MySQL in a single-byte character
set with disabled <varname>NO_BACKSLASH_ESCAPES</varname>), so it is
better to avoid them.
</simpara>
</listitem>
<listitem>
<simpara>
Do not print out any database-specific information, especially
about the schema, by fair means or foul. See also <link
linkend="security.errors">Error Reporting</link> and <link
linkend="ref.errorfunc">Error Handling and Logging Functions</link>.
</simpara>
</listitem>
</itemizedlist>
</para>
<simpara>
Besides these, you benefit from logging queries either within your script
or by the database itself, if it supports logging. Obviously, the logging is unable
to prevent any harmful attempt, but it can be helpful to trace back which
application has been circumvented. The log is not useful by itself but
through the information it contains. More detail is generally better than less.
</simpara>
</sect2>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->