-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.jsonl
848 lines (848 loc) · 184 KB
/
dataset.jsonl
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
{
"input": "void host_lookup(char *user_supplied_addr){\nstruct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);\n\n/*routine that ensures user_supplied_addr is in the right format for conversion */\n\nvalidate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);\n}",
"output": "This program snippet has a vulnerability.This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.This function allocates a buffer of 64 bytes to store the hostname, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker.Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476)."
}
{
"input": "char * copy_input(char *user_supplied_string){\nint i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){die(\"user string too long, die evil hacker!\");}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){\nif( '&' == user_supplied_string[i] ){dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';}else if ('<' == user_supplied_string[i] ){\n/* encode to < */\n\n}else dst_buf[dst_index++] = user_supplied_string[i];\n}return dst_buf;\n}",
"output": "This program snippet has a vulnerability.This example applies an encoding procedure to an input string and stores it into a buffer.The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands."
}
{
"input": "int main (int argc, char **argv) {char *items[] = {\"boat\", \"car\", \"truck\", \"train\"};int index = GetUntrustedOffset();printf(\"You selected %s\\n\", items[index-1]);}",
"output": "This program snippet has a vulnerability.The following example asks a user for an offset into an array to select an item.The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126)."
}
{
"input": "int getValueFromArray(int *array, int len, int index) {\n\nint value;\n\n// check that the array index is less than the maximum\n\n\n// length of the array\nif (index < len) {\n\n// get the value at the specified index of the array\nvalue = array[index];\n}\n// if array index is invalid then output error message\n\n// and return value indicating error\nelse {printf(\"Value is: %d\\n\", array[index]);value = -1;}\nreturn value;\n}",
"output": "This program snippet has a vulnerability.In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the methodHowever, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in a out of bounds read (CWE-125) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below."
}
{
"input": "char last_name[20];printf (\"Enter your last name: \");scanf (\"%s\", last_name);",
"output": "This program snippet has a vulnerability.The following code asks the user to enter their last name and then attempts to store the value entered in the last_name array.The problem with the code above is that it does not restrict or limit the size of the name entered by the user. If the user enters \"Very_very_long_last_name\" which is 24 characters long, then a buffer overflow will occur since the array can only hold 20 characters total."
}
{
"input": "void manipulate_string(char * string){char buf[24];strcpy(buf, string);...}",
"output": "This program snippet has a vulnerability.The following code attempts to create a local copy of a buffer to perform some manipulations to the data.However, the programmer does not ensure that the size of the data pointed to by string will fit in the local buffer and copies the data with the potentially dangerous strcpy() function. This may result in a buffer overflow condition if an attacker can influence the contents of the string parameter."
}
{
"input": "char buf[24];printf(\"Please enter your name and press <Enter>\\n\");gets(buf);...}",
"output": "This program snippet has a vulnerability.The code below calls the gets() function to read in data from the command line.However, gets() is inherently unsafe, because it copies all input from STDIN to the buffer without checking size. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition."
}
{
"input": "...\nstruct hostent *clienthp;char hostname[MAX_LEN];\n// create server socket, bind to server address and listen on socket...\n// accept client connections and process requestsint count = 0;for (count = 0; count < MAX_CONNECTIONS; count++) {\n\nint clientlen = sizeof(struct sockaddr_in);int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr, &clientlen);\nif (clientsocket >= 0) {\nclienthp = gethostbyaddr((char*) &clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);strcpy(hostname, clienthp->h_name);logOutput(\"Accepted client connection from host \", hostname);\n// process client request...close(clientsocket);\n}\n}close(serversocket);\n\n...",
"output": "This program snippet has a vulnerability.In the following example, a server accepts connections from a client and processes the client request. After accepting a client connection, the program will obtain client information using the gethostbyaddr method, copy the hostname of the client that connected to a local variable and output the hostname of the client to a log file.However, the hostname of the client that connected may be longer than the allocated size for the local hostname variable. This will result in a buffer overflow when copying the client hostname to the local variable using the strcpy method."
}
{
"input": "int getValueFromArray(int *array, int len, int index) {\n\nint value;\n\n// check that the array index is less than the maximum\n\n\n// length of the array\nif (index < len) {\n\n\n// get the value at the specified index of the array\nvalue = array[index];\n}\n// if array index is invalid then output error message\n\n\n// and return value indicating error\nelse {printf(\"Value is: %d\\n\", array[index]);value = -1;}\nreturn value;\n}",
"output": "This program snippet has a vulnerability.In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the methodHowever, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in a out of bounds read (CWE-125) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below."
}
{
"input": "...public static final double price = 20.00;int quantity = currentUser.getAttribute(\"quantity\");double total = price * quantity;chargeUser(total);...",
"output": "This program snippet has a vulnerability.This example demonstrates a shopping interaction in which the user is free to specify the quantity of items to be purchased and a total is calculated.The user has no control over the price variable, however the code does not prevent a negative value from being specified for quantity. If an attacker were to provide a negative value, then the user would have their account credited instead of debited."
}
{
"input": "...#define MAX_DIM 100...\n/* board dimensions */\n\nint m,n, error;board_square_t *board;printf(\"Please specify the board height: \\n\");error = scanf(\"%d\", &m);if ( EOF == error ){die(\"No integer passed: Die evil hacker!\\n\");}printf(\"Please specify the board width: \\n\");error = scanf(\"%d\", &n);if ( EOF == error ){die(\"No integer passed: Die evil hacker!\\n\");}if ( m > MAX_DIM || n > MAX_DIM ) {die(\"Value too large: Die evil hacker!\\n\");}board = (board_square_t*) malloc( m * n * sizeof(board_square_t));...",
"output": "This program snippet has a vulnerability.This example asks the user for a height and width of an m X n game board with a maximum dimension of 100 squares.While this code checks to make sure the user cannot specify large, positive integers and consume too much memory, it does not check for negative values supplied by the user. As a result, an attacker can perform a resource consumption (CWE-400) attack against this program by specifying two, large negative values that will not overflow, resulting in a very large memory allocation (CWE-789) and possibly a system crash. Alternatively, an attacker can provide very large negative values which will cause an integer overflow (CWE-190) and unexpected behavior will follow depending on how the values are treated in the remainder of the program."
}
{
"input": "public String getValue(int index) {return array[index];}",
"output": "This program snippet has a vulnerability.In the code snippet below, an untrusted integer value is used to reference an object in an array.If index is outside of the range of the array, this may result in an ArrayIndexOutOfBounds Exception being raised."
}
{
"input": "private void buildList ( int untrustedListSize ){if ( 0 > untrustedListSize ){die(\"Negative value supplied for list size, die evil hacker!\");}Widget[] list = new Widget [ untrustedListSize ];list[0] = new Widget();}",
"output": "This program snippet has a vulnerability.The following example takes a user-supplied value to allocate an array of objects and then operates on the array.This example attempts to build a list from a user-specified value, and even checks to ensure a non-negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0 and then try to store a new Widget in the first location, causing an exception to be thrown."
}
{
"input": "int getValueFromArray(int *array, int len, int index) {\n\nint value;\n\n// check that the array index is less than the maximum\n\n\n// length of the array\nif (index < len) {\n\n// get the value at the specified index of the array\nvalue = array[index];\n}\n// if array index is invalid then output error message\n\n\n// and return value indicating error\nelse {printf(\"Value is: %d\\n\", array[index]);value = -1;}\nreturn value;\n}",
"output": "This program snippet has a vulnerability.In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the methodHowever, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in a out of bounds read (CWE-125) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below."
}
{
"input": "/* capture the sizes of all messages */\nint getsizes(int sock, int count, int *sizes) {\n...char buf[BUFFER_SIZE];int ok;int num, size;\n\n// read values from socket and added to sizes array\nwhile ((ok = gen_recv(sock, buf, sizeof(buf))) == 0){\n\n// continue read from socket until buf only contains '.'\nif (DOTLINE(buf))break;\n else if (sscanf(buf, \"%d %d\", &num, &size) == 2)sizes[num - 1] = size;\n\n}...\n\n}",
"output": "This program snippet has a vulnerability.The following example retrieves the sizes of messages for a pop3 mail server. The message sizes are retrieved from a socket that returns in a buffer the message number and the message size, the message number (num) and size (size) are extracted from the buffer and the message size is placed into an array using the message number for the array index.In this example the message number retrieved from the buffer could be a value that is outside the allowable range of indices for the array and could possibly be a negative number. Without proper validation of the value to be used for the array index an array overflow could occur and could potentially lead to unauthorized access to memory addresses and system crashes. The value of the array index should be validated to ensure that it is within the allowable range of indices for the array as in the following code."
}
{
"input": "// Method called from servlet to obtain product information\npublic String displayProductSummary(int index) {\n\nString productSummary = new String(\"\");\ntry {String productSummary = getProductSummary(index);\n\n} catch (Exception ex) {...}\nreturn productSummary;\n}\npublic String getProductSummary(int index) {return products[index];}",
"output": "This program snippet has a vulnerability.In the following example the method displayProductSummary is called from a Web service servlet to retrieve product summary information for display to the user. The servlet obtains the integer value of the product number from the user and passes it to the displayProductSummary method. The displayProductSummary method passes the integer value of the product number to the getProductSummary method which obtains the product summary from the array object containing the project summaries using the integer value of the product number as the array index.In this example the integer value used as the array index that is provided by the user may be outside the allowable range of indices for the array which may provide unexpected results or cause the application to fail. The integer value used for the array index should be validated to ensure that it is within the allowable range of indices for the array as in the following code.An alternative in Java would be to use one of the collection objects such as ArrayList that will automatically generate an exception if an attempt is made to access an array index that is out of bounds."
}
{
"input": "int main (int argc, char **argv) {char *items[] = {\"boat\", \"car\", \"truck\", \"train\"};int index = GetUntrustedOffset();printf(\"You selected %s\\n\", items[index-1]);}",
"output": "This program snippet has a vulnerability.The following example asks a user for an offset into an array to select an item.The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126)."
}
{
"input": "int i;unsigned int numWidgets;Widget **WidgetList;\nnumWidgets = GetUntrustedSizeValue();if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {ExitError(\"Incorrect number of widgets requested!\");}WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));printf(\"WidgetList ptr=%p\\n\", WidgetList);for(i=0; i<numWidgets; i++) {WidgetList[i] = InitializeWidget();}WidgetList[numWidgets] = NULL;showWidgets(WidgetList);",
"output": "This program snippet has a vulnerability.The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption."
}
{
"input": "img_t table_ptr; /*struct containing img data, 10kB each*/int num_imgs;...num_imgs = get_num_imgs();table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs);...",
"output": "This program snippet has a vulnerability.The following image processing code allocates a table for images.This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119)."
}
{
"input": "char * copy_input(char *user_supplied_string){\nint i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){die(\"user string too long, die evil hacker!\");}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){\nif( '&' == user_supplied_string[i] ){dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';}else if ('<' == user_supplied_string[i] ){\n\n\n/* encode to < */\n\n\n}else dst_buf[dst_index++] = user_supplied_string[i];\n}return dst_buf;\n}",
"output": "This program snippet has a vulnerability.This example applies an encoding procedure to an input string and stores it into a buffer.The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands."
}
{
"input": "DataPacket *packet;int numHeaders;PacketHeader *headers;\nsock=AcceptSocketConnection();ReadPacket(packet, sock);numHeaders =packet->headers;\nif (numHeaders > 100) {ExitError(\"too many headers!\");}headers = malloc(numHeaders * sizeof(PacketHeader);ParsePacketHeaders(packet, headers);",
"output": "This program snippet has a vulnerability.The following code is intended to read an incoming packet from a socket and extract one or more headers.The code performs a check to make sure that the packet does not contain too many headers. However, numHeaders is defined as a signed int, so it could be negative. If the incoming packet specifies a value such as -3, then the malloc calculation will generate a negative number (say, -300 if each header can be a maximum of 100 bytes). When this result is provided to malloc(), it is first converted to a size_t type. This conversion then produces a large value such as 4294966996, which may cause malloc() to fail or to allocate an extremely large amount of memory (CWE-195). With the appropriate negative numbers, an attacker could trick malloc() into using a very small positive number, which then allocates a buffer that is much smaller than expected, potentially leading to a buffer overflow."
}
{
"input": "int *id_sequence;\n\n/* Allocate space for an array of three ids. */\n\n\nid_sequence = (int*) malloc(3);if (id_sequence == NULL) exit(1);\n\n/* Populate the id array. */\n\n\nid_sequence[0] = 13579;id_sequence[1] = 24680;id_sequence[2] = 97531;",
"output": "This program snippet has a vulnerability.The following code attempts to save three different identification numbers into an array. The array is allocated from memory using a call to malloc().The problem with the code above is the value of the size parameter used during the malloc() call. It uses a value of '3' which by definition results in a buffer of three bytes to be created. However the intention was to create a buffer that holds three ints, and in C, each int requires 4 bytes worth of memory, so an array of 12 bytes is needed, 4 bytes for each int. Executing the above code could result in a buffer overflow as 12 bytes of data is being saved into 3 bytes worth of allocated space. The overflow would occur during the assignment of id_sequence[0] and would continue with the assignment of id_sequence[1] and id_sequence[2].The malloc() call could have used '3*sizeof(int)' as the value for the size parameter in order to allocate the correct amount of space required to store the three ints."
}
{
"input": "#include <stdio.h>\nvoid printWrapper(char *string) {\n\nprintf(string);\n}\nint main(int argc, char **argv) {\n\nchar buf[5012];memcpy(buf, argv[1], 5012);printWrapper(argv[1]);return (0);\n}",
"output": "This program snippet has a vulnerability.The following program prints a string provided as an argument.The example is exploitable, because of the call to printf() in the printWrapper() function. Note: The stack buffer was added to make exploitation more simple."
}
{
"input": "int main(int argc, char **argv){char buf[128];...snprintf(buf,128,argv[1]);}",
"output": "This program snippet has a vulnerability.The following code copies a command line argument into a buffer using snprintf().This code allows an attacker to view the contents of the stack and write to the stack using a command line argument containing a sequence of formatting directives. The attacker can read from the stack by providing more formatting directives, such as %x, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.) By using the %n formatting directive, the attacker can write to the stack, causing snprintf() to write the number of bytes output thus far to the specified argument (rather than reading a value from the argument, which is the intended behavior). A sophisticated version of this attack will use four staggered writes to completely control the value of a pointer on the stack."
}
{
"input": "printf(\"%d %d %1$d %1$d\\n\", 5, 9);",
"output": "This program snippet has a vulnerability.Certain implementations make more advanced attacks even easier by providing format directives that control the location in memory to read from or write to. An example of these directives is shown in the following code, written for glibc:This code produces the following output: 5 9 5 5 It is also possible to use half-writes (%hn) to accurately control arbitrary DWORDS in memory, which greatly reduces the complexity needed to execute an attack that would otherwise require four staggered writes, such as the one mentioned in the first example."
}
{
"input": "public String preventXSS(String input, String mask) {return input.replaceAll(\"script\", mask);}",
"output": "This program snippet has a vulnerability.In the following example, an XSS neutralization method intends to replace script tags in user-supplied input with a safe equivalent:The code only works when the \"script\" tag is in all lower-case, forming an incomplete denylist (CWE-184). Equivalent tags such as \"SCRIPT\" or \"ScRiPt\" will not be neutralized by this method, allowing an XSS attack."
}
{
"input": "img_t table_ptr; /*struct containing img data, 10kB each*/int num_imgs;...num_imgs = get_num_imgs();table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs);...",
"output": "This program snippet has a vulnerability.The following image processing code allocates a table for images.This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119)."
}
{
"input": "nresp = packet_get_int();if (nresp > 0) {response = xmalloc(nresp*sizeof(char*));for (i = 0; i < nresp; i++) response[i] = packet_get_string(NULL);}",
"output": "This program snippet has a vulnerability.The following code excerpt from OpenSSH 3.3 demonstrates a classic case of integer overflow:If nresp has the value 1073741824 and sizeof(char*) has its typical value of 4, then the result of the operation nresp*sizeof(char*) overflows, and the argument to xmalloc() will be 0. Most malloc() implementations will happily allocate a 0-byte buffer, causing the subsequent loop iterations to overflow the heap buffer response."
}
{
"input": "short int bytesRec = 0;char buf[SOMEBIGNUM];\nwhile(bytesRec < MAXGET) {bytesRec += getFromInput(buf+bytesRec);}",
"output": "This program snippet has a vulnerability.Integer overflows can be complicated and difficult to detect. The following example is an attempt to show how an integer overflow may lead to undefined looping behavior:In the above case, it is entirely possible that bytesRec may overflow, continuously creating a lower number than MAXGET and also overwriting the first MAXGET-1 bytes of buf."
}
{
"input": "#define JAN 1#define FEB 2#define MAR 3\nshort getMonthlySales(int month) {...}\nfloat calculateRevenueForQuarter(short quarterSold) {...}\nint determineFirstQuarterRevenue() {\n\n\n// Variable for sales revenue for the quarter\nfloat quarterRevenue = 0.0f;\nshort JanSold = getMonthlySales(JAN); /* Get sales in January */short FebSold = getMonthlySales(FEB); /* Get sales in February */short MarSold = getMonthlySales(MAR); /* Get sales in March */\n\n// Calculate quarterly total\nshort quarterSold = JanSold + FebSold + MarSold;\n\n// Calculate the total revenue for the quarter\nquarterRevenue = calculateRevenueForQuarter(quarterSold);\nsaveFirstQuarterRevenue(quarterRevenue);\nreturn 0;\n}",
"output": "This program snippet has a vulnerability.In this example the method determineFirstQuarterRevenue is used to determine the first quarter revenue for an accounting/business application. The method retrieves the monthly sales totals for the first three months of the year, calculates the first quarter sales totals from the monthly sales totals, calculates the first quarter revenue based on the first quarter sales, and finally saves the first quarter revenue results to the database.However, in this example the primitive type short int is used for both the monthly and the quarterly sales variables. In C the short int primitive type has a maximum value of 32768. This creates a potential integer overflow if the value for the three monthly sales adds up to more than the maximum value for the short int primitive type. An integer overflow can lead to data corruption, unexpected behavior, infinite loops and system crashes. To correct the situation the appropriate primitive type should be used, as in the example below, and/or provide some validation mechanism to ensure that the maximum value for the primitive type is not exceeded.Note that an integer overflow could also occur if the quarterSold variable has a primitive type long but the method calculateRevenueForQuarter has a parameter of type short."
}
{
"input": "#include <stdio.h>#include <stdbool.h>main (void){int i;i = -2147483648;i = i - 1;return 0;}",
"output": "This program snippet has a vulnerability.The following example subtracts from a 32 bit signed integer.The example has an integer underflow. The value of i is already at the lowest negative value possible, so after subtracting 1, the new value of i is 2147483647."
}
{
"input": "int a = 5, b = 6;\n\t\t size_t len = a - b;\n\t\t char buf[len]; // Just blows up the stack\n\t\t \n\t\t }",
"output": "This program snippet has a vulnerability.This code performs a stack allocation based on a length calculation.Since a and b are declared as signed ints, the \"a - b\" subtraction gives a negative result (-1). However, since len is declared to be unsigned, len is cast to an extremely large positive number (on 32-bit systems - 4294967295). As a result, the buffer buf[len] declaration uses an extremely large size to allocate on the stack, very likely more than the entire computer's memory space.Miscalculations usually will not be so obvious. The calculation will either be complicated or the result of an attacker's input to attain the negative value."
}
{
"input": "int i;unsigned int numWidgets;Widget **WidgetList;\nnumWidgets = GetUntrustedSizeValue();if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {ExitError(\"Incorrect number of widgets requested!\");}WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));printf(\"WidgetList ptr=%p\\n\", WidgetList);for(i=0; i<numWidgets; i++) {WidgetList[i] = InitializeWidget();}WidgetList[numWidgets] = NULL;showWidgets(WidgetList);",
"output": "This program snippet has a vulnerability.The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption."
}
{
"input": "char firstname[20];char lastname[20];char fullname[40];fullname[0] = '\\0';strncat(fullname, firstname, 20);strncat(fullname, lastname, 20);",
"output": "This program snippet has a vulnerability.In this example, the code does not account for the terminating null character, and it writes one byte beyond the end of the buffer.The first call to strncat() appends up to 20 characters plus a terminating null character to fullname[]. There is plenty of allocated space for this, and there is no weakness associated with this first call. However, the second call to strncat() potentially appends another 20 characters. The code does not account for the terminating null character that is automatically added by strncat(). This terminating null character would be written one byte beyond the end of the fullname[] buffer. Therefore an off-by-one error exists with the second strncat() call, as the third argument should be 19.When using a function like strncat() one must leave a free byte at the end of the buffer for a terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument to strncat() is the number of characters to append, which must be less than the remaining space in the buffer. Be careful not to just use the total size of the buffer."
}
{
"input": "#define PATH_SIZE 60\nchar filename[PATH_SIZE];\nfor(i=0; i<=PATH_SIZE; i++) {\n\nchar c = getc();if (c == 'EOF') {filename[i] = '\\0';}\nfilename[i] = getc();\n}",
"output": "This program snippet has a vulnerability.The Off-by-one error can also be manifested when reading characters from a character array within a for loop that has an incorrect continuation condition.In this case, the correct continuation condition is shown below."
}
{
"input": "int setFilename(char *filename) {char name[20];sprintf(name, \"%16s.dat\", filename);int success = saveFormattedFilenameToDB(name);return success;}",
"output": "This program snippet has a vulnerability.As another example the Off-by-one error can occur when using the sprintf library function to copy a string variable to a formatted string variable and the original string variable comes from an untrusted source. As in the following example where a local function, setFilename is used to store the value of a filename to a database but first uses sprintf to format the filename. The setFilename function includes an input parameter with the name of the file that is used as the copy source in the sprintf function. The sprintf function will copy the file name to a char array of size 20 and specifies the format of the new variable as 16 characters followed by the file extension .dat.However this will cause an Off-by-one error if the original filename is exactly 16 characters or larger because the format of 16 characters with the file extension is exactly 20 characters and does not take into account the required null terminator that will be placed at the end of the string."
}
{
"input": "...public static final double price = 20.00;int quantity = currentUser.getAttribute(\"quantity\");double total = price * quantity;chargeUser(total);...",
"output": "This program snippet has a vulnerability.This example demonstrates a shopping interaction in which the user is free to specify the quantity of items to be purchased and a total is calculated.The user has no control over the price variable, however the code does not prevent a negative value from being specified for quantity. If an attacker were to provide a negative value, then the user would have their account credited instead of debited."
}
{
"input": "...#define MAX_DIM 100...\n/* board dimensions */\n\nint m,n, error;board_square_t *board;printf(\"Please specify the board height: \\n\");error = scanf(\"%d\", &m);if ( EOF == error ){die(\"No integer passed: Die evil hacker!\\n\");}printf(\"Please specify the board width: \\n\");error = scanf(\"%d\", &n);if ( EOF == error ){die(\"No integer passed: Die evil hacker!\\n\");}if ( m > MAX_DIM || n > MAX_DIM ) {die(\"Value too large: Die evil hacker!\\n\");}board = (board_square_t*) malloc( m * n * sizeof(board_square_t));...",
"output": "This program snippet has a vulnerability.This example asks the user for a height and width of an m X n game board with a maximum dimension of 100 squares.While this code checks to make sure the user cannot specify large, positive integers and consume too much memory, it does not check for negative values supplied by the user. As a result, an attacker can perform a resource consumption (CWE-400) attack against this program by specifying two, large negative values that will not overflow, resulting in a very large memory allocation (CWE-789) and possibly a system crash. Alternatively, an attacker can provide very large negative values which will cause an integer overflow (CWE-190) and unexpected behavior will follow depending on how the values are treated in the remainder of the program."
}
{
"input": "private void buildList ( int untrustedListSize ){if ( 0 > untrustedListSize ){die(\"Negative value supplied for list size, die evil hacker!\");}Widget[] list = new Widget [ untrustedListSize ];list[0] = new Widget();}",
"output": "This program snippet has a vulnerability.The following example takes a user-supplied value to allocate an array of objects and then operates on the array.This example attempts to build a list from a user-specified value, and even checks to ensure a non-negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0 and then try to store a new Widget in the first location, causing an exception to be thrown."
}
{
"input": "...\nIntentFilter filter = new IntentFilter(\"com.example.URLHandler.openURL\");MyReceiver receiver = new MyReceiver();registerReceiver(receiver, filter);\n...\n\npublic class UrlHandlerReceiver extends BroadcastReceiver {\n@Overridepublic void onReceive(Context context, Intent intent) {\nif(\"com.example.URLHandler.openURL\".equals(intent.getAction())) {String URL = intent.getStringExtra(\"URLToOpen\");int length = URL.length();\n\n...\n}\n}\n}",
"output": "This program snippet has a vulnerability.This Android application has registered to handle a URL when sent an intent:The application assumes the URL will always be included in the intent. When the URL is not present, the call to getStringExtra() will return null, thus causing a null pointer exception when length() is called."
}
{
"input": "public BankAccount getUserBankAccount(String username, String accountNumber) {\nBankAccount userAccount = null;String query = null;try {if (isAuthorizedUser(username)) {query = \"SELECT * FROM accounts WHERE owner = \"+ username + \" AND accountID = \" + accountNumber;DatabaseManager dbManager = new DatabaseManager();Connection conn = dbManager.getConnection();Statement stmt = conn.createStatement();ResultSet queryResult = stmt.executeQuery(query);userAccount = (BankAccount)queryResult.getObject(accountNumber);}} catch (SQLException ex) {String logMessage = \"Unable to retrieve account information from database,\\nquery: \" + query;Logger.getLogger(BankManager.class.getName()).log(Level.SEVERE, logMessage, ex);}return userAccount;\n}",
"output": "This program snippet has a vulnerability.In the example below, the method getUserBankAccount retrieves a bank account object from a database using the supplied username and account number to query the database. If an SQLException is raised when querying the database, an error message is created and output to a log file.The error message that is created includes information about the database query that may contain sensitive information about the database or query logic. In this case, the error message will expose the table name and column names used in the database. This data could be used to simplify other attacks, such as SQL injection (CWE-89) to directly access the database."
}
{
"input": "locationClient = new LocationClient(this, this, this);locationClient.connect();currentUser.setLocation(locationClient.getLastLocation());\n...\n\ncatch (Exception e) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage(\"Sorry, this application has experienced an error.\");AlertDialog alert = builder.create();alert.show();Log.e(\"ExampleActivity\", \"Caught exception: \" + e + \" While on User:\" + User.toString());}",
"output": "This program snippet has a vulnerability.This code stores location information about the current user:When the application encounters an exception it will write the user object to the log. Because the user object contains location information, the user's location is also written to the log."
}
{
"input": "locationClient = new LocationClient(this, this, this);locationClient.connect();Location userCurrLocation;userCurrLocation = locationClient.getLastLocation();deriveStateFromCoords(userCurrLocation);",
"output": "This program snippet has a vulnerability.This code uses location to determine the user's current US State location.First the application must declare that it requires the ACCESS_FINE_LOCATION permission in the application's manifest.xml:During execution, a call to getLastLocation() will return a location based on the application's location permissions. In this case the application has permission for the most accurate location possible:While the application needs this information, it does not need to use the ACCESS_FINE_LOCATION permission, as the ACCESS_COARSE_LOCATION permission will be sufficient to identify which US state the user is in."
}
{
"input": "try {/.../}catch (Exception e) {System.out.println(e);}",
"output": "This program snippet has a vulnerability.In the following example, sensitive information might be printed depending on the exception that occurs.If an exception related to SQL is handled by the catch, then the output might contain sensitive information such as SQL query structure or private information. If this output is redirected to a web user, this may represent a security problem."
}
{
"input": "public BankAccount getUserBankAccount(String username, String accountNumber) {\nBankAccount userAccount = null;String query = null;try {if (isAuthorizedUser(username)) {query = \"SELECT * FROM accounts WHERE owner = \"+ username + \" AND accountID = \" + accountNumber;DatabaseManager dbManager = new DatabaseManager();Connection conn = dbManager.getConnection();Statement stmt = conn.createStatement();ResultSet queryResult = stmt.executeQuery(query);userAccount = (BankAccount)queryResult.getObject(accountNumber);}} catch (SQLException ex) {String logMessage = \"Unable to retrieve account information from database,\\nquery: \" + query;Logger.getLogger(BankManager.class.getName()).log(Level.SEVERE, logMessage, ex);}return userAccount;\n}",
"output": "This program snippet has a vulnerability.In the example below, the method getUserBankAccount retrieves a bank account object from a database using the supplied username and account number to query the database. If an SQLException is raised when querying the database, an error message is created and output to a log file.The error message that is created includes information about the database query that may contain sensitive information about the database or query logic. In this case, the error message will expose the table name and column names used in the database. This data could be used to simplify other attacks, such as SQL injection (CWE-89) to directly access the database."
}
{
"input": "String filename = System.getProperty(\"com.domain.application.dictionaryFile\");File dictionaryFile = new File(filename);",
"output": "This program snippet has a vulnerability.In the example below, the path to a dictionary file is read from a system property and used to initialize a File object.However, the path is not validated or modified to prevent it from containing relative or absolute path sequences before creating the File object. This allows anyone who can control the system property to determine what file is used. Ideally, the path should be resolved relative to some kind of application or user home directory."
}
{
"input": "String path = getInputPath();if (path.startsWith(\"/safe_dir/\")){File f = new File(path);f.delete()}",
"output": "This program snippet has a vulnerability.The following code attempts to validate a given input path by checking it against an allowlist and once validated delete the given file. In this specific case, the path is considered valid if it starts with the string \"/safe_dir/\".An attacker could provide an input such as this:The software assumes that the path is valid because it starts with the \"/safe_path/\" sequence, but the \"../\" sequence will cause the program to delete the important.dat file in the parent directory"
}
{
"input": "public class FileUploadServlet extends HttpServlet {\n\n...\nprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\nresponse.setContentType(\"text/html\");PrintWriter out = response.getWriter();String contentType = request.getContentType();\n// the starting position of the boundary headerint ind = contentType.indexOf(\"boundary=\");String boundary = contentType.substring(ind+9);\nString pLine = new String();String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value\n// verify that content type is multipart form dataif (contentType != null && contentType.indexOf(\"multipart/form-data\") != -1) {\n\n// extract the filename from the Http headerBufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));...pLine = br.readLine();String filename = pLine.substring(pLine.lastIndexOf(\"\\\\\"), pLine.lastIndexOf(\"\\\"\"));...\n// output the file to the local upload directorytry {\nBufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));for (String line; (line=br.readLine())!=null; ) {if (line.indexOf(boundary) == -1) {bw.write(line);bw.newLine();bw.flush();}} //end of for loopbw.close();\n\n\n} catch (IOException ex) {...}// output successful upload response HTML page\n}// output unsuccessful upload response HTML pageelse{...}\n}...\n\n}",
"output": "This program snippet has a vulnerability.The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet.When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory.This code does not perform a check on the type of the file being uploaded (CWE-434). This could allow an attacker to upload any executable file or other file with malicious code. Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-23). Since the code does not check the filename that is provided in the header, an attacker can use \"../\" sequences to write to files outside of the intended directory. Depending on the executing environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or system crash."
}
{
"input": "import os\n import sys\n def main():\n\n filename = sys.argv[1]\n path = os.path.join(os.getcwd(), filename)\n try:\n\n with open(path, 'r') as f:\n\n file_data = f.read()\n\n\n except FileNotFoundError as e:\n\n print(\"Error - file not found\")\n\n\n main()",
"output": "This program snippet has a vulnerability.This script intends to read a user-supplied file from the current directory. The user inputs the relative path to the file and the script uses Python's os.path.join() function to combine the path to the current working directory with the provided path to the specified file. This results in an absolute path to the desired file. If the file does not exist when the script attempts to read it, an error is printed to the user.However, if the user supplies an absolute path, the os.path.join() function will discard the path to the current working directory and use only the absolute path provided. For example, if the current working directory is /home/user/documents, but the user inputs /etc/passwd, os.path.join() will use only /etc/passwd, as it is considered an absolute path. In the above scenario, this would cause the script to access and read the /etc/passwd file.The constructed path string uses os.sep to add the appropriate separation character for the given operating system (e.g. '\\' or '/') and the call to os.path.normpath() removes any additional slashes that may have been entered - this may occur particularly when using a Windows path. By putting the pieces of the path string together in this fashion, the script avoids a call to os.path.join() and any potential issues that might arise if an absolute path is entered. With this version of the script, if the current working directory is /home/user/documents, and the user inputs /etc/passwd, the resulting path will be /home/user/documents/etc/passwd. The user is therefore contained within the current working directory as intended."
}
{
"input": "char buf[10], cp_buf[10];fgets(buf, 10, stdin);strcpy(cp_buf, buf);",
"output": "This program snippet has a vulnerability.Consider the following code segment:The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy()."
}
{
"input": "int returnChunkSize(void *) {\n\n\n/* if chunk info is valid, return the size of usable memory,\n\n\n* else, return -1 to indicate an error\n\n\n*/\n...\n}int main() {...memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));...}",
"output": "This program snippet has a vulnerability.In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788)."
}
{
"input": "buf = (char*) malloc(req_size);strncpy(buf, xfer, req_size);",
"output": "This program snippet has a vulnerability.The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc().The traditional defense of this coding error is: \"If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or allow the program to die with a segmentation fault when it tries to dereference the null pointer.\" This argument ignores three important considerations:\n\n\nDepending upon the type and size of the application, it may be possible to free memory that is being used elsewhere so that execution can continue.\n\n\nIt is impossible for the program to perform a graceful exit if required. If the program is performing an atomic operation, it can leave the system in an inconsistent state.\n\n\nThe programmer has lost the opportunity to record diagnostic information. Did the call to malloc() fail because req_size was too large or because there were too many requests being handled at the same time? Or was it caused by a memory leak that has built up over time? Without handling the error, there is no way to know."
}
{
"input": "FileInputStream fis;byte[] byteArray = new byte[1024];for (Iterator i=users.iterator(); i.hasNext();) {\nString userName = (String) i.next();String pFileName = PFILE_ROOT + \"/\" + userName;FileInputStream fis = new FileInputStream(pFileName);fis.read(byteArray); // the file is always 1k bytesfis.close();processPFile(userName, byteArray);",
"output": "This program snippet has a vulnerability.The following examples read a file into a byte array.The code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always 1 kilobyte in size and therefore ignores the return value from Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and treat it as though it belongs to the attacker."
}
{
"input": "String itemName = request.getParameter(ITEM_NAME);if (itemName.compareTo(IMPORTANT_ITEM) == 0) {...}...",
"output": "This program snippet has a vulnerability.The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference.The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "String itemName = request.Item(ITEM_NAME);if (itemName.Equals(IMPORTANT_ITEM)) {...}...",
"output": "This program snippet has a vulnerability.The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference.The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "System.clearProperty(\"os.name\");...String os = System.getProperty(\"os.name\");if (os.equalsIgnoreCase(\"Windows 95\")) System.out.println(\"Not supported\");",
"output": "This program snippet has a vulnerability.The following code shows a system property that is set to null and later dereferenced by a programmer who mistakenly assumes it will always be defined.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "void host_lookup(char *user_supplied_addr){\nstruct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);\n\n/*routine that ensures user_supplied_addr is in the right format for conversion */\n\nvalidate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);\n}",
"output": "This program snippet has a vulnerability.This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119)."
}
{
"input": "void f(pthread_mutex_t *mutex) {\npthread_mutex_lock(mutex);\n\n/* access shared resource */\n\n\npthread_mutex_unlock(mutex);\n}",
"output": "This program snippet has a vulnerability.The following function attempts to acquire a lock in order to perform operations on a shared resource.However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels."
}
{
"input": "def makeNewUserDir(username):\nif invalidUsername(username):\n\n\n#avoid CWE-22 and CWE-78 \nprint('Usernames cannot contain invalid characters')return False\n\ntry:raisePrivileges()os.mkdir('/home/' + username)lowerPrivileges()\nexcept OSError:print('Unable to create new user directory for user:' + username)return False\nreturn True",
"output": "This program snippet has a vulnerability.This code temporarily raises the program's privileges to allow creation of a new user folder.While the program only raises its privilege level to create the folder and immediately lowers it again, if the call to os.mkdir() throws an exception, the call to lowerPrivileges() will not occur. As a result, the program is indefinitely operating in a raised privilege state, possibly allowing further exploitation to occur."
}
{
"input": "seteuid(0);\n/* do some stuff */\n\nseteuid(getuid());",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "AccessController.doPrivileged(new PrivilegedAction() {\npublic Object run() {\n// privileged code goes here, for example:\nSystem.loadLibrary(\"awt\");return null;\n// nothing to return\n\n}",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "public enum Roles {ADMIN,USER,GUEST}\npublic void printDebugInfo(User requestingUser){\nif(isAuthenticated(requestingUser)){\nswitch(requestingUser.role){\ncase GUEST:System.out.println(\"You are not authorized to perform this command\");break;\ndefault:System.out.println(currentDebugState());break;\n\n}\n}else{System.out.println(\"You must be logged in to perform this command\");}\n}",
"output": "This program snippet has a vulnerability.This code intends to allow only Administrators to print debug information about a system.While the intention was to only allow Administrators to print the debug information, the code as written only excludes those with the role of \"GUEST\". Someone with the role of \"ADMIN\" or \"USER\" will be allowed access, which goes against the original intent. An attacker may be able to use this debug information to craft an attack on the system."
}
{
"input": "public enum Roles {ADMIN,OPERATOR,USER,GUEST}\npublic void resetPassword(User requestingUser, User user, String password ){\nif(isAuthenticated(requestingUser)){\nswitch(requestingUser.role){\ncase GUEST:System.out.println(\"You are not authorized to perform this command\");break;\ncase USER:System.out.println(\"You are not authorized to perform this command\");break;\ndefault:setPassword(user,password);break;}\n}\n\nelse{System.out.println(\"You must be logged in to perform this command\");}\n}",
"output": "This program snippet has a vulnerability.This code allows someone with the role of \"ADMIN\" or \"OPERATOR\" to reset a user's password. The role of \"OPERATOR\" is intended to have less privileges than an \"ADMIN\", but still be able to help users with small issues such as forgotten passwords.This code does not check the role of the user whose password is being reset. It is possible for an Operator to gain Admin privileges by resetting the password of an Admin account and taking control of that account."
}
{
"input": "bool DoSecureStuff(HANDLE hPipe) {bool fDataWritten = false;ImpersonateNamedPipeClient(hPipe);HANDLE hFile = CreateFile(...);/../RevertToSelf()/../}",
"output": "This program snippet has a vulnerability.This code attempts to take on the privileges of a user before creating a file, thus avoiding performing the action with unnecessarily high privileges:The call to ImpersonateNamedPipeClient may fail, but the return value is not checked. If the call fails, the code may execute with higher privileges than intended. In this case, an attacker could exploit this behavior to write a file to a location that the attacker does not have access to."
}
{
"input": "String sourceIP = request.getRemoteAddr();if (sourceIP != null && sourceIP.equals(APPROVED_IP)) {authenticated = true;}",
"output": "This program snippet has a vulnerability.The following code authenticates users.The authentication mechanism implemented relies on an IP address for source validation. If an attacker is able to spoof the IP, they may be able to bypass the authentication mechanism."
}
{
"input": "sd = socket(AF_INET, SOCK_DGRAM, 0);serv.sin_family = AF_INET;serv.sin_addr.s_addr = htonl(INADDR_ANY);servr.sin_port = htons(1008);bind(sd, (struct sockaddr *) & serv, sizeof(serv));\nwhile (1) {memset(msg, 0x0, MAX_MSG);clilen = sizeof(cli);if (inet_ntoa(cli.sin_addr)==getTrustedAddress()) {n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *) & cli, &clilen);}}",
"output": "This program snippet has a vulnerability.Both of these examples check if a request is from a trusted address before responding to the request.The code only verifies the address as stored in the request packet. An attacker can spoof this address, thus impersonating a trusted client."
}
{
"input": "while(true) {\nDatagramPacket rp=new DatagramPacket(rData,rData.length);outSock.receive(rp);String in = new String(p.getData(),0, rp.getLength());InetAddress clientIPAddress = rp.getAddress();int port = rp.getPort();\nif (isTrustedAddress(clientIPAddress) & secretKey.equals(in)) {out = secret.getBytes();DatagramPacket sp =new DatagramPacket(out,out.length, IPAddress, port); outSock.send(sp);}\n}",
"output": "This program snippet has a vulnerability.Both of these examples check if a request is from a trusted address before responding to the request.The code only verifies the address as stored in the request packet. An attacker can spoof this address, thus impersonating a trusted client."
}
{
"input": "struct hostent *hp;struct in_addr myaddr;char* tHost = \"trustme.example.com\";myaddr.s_addr=inet_addr(ip_addr_string);\nhp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET);if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) {trusted = true;} else {trusted = false;}",
"output": "This program snippet has a vulnerability.The following code samples use a DNS lookup in order to decide whether or not an inbound request is from a trusted host. If an attacker can poison the DNS cache, they can gain trusted status.IP addresses are more reliable than DNS names, but they can also be spoofed. Attackers can easily forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication."
}
{
"input": "String ip = request.getRemoteAddr();InetAddress addr = InetAddress.getByName(ip);if (addr.getCanonicalHostName().endsWith(\"trustme.com\")) {trusted = true;}",
"output": "This program snippet has a vulnerability.The following code samples use a DNS lookup in order to decide whether or not an inbound request is from a trusted host. If an attacker can poison the DNS cache, they can gain trusted status.IP addresses are more reliable than DNS names, but they can also be spoofed. Attackers can easily forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication."
}
{
"input": "if ((cert = SSL_get_peer_certificate(ssl)) && host)foo=SSL_get_verify_result(ssl);\nif ((X509_V_OK==foo) || X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN==foo))\n\n\n// certificate looks good, host can be trusted",
"output": "This program snippet has a vulnerability.This code checks the certificate of a connected peer.In this case, because the certificate is self-signed, there was no external authority that could prove the identity of the host. The program could be communicating with a different system that is spoofing the host, e.g. by poisoning the DNS cache or using an Adversary-in-the-Middle (AITM) attack to modify the traffic from server to client."
}
{
"input": "cert = SSL_get_peer_certificate(ssl);if (cert && (SSL_get_verify_result(ssl)==X509_V_OK)) {\n\n\n// do secret things\n\n\n}",
"output": "This program snippet has a vulnerability.The following OpenSSL code obtains a certificate and verifies it.Even though the \"verify\" step returns X509_V_OK, this step does not include checking the Common Name against the name of the host. That is, there is no guarantee that the certificate is for the desired host. The SSL connection could have been established with a malicious host that provided a valid certificate."
}
{
"input": "if (cert = SSL_get_peer(certificate(ssl)) {\nfoo=SSL_get_verify_result(ssl);if ((X509_V_OK==foo) || (X509_V_ERR_CERT_HAS_EXPIRED==foo))\n\n\n//do stuff",
"output": "This program snippet has a vulnerability.The following OpenSSL code ensures that there is a certificate and allows the use of expired certificates.If the call to SSL_get_verify_result() returns X509_V_ERR_CERT_HAS_EXPIRED, this means that the certificate has expired. As time goes on, there is an increasing chance for attackers to compromise the certificate."
}
{
"input": "if (cert = SSL_get_peer_certificate(ssl)) {\n\n\n// got a certificate, do secret things",
"output": "This program snippet has a vulnerability.The following OpenSSL code ensures that there is a certificate before continuing execution.Because this code does not use SSL_get_verify_results() to check the certificate, it could accept certificates that have been revoked (X509_V_ERR_CERT_REVOKED). The software could be communicating with a malicious host."
}
{
"input": "if (cert = SSL_get_peer_certificate(ssl)) {\n\n\n// got certificate, host can be trusted\n\n\n//foo=SSL_get_verify_result(ssl);\n\n\n//if (X509_V_OK==foo) ...\n\n\n}",
"output": "This program snippet has a vulnerability.The following OpenSSL code ensures that the host has a certificate.Note that the code does not call SSL_get_verify_result(ssl), which effectively disables the validation step that checks the certificate."
}
{
"input": "public BankAccount createBankAccount(String accountNumber, String accountType,String accountName, String accountSSN, double balance) {\n\nBankAccount account = new BankAccount();account.setAccountNumber(accountNumber);account.setAccountType(accountType);account.setAccountOwnerName(accountName);account.setAccountOwnerSSN(accountSSN);account.setBalance(balance);\nreturn account;\n}",
"output": "This program snippet has a vulnerability.In the following Java example the method createBankAccount is used to create a BankAccount object for a bank management application.However, there is no authentication mechanism to ensure that the user creating this bank account object has the authority to create new bank accounts. Some authentication mechanisms should be used to verify that the user has the authority to create bank account objects.The following Java code includes a boolean variable and method for authenticating a user. If the user has not been authenticated then the createBankAccount will not create the bank account object."
}
{
"input": "String username = request.getParameter(\"username\");String password = request.getParameter(\"password\");\nint authResult = authenticateUser(username, password);",
"output": "This program snippet has a vulnerability.The following code, extracted from a servlet's doPost() method, performs an authentication lookup every time the servlet is invoked.However, the software makes no attempt to restrict excessive authentication attempts."
}
{
"input": "int validateUser(char *host, int port){\nint socket = openSocketConnection(host, port);if (socket < 0) {printf(\"Unable to open socket connection\");return(FAIL);}\nint isValidUser = 0;char username[USERNAME_SIZE];char password[PASSWORD_SIZE];\nwhile (isValidUser == 0) {\nif (getNextMessage(socket, username, USERNAME_SIZE) > 0) {if (getNextMessage(socket, password, PASSWORD_SIZE) > 0) {isValidUser = AuthenticateUser(username, password);}}\n}return(SUCCESS);\n}",
"output": "This program snippet has a vulnerability.In the following C/C++ example the validateUser method opens a socket connection, reads a username and password from the socket and attempts to authenticate the username and password.The validateUser method will continuously check for a valid username and password without any restriction on the number of authentication attempts made. The method should limit the number of authentication attempts made to prevent brute force attacks as in the following example code."
}
{
"input": "server.sin_family = AF_INET; hp = gethostbyname(argv[1]);if (hp==NULL) error(\"Unknown host\");memcpy( (char *)&server.sin_addr,(char *)hp->h_addr,hp->h_length);if (argc < 3) port = 80;else port = (unsigned short)atoi(argv[3]);server.sin_port = htons(port);if (connect(sock, (struct sockaddr *)&server, sizeof server) < 0) error(\"Connecting\");...while ((n=read(sock,buffer,BUFSIZE-1))!=-1) {\n\nwrite(dfd,password_buffer,n);...",
"output": "This program snippet has a vulnerability.The following code attempts to establish a connection, read in a password, then store it to a buffer.While successful, the program does not encrypt the data before writing it to a buffer, possibly exposing it to unauthorized actors."
}
{
"input": "try {URL u = new URL(\"http://www.secret.example.org/\");HttpURLConnection hu = (HttpURLConnection) u.openConnection();hu.setRequestMethod(\"PUT\");hu.connect();OutputStream os = hu.getOutputStream();hu.disconnect();}catch (IOException e) {\n\n\n//...\n\n\n}",
"output": "This program snippet has a vulnerability.The following code attempts to establish a connection to a site to communicate sensitive information.Though a connection is successfully made, the connection is unencrypted and it is possible that all sensitive data sent to or received from the server will be read by unintended actors."
}
{
"input": "response.addCookie( new Cookie(\"userAccountID\", acctID);",
"output": "This program snippet has a vulnerability.The following code excerpt stores a plaintext user account ID in a browser cookie.Because the account ID is in plaintext, the user's account information is exposed if their computer is compromised by an attacker."
}
{
"input": "server.sin_family = AF_INET; hp = gethostbyname(argv[1]);if (hp==NULL) error(\"Unknown host\");memcpy( (char *)&server.sin_addr,(char *)hp->h_addr,hp->h_length);if (argc < 3) port = 80;else port = (unsigned short)atoi(argv[3]);server.sin_port = htons(port);if (connect(sock, (struct sockaddr *)&server, sizeof server) < 0) error(\"Connecting\");...while ((n=read(sock,buffer,BUFSIZE-1))!=-1) {\n\nwrite(dfd,password_buffer,n);...",
"output": "This program snippet has a vulnerability.The following code attempts to establish a connection, read in a password, then store it to a buffer.While successful, the program does not encrypt the data before writing it to a buffer, possibly exposing it to unauthorized actors."
}
{
"input": "# Java Web App ResourceBundle properties file\n...webapp.ldap.username=secretUsernamewebapp.ldap.password=secretPassword...",
"output": "This program snippet has a vulnerability.The following examples show a portion of properties and configuration files for Java and ASP.NET applications. The files include username and password information but they are stored in cleartext.This Java example shows a properties file with a cleartext username / password pair.The following example shows a portion of a configuration file for an ASP.Net application. This configuration file includes username and password information for a connection to a database but the pair is stored in cleartext.Username and password information should not be included in a configuration file or a properties file in cleartext as this will allow anyone who can read the file access to the resource. If possible, encrypt this information."
}
{
"input": "try {URL u = new URL(\"http://www.secret.example.org/\");HttpURLConnection hu = (HttpURLConnection) u.openConnection();hu.setRequestMethod(\"PUT\");hu.connect();OutputStream os = hu.getOutputStream();hu.disconnect();}catch (IOException e) {\n//...\n\n}",
"output": "This program snippet has a vulnerability.The following code attempts to establish a connection to a site to communicate sensitive information.Though a connection is successfully made, the connection is unencrypted and it is possible that all sensitive data sent to or received from the server will be read by unintended actors."
}
{
"input": "EVP_des_ecb();",
"output": "This program snippet has a vulnerability.These code examples use the Data Encryption Standard (DES).Once considered a strong algorithm, DES now regarded as insufficient for many applications. It has been replaced by Advanced Encryption Standard (AES)."
}
{
"input": "Cipher des=Cipher.getInstance(\"DES...\");des.initEncrypt(key2);",
"output": "This program snippet has a vulnerability.These code examples use the Data Encryption Standard (DES).Once considered a strong algorithm, DES now regarded as insufficient for many applications. It has been replaced by Advanced Encryption Standard (AES)."
}
{
"input": "String GenerateReceiptURL(String baseUrl) {Random ranGen = new Random();ranGen.setSeed((new Date()).getTime());return(baseUrl + ranGen.nextInt(400000000) + \".html\");}",
"output": "This program snippet has a vulnerability.The following code uses a statistical PRNG to create a URL for a receipt that remains active for some period of time after a purchase.This code uses the Random.nextInt() function to generate \"unique\" identifiers for the receipt pages it generates. Because Random.nextInt() is a statistical PRNG, it is easy for an attacker to guess the strings it generates. Although the underlying design of the receipt system is also faulty, it would be more secure if it used a random number generator that did not produce predictable receipt identifiers, such as a cryptographic PRNG."
}
{
"input": "String GenerateReceiptURL(String baseUrl) {Random ranGen = new Random();ranGen.setSeed((new Date()).getTime());return(baseUrl + ranGen.nextInt(400000000) + \".html\");}",
"output": "This program snippet has a vulnerability.The following code uses a statistical PRNG to create a URL for a receipt that remains active for some period of time after a purchase.This code uses the Random.nextInt() function to generate \"unique\" identifiers for the receipt pages it generates. Because Random.nextInt() is a statistical PRNG, it is easy for an attacker to guess the strings it generates. Although the underlying design of the receipt system is also faulty, it would be more secure if it used a random number generator that did not produce predictable receipt identifiers, such as a cryptographic PRNG."
}
{
"input": "Random random = new Random(System.currentTimeMillis());int accountID = random.nextInt();",
"output": "This program snippet has a vulnerability.Both of these examples use a statistical PRNG seeded with the current value of the system clock to generate a random number:The random number functions used in these examples, rand() and Random.nextInt(), are not considered cryptographically strong. An attacker may be able to predict the random numbers generated by these functions. Note that these example also exhibit CWE-337 (Predictable Seed in PRNG)."
}
{
"input": "srand(time());int randNum = rand();",
"output": "This program snippet has a vulnerability.Both of these examples use a statistical PRNG seeded with the current value of the system clock to generate a random number:The random number functions used in these examples, rand() and Random.nextInt(), are not considered cryptographically strong. An attacker may be able to predict the random numbers generated by these functions. Note that these example also exhibit CWE-337 (Predictable Seed in PRNG)."
}
{
"input": "IntentFilter filter = new IntentFilter(\"com.example.RemoveUser\");MyReceiver receiver = new MyReceiver();registerReceiver(receiver, filter);\npublic class DeleteReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {int userID = intent.getIntExtra(\"userID\");destroyUserData(userID);}}",
"output": "This program snippet has a vulnerability.This Android application will remove a user account when it receives an intent to do so:This application does not check the origin of the intent, thus allowing any malicious application to remove a user. Always check the origin of an intent, or create an allowlist of trusted applications using the manifest.xml file."
}
{
"input": "// Android\n@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url){\nif (url.substring(0,14).equalsIgnoreCase(\"examplescheme:\")){if(url.substring(14,25).equalsIgnoreCase(\"getUserInfo\")){writeDataToView(view, UserData);return false;}else{return true;}}\n}",
"output": "This program snippet has a vulnerability.These Android and iOS applications intercept URL loading within a WebView and perform special actions if a particular URL scheme is used, thus allowing the Javascript within the WebView to communicate with the application:A call into native code can then be initiated by passing parameters within the URL:Because the application does not check the source, a malicious website loaded within this WebView has the same access to the API as a trusted site."
}
{
"input": "File f = new File(downloadedFilePath);JarFile jf = new JarFile(f);",
"output": "This program snippet has a vulnerability.In the following code, a JarFile object is created from a downloaded file.The JAR file that was potentially downloaded from an untrusted source is created without verifying the signature (if present). An alternate constructor that accepts a boolean verify parameter should be used instead."
}
{
"input": "sd = socket(AF_INET, SOCK_DGRAM, 0); serv.sin_family = AF_INET;serv.sin_addr.s_addr = htonl(INADDR_ANY);servr.sin_port = htons(1008);bind(sd, (struct sockaddr *) & serv, sizeof(serv));while (1) {\n\nmemset(msg, 0x0, MAX_MSG);clilen = sizeof(cli);if (inet_ntoa(cli.sin_addr)==...) n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *) & cli, &clilen);\n}",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "while(true) {DatagramPacket packet = new DatagramPacket(data,data.length,IPAddress, port);socket.send(sendPacket);}",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "void f(pthread_mutex_t *mutex) {\npthread_mutex_lock(mutex);\n\n/* access shared resource */\n\n\npthread_mutex_unlock(mutex);\n}",
"output": "This program snippet has a vulnerability.The following function attempts to acquire a lock in order to perform operations on a shared resource.However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels."
}
{
"input": "struct stat *sb;...lstat(\"...\",sb); // it has not been updated since the last time it was readprintf(\"stated file\\n\");if (sb->st_mtimespec==...){print(\"Now updating things\\n\");updateThings();}",
"output": "This program snippet has a vulnerability.The following code checks a file, then updates its contents.Potentially the file could have been updated between the time of the check and the lstat, especially since the printf has latency."
}
{
"input": "if(!access(file,W_OK)) {f = fopen(file,\"w+\");operate(f);...}else {\n\nfprintf(stderr,\"Unable to open file %s.\\n\",file);\n}",
"output": "This program snippet has a vulnerability.The following code is from a program installed setuid root. The program performs certain file operations on behalf of non-privileged users, and uses access checks to ensure that it does not use its root privileges to perform operations that should otherwise be unavailable the current user. The program uses the access() system call to check if the person running the program has permission to access the specified file before it opens the file and performs the necessary operations.The call to access() behaves as expected, and returns 0 if the user running the program has the necessary permissions to write to the file, and -1 otherwise. However, because both access() and fopen() operate on filenames rather than on file handles, there is no guarantee that the file variable still refers to the same file on disk when it is passed to fopen() that it did when it was passed to access(). If an attacker replaces file after the call to access() with a symbolic link to a different file, the program will use its root privileges to operate on the file even if it is a file that the attacker would otherwise be unable to modify. By tricking the program into performing an operation that would otherwise be impermissible, the attacker has gained elevated privileges. This type of vulnerability is not limited to programs with root privileges. If the application is capable of performing any operation that the attacker would not otherwise be allowed perform, then it is a possible target."
}
{
"input": "#include <sys/types.h>\n\t\t #include <sys/stat.h>\n\n\t\t ...\n\n\t\t struct stat sb;\n\t\t stat(\"MYFILE.txt\",&sb);\n\t\t printf(\"file change time: %d\\n\",sb->st_ctime);\n\t\t switch(sb->st_ctime % 2){\n\t\t case 0: printf(\"Option 1\\n\"); break;\n\t\t case 1: printf(\"Option 2\\n\"); break;\n\t\t default: printf(\"this should be unreachable?\\n\"); break;\n}",
"output": "This program snippet has a vulnerability.This example is adapted from [REF-18]. Assume that this code block is invoked from multiple threads. The switch statement will execute different code depending on the time when MYFILE.txt was last changed. If this code block were executed within multiple threads, and MYFILE.txt changed between the operation of one thread and another, then the switch could produce different, possibly unexpected results."
}
{
"input": "public int computeAverageResponseTime (int totalTime, int numRequests) {return totalTime / numRequests;}",
"output": "This program snippet has a vulnerability.The following Java example contains a function to compute an average but does not validate that the input value used as the denominator is not zero. This will create an exception for attempting to divide by zero. If this error is not handled by Java exception handling, unexpected results can occur.By validating the input value used as the denominator the following code will ensure that a divide by zero error will not cause unexpected results. The following Java code example will validate the input value, output an error message, and throw an exception."
}
{
"input": "double divide(double x, double y){return x/y;}",
"output": "This program snippet has a vulnerability.The following C/C++ example contains a function that divides two numeric values without verifying that the input value used as the denominator is not zero. This will create an error for attempting to divide by zero, if this error is not caught by the error handling capabilities of the language, unexpected results can occur.By validating the input value used as the denominator the following code will ensure that a divide by zero error will not cause unexpected results. If the method is called and a zero is passed as the second argument a DivideByZero error will be thrown and should be caught by the calling block with an output message indicating the error.Example 2 References:[REF-371] Alex Allain. \"Handling Errors Exceptionally Well in C++\". <https://www.cprogramming.com/tutorial/exceptions.html>. URL validated: 2023-04-07."
}
{
"input": "private void auth(LoginContext lc, HttpSession session) throws LoginException {...lc.login();...}",
"output": "This program snippet has a vulnerability.The following example shows a snippet of code from a J2EE web application where the application authenticates users with LoginContext.login() without first calling HttpSession.invalidate().In order to exploit the code above, an attacker could first create a session (perhaps by logging into the application) from a public terminal, record the session identifier assigned by the application, and reset the browser to the login page. Next, a victim sits down at the same public terminal, notices the browser open to the login page of the site, and enters credentials to authenticate against the application. The code responsible for authenticating the victim continues to use the pre-existing session identifier, now the attacker simply uses the session identifier recorded earlier to access the victim's active session, providing nearly unrestricted access to the victim's account for the lifetime of the session. Even given a vulnerable application, the success of the specific attack described here is dependent on several factors working in the favor of the attacker: access to an unmonitored public terminal, the ability to keep the compromised session active and a victim interested in logging into the vulnerable application on the public terminal.In most circumstances, the first two challenges are surmountable given a sufficient investment of time. Finding a victim who is both using a public terminal and interested in logging into the vulnerable application is possible as well, so long as the site is reasonably popular. The less well known the site is, the lower the odds of an interested victim using the public terminal and the lower the chance of success for the attack vector described above. The biggest challenge an attacker faces in exploiting session fixation vulnerabilities is inducing victims to authenticate against the vulnerable application using a session identifier known to the attacker.In the example above, the attacker did this through a direct method that is not subtle and does not scale suitably for attacks involving less well-known web sites. However, do not be lulled into complacency; attackers have many tools in their belts that help bypass the limitations of this attack vector. The most common technique employed by attackers involves taking advantage of cross-site scripting or HTTP response splitting vulnerabilities in the target site [12]. By tricking the victim into submitting a malicious request to a vulnerable application that reflects JavaScript or other code back to the victim's browser, an attacker can create a cookie that will cause the victim to reuse a session identifier controlled by the attacker. It is worth noting that cookies are often tied to the top level domain associated with a given URL. If multiple applications reside on the same top level domain, such as bank.example.com and recipes.example.com, a vulnerability in one application can allow an attacker to set a cookie with a fixed session identifier that will be used in all interactions with any application on the domain example.com [29]."
}
{
"input": "class Worker implements Executor {\n...public void execute(Runnable r) {\n\ntry {...}catch (InterruptedException ie) {\n\n\n// postpone response\nThread.currentThread().interrupt();\n}\n}\npublic Worker(Channel ch, int nworkers) {...}\nprotected void activate() {\n\nRunnable loop = new Runnable() {\n\npublic void run() {\n\ntry {for (;;) {Runnable r = ...;r.run();}}catch (InterruptedException ie) {...}\n}\n};new Thread(loop).start();\n}\n}",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness.There are no limits to runnables. Potentially an attacker could cause resource problems very quickly."
}
{
"input": "sock=socket(AF_INET, SOCK_STREAM, 0);while (1) {newsock=accept(sock, ...);printf(\"A connection has been accepted\\n\");pid = fork();}",
"output": "This program snippet has a vulnerability.This code allocates a socket and forks each time it receives a new connection.The program does not track how many connections have been made, and it does not limit the number of connections. Because forking is a relatively expensive operation, an attacker would be able to cause the system to run out of CPU, processes, or memory by making a large number of connections. Alternatively, an attacker could consume all available connections, preventing others from accessing the system remotely."
}
{
"input": "int writeDataFromSocketToFile(char *host, int port){\n\nchar filename[FILENAME_SIZE];char buffer[BUFFER_SIZE];int socket = openSocketConnection(host, port);\nif (socket < 0) {printf(\"Unable to open socket connection\");return(FAIL);}if (getNextMessage(socket, filename, FILENAME_SIZE) > 0) {\nif (openFileToWrite(filename) > 0) {\nwhile (getNextMessage(socket, buffer, BUFFER_SIZE) > 0){if (!(writeToFile(buffer) > 0))break;\n}\n}closeFile();\n}closeSocket(socket);\n}",
"output": "This program snippet has a vulnerability.In the following example a server socket connection is used to accept a request to store data on the local file system using a specified filename. The method openSocketConnection establishes a server socket to accept requests from a client. When a client establishes a connection to this service the getNextMessage method is first used to retrieve from the socket the name of the file to store the data, the openFileToWrite method will validate the filename and open a file to write to on the local file system. The getNextMessage is then used within a while loop to continuously read data from the socket and output the data to the file until there is no longer any data from the socket.This example creates a situation where data can be dumped to a file on the local file system without any limits on the size of the file. This could potentially exhaust file or disk resources and/or limit other clients' ability to access the service."
}
{
"input": "/* process message accepts a two-dimensional character array of the form [length][body] containing the message to be processed */\nint processMessage(char **message){\nchar *body;\nint length = getMessageLength(message[0]);\nif (length > 0) {body = &message[1][0];processMessageBody(body);return(SUCCESS);}else {printf(\"Unable to process message; invalid message length\");return(FAIL);}\n}",
"output": "This program snippet has a vulnerability.In the following example, the processMessage method receives a two dimensional character array containing the message to be processed. The two-dimensional character array contains the length of the message in the first character array and the message body in the second character array. The getMessageLength method retrieves the integer value of the length from the first character array. After validating that the message length is greater than zero, the body character array pointer points to the start of the second character array of the two-dimensional character array and memory is allocated for the new body character array.This example creates a situation where the length of the body character array can be very large and will consume excessive memory, exhausting system resources. This can be avoided by restricting the length of the second character array with a maximum length checkAlso, consider changing the type from 'int' to 'unsigned int', so that you are always guaranteed that the number is positive. This might not be possible if the protocol specifically requires allowing negative values, or if you cannot control the return value from getMessageLength(), but it could simplify the check to ensure the input is positive, and eliminate other errors such as signed-to-unsigned conversion errors (CWE-195) that may occur elsewhere in the code."
}
{
"input": "public void acceptConnections() {\n\ntry {ServerSocket serverSocket = new ServerSocket(SERVER_PORT);int counter = 0;boolean hasConnections = true;while (hasConnections) {Socket client = serverSocket.accept();Thread t = new Thread(new ClientSocketThread(client));t.setName(client.getInetAddress().getHostName() + \":\" + counter++);t.start();}serverSocket.close();\n\n} catch (IOException ex) {...}\n}",
"output": "This program snippet has a vulnerability.In the following example, a server object creates a server socket and accepts client connections to the socket. For every client connection to the socket a separate thread object is generated using the ClientSocketThread class that handles request made by the client through the socket.In this example there is no limit to the number of client connections and client threads that are created. Allowing an unlimited number of client connections and threads could potentially overwhelm the system and system resources.The server should limit the number of client connections and the client threads that are created. This can be easily done by creating a thread pool object that limits the number of threads that are generated."
}
{
"input": "char* getBlock(int fd) {\nchar* buf = (char*) malloc(BLOCK_SIZE);if (!buf) {return NULL;}if (read(fd, buf, BLOCK_SIZE) != BLOCK_SIZE) {\n\nreturn NULL;\n}return buf;\n}",
"output": "This program snippet has a vulnerability.The following C function leaks a block of allocated memory if the call to read() does not return the expected number of bytes:"
}
{
"input": "private void processFile(string fName){BufferReader fil = new BufferReader(new FileReader(fName));String line;while ((line = fil.ReadLine()) != null){processLine(line);}}",
"output": "This program snippet has a vulnerability.The following method never closes the new file handle. Given enough time, the Finalize() method for BufferReader should eventually call Close(), but there is no guarantee as to how long this action will take. In fact, there is no guarantee that Finalize() will ever be invoked. In a busy environment, the Operating System could use up all of the available file handles before the Close() function is called.The good code example simply adds an explicit call to the Close() function when the system is done using the file. Within a simple example such as this the problem is easy to see and fix. In a real system, the problem may be considerably more obscure."
}
{
"input": "try {Connection con = DriverManager.getConnection(some_connection_string);}catch ( Exception e ) {log( e );}",
"output": "This program snippet has a vulnerability.This code attempts to open a connection to a database and catches any exceptions that may occur.If an exception occurs after establishing the database connection and before the same connection closes, the pool of database connections may become exhausted. If the number of available connections is exceeded, other users cannot access this resource, effectively denying access to the application."
}
{
"input": "int decodeFile(char* fName) {\nchar buf[BUF_SZ];FILE* f = fopen(fName, \"r\");if (!f) {printf(\"cannot open %s\\n\", fName);return DECODE_FAIL;}else {\nwhile (fgets(buf, BUF_SZ, f)) {if (!checkChecksum(buf)) {return DECODE_FAIL;}else {decodeBlock(buf);}}\n}fclose(f);return DECODE_SUCCESS;\n}",
"output": "This program snippet has a vulnerability.The following C function does not close the file handle it opens if an error occurs. If the process is long-lived, the process can run out of file handles."
}
{
"input": "class A {void foo();};void A::foo(){int *ptr;ptr = (int*)malloc(sizeof(int));delete ptr;}",
"output": "This program snippet has a vulnerability.In this example, the program does not use matching functions such as malloc/free, new/delete, and new[]/delete[] to allocate/deallocate the resource."
}
{
"input": "class A{void foo(bool);};void A::foo(bool heap) {int localArray[2] = {11,22};int *p = localArray;if (heap){p = new int[2];}delete[] p;}",
"output": "This program snippet has a vulnerability.In this example, the program calls the delete[] function on non-heap memory."
}
{
"input": "char* ptr = (char*)malloc (SIZE);...if (abrt) {free(ptr);}...free(ptr);",
"output": "This program snippet has a vulnerability.The following code shows a simple example of a double free vulnerability.Double free vulnerabilities have two common (and sometimes overlapping) causes:\n\n\nError conditions and other exceptional circumstances\n\n\nConfusion over which part of the program is responsible for freeing the memory\n\n\nAlthough some double free vulnerabilities are not much more complicated than this example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once."
}
{
"input": "#include <stdio.h>#include <unistd.h>#define BUFSIZE1 512#define BUFSIZE2 ((BUFSIZE1/2) - 8)\nint main(int argc, char **argv) {char *buf1R1;char *buf2R1;char *buf1R2;buf1R1 = (char *) malloc(BUFSIZE2);buf2R1 = (char *) malloc(BUFSIZE2);free(buf1R1);free(buf2R1);buf1R2 = (char *) malloc(BUFSIZE1);strncpy(buf1R2, argv[1], BUFSIZE1-1);free(buf2R1);free(buf1R2);}",
"output": "This program snippet has a vulnerability.While contrived, this code should be exploitable on Linux distributions that do not ship with heap-chunk check summing turned on."
}
{
"input": "#include <stdio.h>#include <unistd.h>#define BUFSIZER1 512#define BUFSIZER2 ((BUFSIZER1/2) - 8)int main(int argc, char **argv) {char *buf1R1;char *buf2R1;char *buf2R2;char *buf3R2;buf1R1 = (char *) malloc(BUFSIZER1);buf2R1 = (char *) malloc(BUFSIZER1);free(buf2R1);buf2R2 = (char *) malloc(BUFSIZER2);buf3R2 = (char *) malloc(BUFSIZER2);strncpy(buf2R1, argv[1], BUFSIZER1-1);free(buf1R1);free(buf2R2);free(buf3R2);}",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "char* ptr = (char*)malloc (SIZE);if (err) {abrt = 1;free(ptr);}...if (abrt) {logError(\"operation aborted before commit\", ptr);}",
"output": "This program snippet has a vulnerability.The following code illustrates a use after free error:When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function."
}
{
"input": "#define DIR \"/restricted/directory\"\nchar cmd[500];sprintf(cmd, \"ls -l %480s\", DIR);\n/* Raise privileges to those needed for accessing DIR. */\n\nRaisePrivileges(...);system(cmd);DropPrivileges(...);...",
"output": "This program snippet has a vulnerability.This program is intended to execute a command that lists the contents of a restricted directory, then performs other actions. Assume that it runs with setuid privileges in order to bypass the permissions check by the operating system.This code may look harmless at first, since both the directory and the command are set to fixed values that the attacker can't control. The attacker can only see the contents for DIR, which is the intended program behavior. Finally, the programmer is also careful to limit the code that executes with raised privileges.However, because the program does not modify the PATH environment variable, the following attack would work:"
}
{
"input": "...System.Runtime.getRuntime().exec(\"make\");...",
"output": "This program snippet has a vulnerability.The following code is from a web application that allows users access to an interface through which they can update their password on the system. In this environment, user passwords can be managed using the Network Information System (NIS), which is commonly used on UNIX systems. When performing NIS updates, part of the process for updating passwords is to run a make command in the /var/yp directory. Performing NIS updates requires extra privileges.The problem here is that the program does not specify an absolute path for make and does not clean its environment prior to executing the call to Runtime.exec(). If an attacker can modify the $PATH variable to point to a malicious binary called make and cause the program to be executed in their environment, then the malicious binary will be loaded instead of the one intended. Because of the nature of the application, it runs with the privileges necessary to perform system operations, which means the attacker's make will now be run with these privileges, possibly giving the attacker complete control of the system."
}
{
"input": "...System.Runtime.getRuntime().exec(\"make\");...",
"output": "This program snippet has a vulnerability.The following code is from a web application that allows users access to an interface through which they can update their password on the system. In this environment, user passwords can be managed using the Network Information System (NIS), which is commonly used on UNIX systems. When performing NIS updates, part of the process for updating passwords is to run a make command in the /var/yp directory. Performing NIS updates requires extra privileges.The problem here is that the program does not specify an absolute path for make and does not clean its environment prior to executing the call to Runtime.exec(). If an attacker can modify the $PATH variable to point to a malicious binary called make and cause the program to be executed in their environment, then the malicious binary will be loaded instead of the one intended. Because of the nature of the application, it runs with the privileges necessary to perform system operations, which means the attacker's make will now be run with these privileges, possibly giving the attacker complete control of the system."
}
{
"input": "UINT errCode = WinExec( \"C:\\\\Program Files\\\\Foo\\\\Bar\", SW_SHOW );",
"output": "This program snippet has a vulnerability.The following example demonstrates the weakness."
}
{
"input": "public class FileUploadServlet extends HttpServlet {\n\n...\nprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\nresponse.setContentType(\"text/html\");PrintWriter out = response.getWriter();String contentType = request.getContentType();\n// the starting position of the boundary headerint ind = contentType.indexOf(\"boundary=\");String boundary = contentType.substring(ind+9);\nString pLine = new String();String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value\n// verify that content type is multipart form dataif (contentType != null && contentType.indexOf(\"multipart/form-data\") != -1) {\n\n// extract the filename from the Http headerBufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));...pLine = br.readLine();String filename = pLine.substring(pLine.lastIndexOf(\"\\\\\"), pLine.lastIndexOf(\"\\\"\"));...\n// output the file to the local upload directorytry {\nBufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));for (String line; (line=br.readLine())!=null; ) {if (line.indexOf(boundary) == -1) {bw.write(line);bw.newLine();bw.flush();}} //end of for loopbw.close();\n\n\n} catch (IOException ex) {...}// output successful upload response HTML page\n}// output unsuccessful upload response HTML pageelse{...}\n}...\n\n}",
"output": "This program snippet has a vulnerability.The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet.When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory.This code does not perform a check on the type of the file being uploaded (CWE-434). This could allow an attacker to upload any executable file or other file with malicious code. Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-23). Since the code does not check the filename that is provided in the header, an attacker can use \"../\" sequences to write to files outside of the intended directory. Depending on the executing environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or system crash."
}
{
"input": "try {InputStream is = new FileInputStream(path);byte b[] = new byte[is.available()];is.read(b);is.close();} catch (Throwable t) {log.error(\"Something bad happened: \" + t.getMessage());}",
"output": "This program snippet has a vulnerability.Stream resources in a Java application should be released in a finally block, otherwise an exception thrown before the call to close() would result in an unreleased I/O resource. In the example below, the close() method is called in the try block (incorrect)."
}
{
"input": "String ctl = request.getParameter(\"ctl\");Class cmdClass = Class.forName(ctl + \"Command\");Worker ao = (Worker) cmdClass.newInstance();ao.doAction(request);",
"output": "This program snippet has a vulnerability.A common reason that programmers use the reflection API is to implement their own command dispatcher. The following example shows a command dispatcher that does not use reflection:A programmer might refactor this code to use reflection as follows:The refactoring initially appears to offer a number of advantages. There are fewer lines of code, the if/else blocks have been entirely eliminated, and it is now possible to add new command types without modifying the command dispatcher. However, the refactoring allows an attacker to instantiate any object that implements the Worker interface. If the command dispatcher is still responsible for access control, then whenever programmers create a new class that implements the Worker interface, they must remember to modify the dispatcher's access control code. If they do not modify the access control code, then some Worker classes will not have any access control.One way to address this access control problem is to make the Worker object responsible for performing the access control check. An example of the re-refactored code follows:Although this is an improvement, it encourages a decentralized approach to access control, which makes it easier for programmers to make access control mistakes. This code also highlights another security problem with using reflection to build a command dispatcher. An attacker can invoke the default constructor for any kind of object. In fact, the attacker is not even constrained to objects that implement the Worker interface; the default constructor for any object in the system can be invoked. If the object does not implement the Worker interface, a ClassCastException will be thrown before the assignment to ao, but if the constructor performs operations that work in the attacker's favor, the damage will already have been done. Although this scenario is relatively benign in simple products, in larger products where complexity grows exponentially it is not unreasonable that an attacker could find a constructor to leverage as part of an attack."
}
{
"input": "String ctl = request.getParameter(\"ctl\");Class cmdClass = Class.forName(ctl + \"Command\");Worker ao = (Worker) cmdClass.newInstance();ao.checkAccessControl(request);ao.doAction(request);",
"output": "This program snippet has a vulnerability.A common reason that programmers use the reflection API is to implement their own command dispatcher. The following example shows a command dispatcher that does not use reflection:A programmer might refactor this code to use reflection as follows:The refactoring initially appears to offer a number of advantages. There are fewer lines of code, the if/else blocks have been entirely eliminated, and it is now possible to add new command types without modifying the command dispatcher. However, the refactoring allows an attacker to instantiate any object that implements the Worker interface. If the command dispatcher is still responsible for access control, then whenever programmers create a new class that implements the Worker interface, they must remember to modify the dispatcher's access control code. If they do not modify the access control code, then some Worker classes will not have any access control.One way to address this access control problem is to make the Worker object responsible for performing the access control check. An example of the re-refactored code follows:Although this is an improvement, it encourages a decentralized approach to access control, which makes it easier for programmers to make access control mistakes. This code also highlights another security problem with using reflection to build a command dispatcher. An attacker can invoke the default constructor for any kind of object. In fact, the attacker is not even constrained to objects that implement the Worker interface; the default constructor for any object in the system can be invoked. If the object does not implement the Worker interface, a ClassCastException will be thrown before the assignment to ao, but if the constructor performs operations that work in the attacker's favor, the damage will already have been done. Although this scenario is relatively benign in simple products, in larger products where complexity grows exponentially it is not unreasonable that an attacker could find a constructor to leverage as part of an attack."
}
{
"input": "void host_lookup(char *user_supplied_addr){\nstruct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);\n\n/*routine that ensures user_supplied_addr is in the right format for conversion */\n\nvalidate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);\n}",
"output": "This program snippet has a vulnerability.This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119)."
}
{
"input": "String cmd = System.getProperty(\"cmd\");cmd = cmd.trim();",
"output": "This program snippet has a vulnerability.In the following code, the programmer assumes that the system always has a property named \"cmd\" defined. If an attacker can control the program's environment so that \"cmd\" is not defined, the program throws a NULL pointer exception when it attempts to call the trim() method."
}
{
"input": "...\nIntentFilter filter = new IntentFilter(\"com.example.URLHandler.openURL\");MyReceiver receiver = new MyReceiver();registerReceiver(receiver, filter);\n...\n\npublic class UrlHandlerReceiver extends BroadcastReceiver {\n@Overridepublic void onReceive(Context context, Intent intent) {\nif(\"com.example.URLHandler.openURL\".equals(intent.getAction())) {String URL = intent.getStringExtra(\"URLToOpen\");int length = URL.length();\n\n...\n}\n}\n}",
"output": "This program snippet has a vulnerability.This Android application has registered to handle a URL when sent an intent:The application assumes the URL will always be included in the intent. When the URL is not present, the call to getStringExtra() will return null, thus causing a null pointer exception when length() is called."
}
{
"input": "URL[] classURLs= new URL[]{new URL(\"file:subdir/\")};URLClassLoader loader = new URLClassLoader(classURLs);Class loadedClass = Class.forName(\"loadMe\", true, loader);",
"output": "This program snippet has a vulnerability.This example loads an external class from a local subdirectory.This code does not ensure that the class loaded is the intended one, for example by verifying the class's checksum. An attacker may be able to modify the class file to execute malicious code."
}
{
"input": "try {File file = new File(\"object.obj\");ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));javax.swing.JButton button = (javax.swing.JButton) in.readObject();in.close();}",
"output": "This program snippet has a vulnerability.This code snippet deserializes an object from a file and uses it as a UI button:This code does not attempt to verify the source or contents of the file before deserializing it. An attacker may be able to replace the intended file with a file that contains arbitrary malicious code which will be executed when the button is pressed.To mitigate this, explicitly define final readObject() to prevent deserialization. An example of this is:"
}
{
"input": "try {\nclass ExampleProtocol(protocol.Protocol):def dataReceived(self, data):\n# Code that would be here would parse the incoming data# After receiving headers, call confirmAuth() to authenticate\ndef confirmAuth(self, headers):try:token = cPickle.loads(base64.b64decode(headers['AuthToken']))if not check_hmac(token['signature'], token['data'], getSecretKey()):raise AuthFailself.secure_data = token['data']except:raise AuthFail\n}",
"output": "This program snippet has a vulnerability.In Python, the Pickle library handles the serialization and deserialization processes. In this example derived from [REF-467], the code receives and parses data, and afterwards tries to authenticate a user based on validating a token. Unfortunately, the code does not verify that the incoming data is legitimate. An attacker can construct a illegitimate, serialized object \"AuthToken\" that instantiates one of Python's subprocesses to execute arbitrary commands. For instance,the attacker could construct a pickle that leverages Python's subprocess module, which spawns new processes and includes a number of arguments for various uses. Since Pickle allows objects to define the process for how they should be unpickled, the attacker can direct the unpickle process to call Popen in the subprocess module and execute /bin/sh."
}
{
"input": "...Properties prop = new Properties();prop.load(new FileInputStream(\"config.properties\"));String password = prop.getProperty(\"password\");DriverManager.getConnection(url, usr, password);...",
"output": "This program snippet has a vulnerability.The following code reads a password from a properties file and uses the password to connect to a database.This code will run successfully, but anyone who has access to config.properties can read the value of password. If a devious employee has access to this information, they can use it to break into the system."
}
{
"input": "...String password = regKey.GetValue(passKey).toString();NetworkCredential netCred = new NetworkCredential(username,password,domain);...",
"output": "This program snippet has a vulnerability.The following code reads a password from the registry and uses the password to create a new network credential.This code will run successfully, but anyone who has access to the registry key used to store the password can read the value of password. If a devious employee has access to this information, they can use it to break into the system"
}
{
"input": "int VerifyAdmin(char *password) {if (strcmp(compress(password), compressed_password)) {printf(\"Incorrect Password!\\n\");return(0);}printf(\"Entering Diagnostic Mode...\\n\");return(1);}",
"output": "This program snippet has a vulnerability.Both of these examples verify a password by comparing it to a stored compressed version.Because a compression algorithm is used instead of a one way hashing algorithm, an attacker can recover compressed passwords stored in the database."
}
{
"input": "int VerifyAdmin(String password) {if (passwd.Equals(compress(password), compressed_password)) {return(0);}\n//Diagnostic Mode\nreturn(1);}",
"output": "This program snippet has a vulnerability.Both of these examples verify a password by comparing it to a stored compressed version.Because a compression algorithm is used instead of a one way hashing algorithm, an attacker can recover compressed passwords stored in the database."
}
{
"input": "# Java Web App ResourceBundle properties file\n...webapp.ldap.username=secretUsernamewebapp.ldap.password=secretPassword...",
"output": "This program snippet has a vulnerability.The following examples show a portion of properties and configuration files for Java and ASP.NET applications. The files include username and password information but they are stored in cleartext.This Java example shows a properties file with a cleartext username / password pair.The following example shows a portion of a configuration file for an ASP.Net application. This configuration file includes username and password information for a connection to a database but the pair is stored in cleartext.Username and password information should not be included in a configuration file or a properties file in cleartext as this will allow anyone who can read the file access to the resource. If possible, encrypt this information."
}
{
"input": "logger.info(\"Username: \" + usernme + \", CCN: \" + ccn);",
"output": "This program snippet has a vulnerability.In the following code snippet, a user's full name and credit card number are written to a log file."
}
{
"input": "locationClient = new LocationClient(this, this, this);locationClient.connect();currentUser.setLocation(locationClient.getLastLocation());\n...\n\ncatch (Exception e) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage(\"Sorry, this application has experienced an error.\");AlertDialog alert = builder.create();alert.show();Log.e(\"ExampleActivity\", \"Caught exception: \" + e + \" While on User:\" + User.toString());}",
"output": "This program snippet has a vulnerability.This code stores location information about the current user:When the application encounters an exception it will write the user object to the log. Because the user object contains location information, the user's location is also written to the log."
}
{
"input": "public BankAccount getUserBankAccount(String username, String accountNumber) {\nBankAccount userAccount = null;String query = null;try {if (isAuthorizedUser(username)) {query = \"SELECT * FROM accounts WHERE owner = \"+ username + \" AND accountID = \" + accountNumber;DatabaseManager dbManager = new DatabaseManager();Connection conn = dbManager.getConnection();Statement stmt = conn.createStatement();ResultSet queryResult = stmt.executeQuery(query);userAccount = (BankAccount)queryResult.getObject(accountNumber);}} catch (SQLException ex) {String logMessage = \"Unable to retrieve account information from database,\\nquery: \" + query;Logger.getLogger(BankManager.class.getName()).log(Level.SEVERE, logMessage, ex);}return userAccount;\n}",
"output": "This program snippet has a vulnerability.In the example below, the method getUserBankAccount retrieves a bank account object from a database using the supplied username and account number to query the database. If an SQLException is raised when querying the database, an error message is created and output to a log file.The error message that is created includes information about the database query that may contain sensitive information about the database or query logic. In this case, the error message will expose the table name and column names used in the database. This data could be used to simplify other attacks, such as SQL injection (CWE-89) to directly access the database."
}
{
"input": "Cookie[] cookies = request.getCookies();for (int i =0; i< cookies.length; i++) {Cookie c = cookies[i];if (c.getName().equals(\"role\")) {userRole = c.getValue();}}",
"output": "This program snippet has a vulnerability.The following code excerpt reads a value from a browser cookie to determine the role of the user.It is easy for an attacker to modify the \"role\" value found in the locally stored cookie, allowing privilege escalation."
}
{
"input": "public class RedirectServlet extends HttpServlet {\n\nprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String query = request.getQueryString();if (query.contains(\"url\")) {String url = request.getParameter(\"url\");response.sendRedirect(url);}}\n}",
"output": "This program snippet has a vulnerability.The following code is a Java servlet that will receive a GET request with a url parameter in the request to redirect the browser to the address specified in the url parameter. The servlet will retrieve the url parameter value from the request and send a response to redirect the browser to the url address.The problem with this Java servlet code is that an attacker could use the RedirectServlet as part of a e-mail phishing scam to redirect users to a malicious site. An attacker could send an HTML formatted e-mail directing the user to log into their account by including in the e-mail the following link:The user may assume that the link is safe since the URL starts with their trusted bank, bank.example.com. However, the user will then be redirected to the attacker's web site (attacker.example.net) which the attacker may have made to appear very similar to bank.example.com. The user may then unwittingly enter credentials into the attacker's web page and compromise their bank account. A Java servlet should never redirect a user to a URL without verifying that the redirect address is a trusted site."
}
{
"input": "<web-app>\n[...snipped...]\n<session-config><session-timeout>-1</session-timeout></session-config>\n</web-app>",
"output": "This program snippet has a vulnerability.The following snippet was taken from a J2EE web.xml deployment descriptor in which the session-timeout parameter is explicitly defined (the default value depends on the container). In this case the value is set to -1, which means that a session will never expire."
}
{
"input": "String email = request.getParameter(\"email_address\");assert email != null;",
"output": "This program snippet has a vulnerability.In the excerpt below, an AssertionError (an unchecked exception) is thrown if the user hasn't entered an email address in an HTML form."
}
{
"input": "private boolean initialized = true;public void someMethod() {\nif (!initialized) {\n\n\n// perform initialization tasks\n...\ninitialized = true;\n}",
"output": "This program snippet has a vulnerability.Here, a boolean initiailized field is consulted to ensure that initialization tasks are only completed once. However, the field is mistakenly set to true during static initialization, so the initialization code is never reached."
}
{
"input": "char str[20];strcat(str, \"hello world\");printf(\"%s\", str);",
"output": "This program snippet has a vulnerability.The following code intends to concatenate a string to a variable and print the string.This might seem innocent enough, but str was not initialized, so it contains random memory. As a result, str[0] might not contain the null terminator, so the copy might start at an offset other than 0. The consequences can vary, depending on the underlying memory.If a null terminator is found before str[8], then some bytes of random garbage will be printed before the \"hello world\" string. The memory might contain sensitive information from previous uses, such as a password (which might occur as a result of CWE-14 or CWE-244). In this example, it might not be a big deal, but consider what could happen if large amounts of memory are printed out before the null terminator is found. If a null terminator isn't found before str[8], then a buffer overflow could occur, since strcat will first look for the null terminator, then copy 12 bytes starting with that location. Alternately, a buffer over-read might occur (CWE-126) if a null terminator isn't found before the end of the memory segment is reached, leading to a segmentation fault and crash."
}
{
"input": "private long someLongValue;public long getLongValue() {return someLongValue;}\npublic void setLongValue(long l) {someLongValue = l;}",
"output": "This program snippet has a vulnerability.In the following Java snippet, methods are defined to get and set a long field in an instance of a class that is shared across multiple threads. Because operations on double and long are nonatomic in Java, concurrent access may cause unexpected behavior. Thus, all operations on long and double fields should be synchronized."
}
{
"input": "void f(pthread_mutex_t *mutex) {\npthread_mutex_lock(mutex);\n\n/* access shared resource */\n\n\npthread_mutex_unlock(mutex);\n}",
"output": "This program snippet has a vulnerability.The following function attempts to acquire a lock in order to perform operations on a shared resource.However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels."
}
{
"input": "if (helper == null) {\nsynchronized (this) {if (helper == null) {helper = new Helper();}}\n}return helper;",
"output": "This program snippet has a vulnerability.It may seem that the following bit of code achieves thread safety while avoiding unnecessary synchronization...The programmer wants to guarantee that only one Helper() object is ever allocated, but does not want to pay the cost of synchronization every time this code is called.Suppose that helper is not initialized. Then, thread A sees that helper==null and enters the synchronized block and begins to execute:If a second thread, thread B, takes over in the middle of this call and helper has not finished running the constructor, then thread B may make calls on helper while its fields hold incorrect values."
}
{
"input": "char* ptr = (char*)malloc (SIZE);if (err) {abrt = 1;free(ptr);}...if (abrt) {logError(\"operation aborted before commit\", ptr);}",
"output": "This program snippet has a vulnerability.The following code shows a simple example of a use after free error:When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function."
}
{
"input": "char* ptr = (char*)malloc (SIZE);...if (abrt) {free(ptr);}...free(ptr);",
"output": "This program snippet has a vulnerability.The following code shows a simple example of a double free error:Double free vulnerabilities have two common (and sometimes overlapping) causes:\n\n\nError conditions and other exceptional circumstances\n\n\nConfusion over which part of the program is responsible for freeing the memory\n\n\nAlthough some double free vulnerabilities are not much more complicated than the previous example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once."
}
{
"input": "#define FAIL 0#define SUCCESS 1#define ERROR -1#define MAX_MESSAGE_SIZE 32\nint processMessage(char **message){\nint result = SUCCESS;\nint length = getMessageLength(message[0]);char *messageBody;\nif ((length > 0) && (length < MAX_MESSAGE_SIZE)) {\n\nmessageBody = (char*)malloc(length*sizeof(char));messageBody = &message[1][0];\nint success = processMessageBody(messageBody);\nif (success == ERROR) {result = ERROR;free(messageBody);}\n}else {printf(\"Unable to process message; invalid message length\");result = FAIL;}\nif (result == ERROR) {logError(\"Error processing message\", messageBody);}\nreturn result;\n}",
"output": "This program snippet has a vulnerability.In the following C/C++ example the method processMessage is used to process a message received in the input array of char arrays. The input message array contains two char arrays: the first is the length of the message and the second is the body of the message. The length of the message is retrieved and used to allocate enough memory for a local char array, messageBody, to be created for the message body. The messageBody is processed in the method processMessageBody that will return an error if an error occurs while processing. If an error occurs then the return result variable is set to indicate an error and the messageBody char array memory is released using the method free and an error message is sent to the logError method.However, the call to the method logError includes the messageBody after the memory for messageBody has been released using the free method. This can cause unexpected results and may lead to system crashes. A variable should never be used after its memory resources have been released."
}
{
"input": "void do_something_recursive (int flg)\n\t {\n\n\t ... // Do some real work here, but the value of flg is unmodified\n\t if (flg) { do_something_recursive (flg); } // flg is never modified so it is always TRUE - this call will continue until the stack explodes\n\n\t }\n\t int flag = 1; // Set to TRUE\n\t do_something_recursive (flag);",
"output": "This program snippet has a vulnerability.In this example a mistake exists in the code where the exit condition contained in flg is never called. This results in the function calling itself over and over again until the stack is exhausted.\n Note that the only difference between the Good and Bad examples is that the recursion flag will change value and cause the recursive call to return."
}
{
"input": "int i = (int) 33457.8f;",
"output": "This program snippet has a vulnerability.In the following Java example, a float literal is cast to an integer, thus causing a loss of precision."
}
{
"input": "unsigned int readdata () {int amount = 0;...if (result == ERROR)amount = -1;...return amount;}",
"output": "This program snippet has a vulnerability.In this example the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned int, amount will be implicitly converted to unsigned.If the error condition in the code above is met, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers."
}
{
"input": "unsigned int readdata () {int amount = 0;...amount = accessmainframe();...return amount;}",
"output": "This program snippet has a vulnerability.In this example, depending on the return value of accecssmainframe(), the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned value, amount will be implicitly cast to an unsigned number.If the return value of accessmainframe() is -1, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers."
}
{
"input": "img_t table_ptr; /*struct containing img data, 10kB each*/int num_imgs;...num_imgs = get_num_imgs();table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs);...",
"output": "This program snippet has a vulnerability.The following image processing code allocates a table for images.This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119)."
}
{
"input": "...int touchdowns = team.getTouchdowns();int yardsGained = team.getTotalYardage();System.out.println(team.getName() + \" averages \" + yardsGained / touchdowns + \"yards gained for every touchdown scored\");...",
"output": "This program snippet has a vulnerability.This code attempts to calculate a football team's average number of yards gained per touchdown.The code does not consider the event that the team they are querying has not scored a touchdown, but has gained yardage. In that case, we should expect an ArithmeticException to be thrown by the JVM. This could lead to a loss of availability if our error handling code is not set up correctly."
}
{
"input": "int *p = x;char * second_char = (char *)(p + 1);",
"output": "This program snippet has a vulnerability.This example attempts to calculate the position of the second byte of a pointer.In this example, second_char is intended to point to the second byte of p. But, adding 1 to p actually adds sizeof(int) to p, giving a result that is incorrect (3 bytes off on 32-bit platforms). If the resulting memory address is read, this could potentially be an information leak. If it is a write, it could be a security-critical write to unauthorized memory-- whether or not it is a buffer overflow. Note that the above code may also be wrong in other ways, particularly in a little endian environment."
}
{
"input": "public class Truck {\nprivate String make;private String model;private int year;\npublic boolean equals(Object o) {\nif (o == null) return false;if (o == this) return true;if (!(o instanceof Truck)) return false;\nTruck t = (Truck) o;\nreturn (this.make.equals(t.getMake()) && this.model.equals(t.getModel()));\n}\n}",
"output": "This program snippet has a vulnerability.Consider an application in which Truck objects are defined to be the same if they have the same make, the same model, and were manufactured in the same year.Here, the equals() method only checks the make and model of the Truck objects, but the year of manufacture is not included."
}
{
"input": "/* Ignore CWE-259 (hard-coded password) and CWE-309 (use of password system for authentication) for this example. */ \n\nchar *username = \"admin\";char *pass = \"password\";\nint AuthenticateUser(char *inUser, char *inPass) {if (strncmp(username, inUser, strlen(inUser))) {logEvent(\"Auth failure of username using strlen of inUser\");return(AUTH_FAIL);}if (! strncmp(pass, inPass, strlen(inPass))) {logEvent(\"Auth success of password using strlen of inUser\");return(AUTH_SUCCESS);}else {logEvent(\"Auth fail of password using sizeof\");return(AUTH_FAIL);}}\nint main (int argc, char **argv) {\n int authResult;if (argc < 3) {ExitError(\"Usage: Provide a username and password\");}authResult = AuthenticateUser(argv[1], argv[2]);if (authResult == AUTH_SUCCESS) {DoAuthenticatedTask(argv[1]);}else {ExitError(\"Authentication failed\");}}",
"output": "This program snippet has a vulnerability.This example defines a fixed username and password. The AuthenticateUser() function is intended to accept a username and a password from an untrusted user, and check to ensure that it matches the username and password. If the username and password match, AuthenticateUser() is intended to indicate that authentication succeeded.In AuthenticateUser(), the strncmp() call uses the string length of an attacker-provided inPass parameter in order to determine how many characters to check in the password. So, if the attacker only provides a password of length 1, the check will only examine the first byte of the application's password before determining success.As a result, this partial comparison leads to improper authentication (CWE-287). Any of these passwords would still cause authentication to succeed for the \"admin\" user:This significantly reduces the search space for an attacker, making brute force attacks more feasible.The same problem also applies to the username, so values such as \"a\" and \"adm\" will succeed for the username.While this demonstrative example may not seem realistic, see the Observed Examples for CVE entries that effectively reflect this same weakness."
}
{
"input": "#define OUTFILE \"hello.out\"\numask(0);FILE *out;\n/* Ignore link following (CWE-59) for brevity */ \n\nout = fopen(OUTFILE, \"w\");if (out) {fprintf(out, \"hello world!\\n\");fclose(out);}",
"output": "This program snippet has a vulnerability.The following code sets the umask of the process to 0 before creating a file and writing \"Hello world\" into the file.After running this program on a UNIX system, running the \"ls -l\" command might return the following output:The \"rw-rw-rw-\" string indicates that the owner, group, and world (all users) can read the file and write to it."
}
{
"input": "char buf[10], cp_buf[10];fgets(buf, 10, stdin);strcpy(cp_buf, buf);",
"output": "This program snippet has a vulnerability.Consider the following code segment:The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy()."
}
{
"input": "buf = (char*) malloc(req_size);strncpy(buf, xfer, req_size);",
"output": "This program snippet has a vulnerability.The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc().The traditional defense of this coding error is: \"If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or simply allow the program to die with a segmentation fault when it tries to dereference the null pointer.\" This argument ignores three important considerations:\n\n\nDepending upon the type and size of the application, it may be possible to free memory that is being used elsewhere so that execution can continue.\n\n\nIt is impossible for the program to perform a graceful exit if required. If the program is performing an atomic operation, it can leave the system in an inconsistent state.\n\n\nThe programmer has lost the opportunity to record diagnostic information. Did the call to malloc() fail because req_size was too large or because there were too many requests being handled at the same time? Or was it caused by a memory leak that has built up over time? Without handling the error, there is no way to know."
}
{
"input": "FileInputStream fis;byte[] byteArray = new byte[1024];for (Iterator i=users.iterator(); i.hasNext();) {\nString userName = (String) i.next();String pFileName = PFILE_ROOT + \"/\" + userName;FileInputStream fis = new FileInputStream(pFileName);fis.read(byteArray); // the file is always 1k bytesfis.close();processPFile(userName, byteArray);",
"output": "This program snippet has a vulnerability.The following examples read a file into a byte array.The code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always 1 kilobyte in size and therefore ignores the return value from Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and treat it as though it belongs to the attacker."
}
{
"input": "String itemName = request.getParameter(ITEM_NAME);if (itemName.compareTo(IMPORTANT_ITEM) == 0) {...}...",
"output": "This program snippet has a vulnerability.The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference.The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "String itemName = request.Item(ITEM_NAME);if (itemName.Equals(IMPORTANT_ITEM)) {...}...",
"output": "This program snippet has a vulnerability.The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference.The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "System.clearProperty(\"os.name\");...String os = System.getProperty(\"os.name\");if (os.equalsIgnoreCase(\"Windows 95\")) System.out.println(\"Not supported\");",
"output": "This program snippet has a vulnerability.The following code shows a system property that is set to null and later dereferenced by a programmer who mistakenly assumes it will always be defined.The traditional defense of this coding error is: \"I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value.\" But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved."
}
{
"input": "void host_lookup(char *user_supplied_addr){\nstruct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);\n\n/*routine that ensures user_supplied_addr is in the right format for conversion */\n\nvalidate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);\n}",
"output": "This program snippet has a vulnerability.This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119)."
}
{
"input": "int outputStringToFile(char *output, char *filename) {\n\nopenFileToWrite(filename);writeToFile(output);closeFile(filename);\n}",
"output": "This program snippet has a vulnerability.In the following C/C++ example the method outputStringToFile opens a file in the local filesystem and outputs a string to the file. The input parameters output and filename contain the string to output to the file and the name of the file respectively.However, this code does not check the return values of the methods openFileToWrite, writeToFile, closeFile to verify that the file was properly opened and closed and that the string was successfully written to the file. The return values for these methods should be checked to determine if the method was successful and allow for detection of errors or unexpected conditions as in the following example."
}
{
"input": "private File readFile = null;\npublic void setInputFile(String inputFile) {\n\n\n// create readFile File object from string containing name of file\n\n\n}\npublic void readFromFile() {\ntry {\nreader = new FileReader(readFile);\n\n// read input file\n\n\n} catch (FileNotFoundException ex) {...}\n}",
"output": "This program snippet has a vulnerability.In the following Java example the method readFromFile uses a FileReader object to read the contents of a file. The FileReader object is created using the File object readFile, the readFile object is initialized using the setInputFile method. The setInputFile method should be called before calling the readFromFile method.However, the readFromFile method does not check to see if the readFile object is null, i.e. has not been initialized, before creating the FileReader object and reading from the input file. The readFromFile method should verify whether the readFile object is null and output an error message and raise an exception if the readFile object is null, as in the following code."
}
{
"input": "char **ap, *argv[10], *inputstring;for (ap = argv; (*ap = strsep(&inputstring, \" \\t\")) != NULL;)\nif (**ap != '\\0')if (++ap >= &argv[10])break;\n\n\n\n/.../free(ap[4]);",
"output": "This program snippet has a vulnerability.This code attempts to tokenize a string and place it into an array using the strsep function, which inserts a \\0 byte in place of whitespace or a tab character. After finishing the loop, each string in the AP array points to a location within the input string.Since strsep is not allocating any new memory, freeing an element in the middle of the array is equivalent to free a pointer in the middle of inputstring."
}
{
"input": "void foo(){\nBarObj *ptr = new BarObj()\n/* do some work with ptr here */\n\n...\nfree(ptr);\n}",
"output": "This program snippet has a vulnerability.This example allocates a BarObj object using the new operator in C++, however, the programmer then deallocates the object using free(), which may lead to unexpected behavior.Instead, the programmer should have either created the object with one of the malloc family functions, or else deleted the object with the delete operator."
}
{
"input": "#define SUCCESS (1)#define FAILURE (0)\nint contains_char(char c){\nchar *str;str = (char*)malloc(20*sizeof(char));strcpy(str, \"Search Me!\");while( *str != NULL){\nif( *str == c ){\n\n\n/* matched char, free string and return success */\nfree(str);return SUCCESS;\n}\n/* didn't match yet, increment pointer and try next char */\n\nstr = str + 1;\n}\n/* we did not match the char in the string, free mem and return failure */\n\nfree(str);return FAILURE;\n}",
"output": "This program snippet has a vulnerability.In this example, the programmer dynamically allocates a buffer to hold a string and then searches for a specific character. After completing the search, the programmer attempts to release the allocated memory and return SUCCESS or FAILURE to the caller. Note: for simplification, this example uses a hard-coded \"Search Me!\" string and a constant string length of 20.However, if the character is not at the beginning of the string, or if it is not in the string at all, then the pointer will not be at the start of the buffer when the programmer frees it.Instead of freeing the pointer in the middle of the buffer, the programmer can use an indexing pointer to step through the memory or abstract the memory calculations by using array indexing."
}
{
"input": "//hardcode input length for simplicity\nchar* input = (char*) malloc(40*sizeof(char));char *tok;char* sep = \" \\t\";\nget_user_input( input );\n\n/* The following loop will parse and process each token in the input string */\n\ntok = strtok( input, sep);while( NULL != tok ){\nif( isMalformed( tok ) ){\n\n\n/* ignore and discard bad data */\nfree( tok );\n}else{add_to_command_queue( tok );}tok = strtok( NULL, sep));\n}",
"output": "This program snippet has a vulnerability.Consider the following code in the context of a parsing application to extract commands out of user data. The intent is to parse each command and add it to a queue of commands to be executed, discarding each malformed entry.While the above code attempts to free memory associated with bad commands, since the memory was all allocated in one chunk, it must all be freed together.One way to fix this problem would be to copy the commands into a new memory location before placing them in the queue. Then, after all commands have been processed, the memory can safely be freed."
}
{
"input": "int main(int argc, char** argv) {char cmd[CMD_MAX] = \"/usr/bin/cat \";strcat(cmd, argv[1]);system(cmd);}",
"output": "This program snippet has a vulnerability.The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form \";rm -rf /\", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.Note that if argv[1] is a very long argument, then this issue might also be subject to a buffer overflow (CWE-120)."
}
{
"input": "...String btype = request.getParameter(\"backuptype\");String cmd = new String(\"cmd.exe /K \\\"c:\\\\util\\\\rmanDB.bat \"+btype+\"&&c:\\\\utl\\\\cleanup.bat\\\"\")\nSystem.Runtime.getRuntime().exec(cmd);...",
"output": "This program snippet has a vulnerability.The following code is from an administrative web application designed to allow users to kick off a backup of an Oracle database using a batch-file wrapper around the rman utility and then run a cleanup.bat script to delete some temporary files. The script rmanDB.bat accepts a single command line parameter, which specifies what type of backup to perform. Because access to the database is restricted, the application runs the backup as a privileged user.The problem here is that the program does not do any validation on the backuptype parameter read from the user. Typically the Runtime.exec() function will not execute multiple commands, but in this case the program first runs the cmd.exe shell in order to run multiple commands with a single call to Runtime.exec(). Once the shell is invoked, it will happily execute multiple commands separated by two ampersands. If an attacker passes a string of the form \"& del c:\\\\dbms\\\\*.*\", then the application will execute this command along with the others specified by the program. Because of the nature of the application, it runs with the privileges necessary to interact with the database, which means whatever command the attacker injects will run with those privileges as well."
}
{
"input": "...String home = System.getProperty(\"APPHOME\");String cmd = home + INITCMD;java.lang.Runtime.getRuntime().exec(cmd);...",
"output": "This program snippet has a vulnerability.The following code from a system utility uses the system property APPHOME to determine the directory in which it is installed and then executes an initialization script based on a relative path from the specified directory.The code above allows an attacker to execute arbitrary commands with the elevated privilege of the application by modifying the system property APPHOME to point to a different path containing a malicious version of INITCMD. Because the program does not validate the value read from the environment, if an attacker can control the value of the system property APPHOME, then they can fool the application into running malicious code and take control of the system."
}
{
"input": "#include <stdio.h>#include <unistd.h>\nint main(int argc, char **argv) {\n\nchar cat[] = \"cat \";char *command;size_t commandLength;\ncommandLength = strlen(cat) + strlen(argv[1]) + 1;command = (char *) malloc(commandLength);strncpy(command, cat, commandLength);strncat(command, argv[1], (commandLength - strlen(cat)) );\nsystem(command);return (0);\n}",
"output": "This program snippet has a vulnerability.The following code is a wrapper around the UNIX command cat which prints the contents of a file to standard out. It is also injectable:Used normally, the output is simply the contents of the file requested:However, if we add a semicolon and another command to the end of this line, the command is executed by catWrapper with no complaint:If catWrapper had been set to have a higher privilege level than the standard user, arbitrary commands could be executed with that higher privilege."
}
{
"input": "sock=socket(AF_INET, SOCK_STREAM, 0);while (1) {newsock=accept(sock, ...);printf(\"A connection has been accepted\\n\");pid = fork();}",
"output": "This program snippet has a vulnerability.This code allocates a socket and forks each time it receives a new connection.The program does not track how many connections have been made, and it does not limit the number of connections. Because forking is a relatively expensive operation, an attacker would be able to cause the system to run out of CPU, processes, or memory by making a large number of connections. Alternatively, an attacker could consume all available connections, preventing others from accessing the system remotely."
}
{
"input": "int writeDataFromSocketToFile(char *host, int port){\n\nchar filename[FILENAME_SIZE];char buffer[BUFFER_SIZE];int socket = openSocketConnection(host, port);\nif (socket < 0) {printf(\"Unable to open socket connection\");return(FAIL);}if (getNextMessage(socket, filename, FILENAME_SIZE) > 0) {\nif (openFileToWrite(filename) > 0) {\nwhile (getNextMessage(socket, buffer, BUFFER_SIZE) > 0){if (!(writeToFile(buffer) > 0))break;\n}\n}closeFile();\n}closeSocket(socket);\n}",
"output": "This program snippet has a vulnerability.In the following example a server socket connection is used to accept a request to store data on the local file system using a specified filename. The method openSocketConnection establishes a server socket to accept requests from a client. When a client establishes a connection to this service the getNextMessage method is first used to retrieve from the socket the name of the file to store the data, the openFileToWrite method will validate the filename and open a file to write to on the local file system. The getNextMessage is then used within a while loop to continuously read data from the socket and output the data to the file until there is no longer any data from the socket.This example creates a situation where data can be dumped to a file on the local file system without any limits on the size of the file. This could potentially exhaust file or disk resources and/or limit other clients' ability to access the service."
}
{
"input": "/* process message accepts a two-dimensional character array of the form [length][body] containing the message to be processed */\nint processMessage(char **message){\nchar *body;\nint length = getMessageLength(message[0]);\nif (length > 0) {body = &message[1][0];processMessageBody(body);return(SUCCESS);}else {printf(\"Unable to process message; invalid message length\");return(FAIL);}\n}",
"output": "This program snippet has a vulnerability.In the following example, the processMessage method receives a two dimensional character array containing the message to be processed. The two-dimensional character array contains the length of the message in the first character array and the message body in the second character array. The getMessageLength method retrieves the integer value of the length from the first character array. After validating that the message length is greater than zero, the body character array pointer points to the start of the second character array of the two-dimensional character array and memory is allocated for the new body character array.This example creates a situation where the length of the body character array can be very large and will consume excessive memory, exhausting system resources. This can be avoided by restricting the length of the second character array with a maximum length checkAlso, consider changing the type from 'int' to 'unsigned int', so that you are always guaranteed that the number is positive. This might not be possible if the protocol specifically requires allowing negative values, or if you cannot control the return value from getMessageLength(), but it could simplify the check to ensure the input is positive, and eliminate other errors such as signed-to-unsigned conversion errors (CWE-195) that may occur elsewhere in the code."
}
{
"input": "public void acceptConnections() {\n\ntry {ServerSocket serverSocket = new ServerSocket(SERVER_PORT);int counter = 0;boolean hasConnections = true;while (hasConnections) {Socket client = serverSocket.accept();Thread t = new Thread(new ClientSocketThread(client));t.setName(client.getInetAddress().getHostName() + \":\" + counter++);t.start();}serverSocket.close();\n\n} catch (IOException ex) {...}\n}",
"output": "This program snippet has a vulnerability.In the following example, a server object creates a server socket and accepts client connections to the socket. For every client connection to the socket a separate thread object is generated using the ClientSocketThread class that handles request made by the client through the socket.In this example there is no limit to the number of client connections and client threads that are created. Allowing an unlimited number of client connections and threads could potentially overwhelm the system and system resources.The server should limit the number of client connections and the client threads that are created. This can be easily done by creating a thread pool object that limits the number of threads that are generated."
}
{
"input": "bar connection() {foo = malloc(1024);return foo;}endConnection(bar foo) {free(foo);}int main() {while(1) {foo=connection();}endConnection(foo)}",
"output": "This program snippet has a vulnerability.Here the problem is that every time a connection is made, more memory is allocated. So if one just opened up more and more connections, eventually the machine would run out of memory."
}
{
"input": "private void processFile(string fName){BufferReader fil = new BufferReader(new FileReader(fName));String line;while ((line = fil.ReadLine()) != null){processLine(line);}}",
"output": "This program snippet has a vulnerability.The following method never closes the new file handle. Given enough time, the Finalize() method for BufferReader should eventually call Close(), but there is no guarantee as to how long this action will take. In fact, there is no guarantee that Finalize() will ever be invoked. In a busy environment, the Operating System could use up all of the available file handles before the Close() function is called.The good code example simply adds an explicit call to the Close() function when the system is done using the file. Within a simple example such as this the problem is easy to see and fix. In a real system, the problem may be considerably more obscure."
}
{
"input": "try {Connection con = DriverManager.getConnection(some_connection_string);}catch ( Exception e ) {log( e );}",
"output": "This program snippet has a vulnerability.This code attempts to open a connection to a database and catches any exceptions that may occur.If an exception occurs after establishing the database connection and before the same connection closes, the pool of database connections may become exhausted. If the number of available connections is exceeded, other users cannot access this resource, effectively denying access to the application."
}
{
"input": "int decodeFile(char* fName) {\nchar buf[BUF_SZ];FILE* f = fopen(fName, \"r\");if (!f) {printf(\"cannot open %s\\n\", fName);return DECODE_FAIL;}else {\nwhile (fgets(buf, BUF_SZ, f)) {if (!checkChecksum(buf)) {return DECODE_FAIL;}else {decodeBlock(buf);}}\n}fclose(f);return DECODE_SUCCESS;\n}",
"output": "This program snippet has a vulnerability.The following C function does not close the file handle it opens if an error occurs. If the process is long-lived, the process can run out of file handles."
}
{
"input": "int main(int argc, char** argv) {char cmd[CMD_MAX] = \"/usr/bin/cat \";strcat(cmd, argv[1]);system(cmd);}",
"output": "This program snippet has a vulnerability.The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form \";rm -rf /\", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.Note that if argv[1] is a very long argument, then this issue might also be subject to a buffer overflow (CWE-120)."
}
{
"input": "String script = System.getProperty(\"SCRIPTNAME\");if (script != null)System.exec(script);",
"output": "This program snippet has a vulnerability.The example below reads the name of a shell script to execute from the system properties. It is subject to the second variant of OS command injection.If an attacker has control over this property, then they could modify the property to point to a dangerous program."
}
{
"input": "public String coordinateTransformLatLonToUTM(String coordinates){\nString utmCoords = null;try {\nString latlonCoords = coordinates;Runtime rt = Runtime.getRuntime();Process exec = rt.exec(\"cmd.exe /C latlon2utm.exe -\" + latlonCoords);\n// process results of coordinate transform\n\n\n// ...\n\n\n}catch(Exception e) {...}return utmCoords;\n}",
"output": "This program snippet has a vulnerability.In the example below, a method is used to transform geographic coordinates from latitude and longitude format to UTM format. The method gets the input coordinates from a user through a HTTP request and executes a program local to the application server that performs the transformation. The method passes the latitude and longitude coordinates as a command-line option to the external program and will perform some processing to retrieve the results of the transformation and return the resulting UTM coordinates.However, the method does not verify that the contents of the coordinates input parameter includes only correctly-formatted latitude and longitude coordinates. If the input coordinates were not validated prior to the call to this method, a malicious user could execute another program local to the application server by appending '&' followed by the command for another program to the end of the coordinate string. The '&' instructs the Windows operating system to execute another program."
}
{
"input": "...String btype = request.getParameter(\"backuptype\");String cmd = new String(\"cmd.exe /K \\\"c:\\\\util\\\\rmanDB.bat \"+btype+\"&&c:\\\\utl\\\\cleanup.bat\\\"\")\nSystem.Runtime.getRuntime().exec(cmd);...",
"output": "This program snippet has a vulnerability.The following code is from an administrative web application designed to allow users to kick off a backup of an Oracle database using a batch-file wrapper around the rman utility and then run a cleanup.bat script to delete some temporary files. The script rmanDB.bat accepts a single command line parameter, which specifies what type of backup to perform. Because access to the database is restricted, the application runs the backup as a privileged user.The problem here is that the program does not do any validation on the backuptype parameter read from the user. Typically the Runtime.exec() function will not execute multiple commands, but in this case the program first runs the cmd.exe shell in order to run multiple commands with a single call to Runtime.exec(). Once the shell is invoked, it will happily execute multiple commands separated by two ampersands. If an attacker passes a string of the form \"& del c:\\\\dbms\\\\*.*\", then the application will execute this command along with the others specified by the program. Because of the nature of the application, it runs with the privileges necessary to interact with the database, which means whatever command the attacker injects will run with those privileges as well."
}
{
"input": "int id_sequence[3];\n/* Populate the id array. */\nid_sequence[0] = 123;id_sequence[1] = 234;id_sequence[2] = 345;id_sequence[3] = 456;",
"output": "This program snippet has a vulnerability.The following code attempts to save four different identification numbers into an array.Since the array is only allocated to hold three elements, the valid indices are 0 to 2; so, the assignment to id_sequence[3] is out of bounds."
}
{
"input": "int returnChunkSize(void *) {\n\n\n/* if chunk info is valid, return the size of usable memory,\n\n\n* else, return -1 to indicate an error\n\n\n*/\n...\n}int main() {...memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));...}",
"output": "This program snippet has a vulnerability.In the following code, it is possible to request that memcpy move a much larger segment of memory than assumed:If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788)."
}
{
"input": "void host_lookup(char *user_supplied_addr){\nstruct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);\n\n/*routine that ensures user_supplied_addr is in the right format for conversion */\n\nvalidate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);\n}",
"output": "This program snippet has a vulnerability.This code takes an IP address from the user and verifies that it is well formed. It then looks up the hostname and copies it into a buffer.This function allocates a buffer of 64 bytes to store the hostname. However, there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker.Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476)."
}
{
"input": "char * copy_input(char *user_supplied_string){\nint i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){die(\"user string too long, die evil hacker!\");}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){\nif( '&' == user_supplied_string[i] ){dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';}else if ('<' == user_supplied_string[i] ){\n\n\n/* encode to < */\n\n\n}else dst_buf[dst_index++] = user_supplied_string[i];\n}return dst_buf;\n}",
"output": "This program snippet has a vulnerability.This code applies an encoding procedure to an input string and stores it into a buffer.The programmer attempts to encode the ampersand character in the user-controlled string. However, the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands."
}
{
"input": "char* trimTrailingWhitespace(char *strMessage, int length) {\nchar *retMessage;char *message = malloc(sizeof(char)*(length+1));\n\n// copy input string to a temporary string\nchar message[length+1];int index;for (index = 0; index < length; index++) {message[index] = strMessage[index];}message[index] = '\\0';\n\n// trim trailing whitespace\nint len = index-1;while (isspace(message[len])) {message[len] = '\\0';len--;}\n\n// return string without trailing whitespace\nretMessage = message;return retMessage;\n}",
"output": "This program snippet has a vulnerability.In the following C/C++ code, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character.However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer."
}
{
"input": "int i;unsigned int numWidgets;Widget **WidgetList;\nnumWidgets = GetUntrustedSizeValue();if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {ExitError(\"Incorrect number of widgets requested!\");}WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));printf(\"WidgetList ptr=%p\\n\", WidgetList);for(i=0; i<numWidgets; i++) {WidgetList[i] = InitializeWidget();}WidgetList[numWidgets] = NULL;showWidgets(WidgetList);",
"output": "This program snippet has a vulnerability.The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption."
}
{
"input": "int main() {...strncpy(destBuf, &srcBuf[find(srcBuf, ch)], 1024);...}",
"output": "This program snippet has a vulnerability.The following code may result in a buffer underwrite, if find() returns a negative value to indicate that ch is not found in srcBuf:If the index to srcBuf is somehow under user control, this is an arbitrary write-what-where condition."
}
{
"input": "...DriverManager.getConnection(url, \"scott\", \"tiger\");...",
"output": "This program snippet has a vulnerability.The following code uses a hard-coded password to connect to a database:This is an example of an external hard-coded password on the client-side of a connection. This code will run successfully, but anyone who has access to it will have access to the password. Once the program has shipped, there is no going back from the database user \"scott\" with a password of \"tiger\" unless the program is patched. A devious employee with access to this information can use it to break into the system. Even worse, if attackers have access to the bytecode for application, they can use the javap -c command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for the example above:"
}
{
"input": "int VerifyAdmin(char *password) {\nif (strcmp(password, \"Mew!\")) {\n\n printf(\"Incorrect Password!\\n\");return(0)\n}printf(\"Entering Diagnostic Mode...\\n\");return(1);\n}",
"output": "This program snippet has a vulnerability.The following code is an example of an internal hard-coded password in the back-end:Every instance of this program can be placed into diagnostic mode with the same password. Even worse is the fact that if this program is distributed as a binary-only distribution, it is very difficult to change that password or disable this \"functionality.\""
}
{
"input": "int VerifyAdmin(String password) {if (!password.equals(\"Mew!\")) {return(0)}//Diagnostic Modereturn(1);}",
"output": "This program snippet has a vulnerability.The following code is an example of an internal hard-coded password in the back-end:Every instance of this program can be placed into diagnostic mode with the same password. Even worse is the fact that if this program is distributed as a binary-only distribution, it is very difficult to change that password or disable this \"functionality.\""
}
{
"input": "int VerifyAdmin(char *password) {\nif (strcmp(password,\"68af404b513073584c4b6f22b6c63e6b\")) {\n\nprintf(\"Incorrect Password!\\n\");return(0);\n}printf(\"Entering Diagnostic Mode...\\n\");return(1);\n}",
"output": "This program snippet has a vulnerability.The following code examples attempt to verify a password using a hard-coded cryptographic key.The cryptographic key is within a hard-coded string value that is compared to the password. It is likely that an attacker will be able to read the key and compromise the system."
}
{
"input": "public boolean VerifyAdmin(String password) {if (password.equals(\"68af404b513073584c4b6f22b6c63e6b\")) {System.out.println(\"Entering Diagnostic Mode...\");return true;}System.out.println(\"Incorrect Password!\");return false;",
"output": "This program snippet has a vulnerability.The following code examples attempt to verify a password using a hard-coded cryptographic key.The cryptographic key is within a hard-coded string value that is compared to the password. It is likely that an attacker will be able to read the key and compromise the system."
}
{
"input": "# Java Web App ResourceBundle properties file\n...webapp.ldap.username=secretUsernamewebapp.ldap.password=secretPassword...",
"output": "This program snippet has a vulnerability.The following examples show a portion of properties and configuration files for Java and ASP.NET applications. The files include username and password information but they are stored in cleartext.This Java example shows a properties file with a cleartext username / password pair.The following example shows a portion of a configuration file for an ASP.Net application. This configuration file includes username and password information for a connection to a database but the pair is stored in cleartext.Username and password information should not be included in a configuration file or a properties file in cleartext as this will allow anyone who can read the file access to the resource. If possible, encrypt this information."
}
{
"input": "int processMessagesFromServer(char *hostaddr, int port) {\n...int servsock;int connected;struct sockaddr_in servaddr;\n\n// create socket to connect to server\nservsock = socket( AF_INET, SOCK_STREAM, 0);memset( &servaddr, 0, sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_port = htons(port);servaddr.sin_addr.s_addr = inet_addr(hostaddr);\ndo {\n\n\n// establish connection to server\nconnected = connect(servsock, (struct sockaddr *)&servaddr, sizeof(servaddr));\n\n// if connected then read and process messages from server\nif (connected > -1) {\n\n\n// read and process messages\n...\n}\n\n\n\n// keep trying to establish connection to the server\n} while (connected < 0);\n\n// close socket and return success or failure\n...\n}",
"output": "This program snippet has a vulnerability.In the following code the method processMessagesFromServer attempts to establish a connection to a server and read and process messages from the server. The method uses a do/while loop to continue trying to establish the connection to the server when an attempt fails.However, this will create an infinite loop if the server does not respond. This infinite loop will consume system resources and can be used to create a denial of service attack. To resolve this a counter should be used to limit the number of attempts to establish a connection to the server, as in the following code."
}
{
"input": "public boolean isReorderNeeded(String bookISBN, int rateSold) {\n\nboolean isReorder = false;\nint minimumCount = 10;int days = 0;\n\n// get inventory count for book\nint inventoryCount = inventory.getIventoryCount(bookISBN);\n\n// find number of days until inventory count reaches minimum\nwhile (inventoryCount > minimumCount) {\n\ninventoryCount = inventoryCount - rateSold;days++;\n\n}\n\n// if number of days within reorder timeframe\n\n\n// set reorder return boolean to true\nif (days > 0 && days < 5) {isReorder = true;}\nreturn isReorder;\n}",
"output": "This program snippet has a vulnerability.For this example the method isReorderNeeded as part of a bookstore application that determines if a particular book needs to be reordered based on the current inventory count and the rate at which the book is being sold.However, the while loop will become an infinite loop if the rateSold input parameter has a value of zero since the inventoryCount will never fall below the minimumCount. In this case the input parameter should be validated to ensure that a value of zero does not cause an infinite loop,as in the following code."
}
{
"input": "#define NAME_TYPE 1#define ID_TYPE 2\nstruct MessageBuffer{int msgType;union {char *name;int nameID;};};\n\nint main (int argc, char **argv) {\nstruct MessageBuffer buf;char *defaultMessage = \"Hello World\";\nbuf.msgType = NAME_TYPE;buf.name = defaultMessage;printf(\"Pointer of buf.name is %p\\n\", buf.name);\n/* This particular value for nameID is used to make the code architecture-independent. If coming from untrusted input, it could be any value. */\n\nbuf.nameID = (int)(defaultMessage + 1);printf(\"Pointer of buf.name is now %p\\n\", buf.name);if (buf.msgType == NAME_TYPE) {printf(\"Message: %s\\n\", buf.name);}else {printf(\"Message: Use ID %d\\n\", buf.nameID);}\n}",
"output": "This program snippet has a vulnerability.The following code uses a union to support the representation of different types of messages. It formats messages differently, depending on their type.The code intends to process the message as a NAME_TYPE, and sets the default message to \"Hello World.\" However, since both buf.name and buf.nameID are part of the same union, they can act as aliases for the same memory location, depending on memory layout after compilation.As a result, modification of buf.nameID - an int - can effectively modify the pointer that is stored in buf.name - a string.Execution of the program might generate output such as:\n\nPointer of name is 10830\nPointer of name is now 10831\nMessage: ello World\n\nNotice how the pointer for buf.name was changed, even though buf.name was not explicitly modified.In this case, the first \"H\" character of the message is omitted. However, if an attacker is able to fully control the value of buf.nameID, then buf.name could contain an arbitrary pointer, leading to out-of-bounds reads or writes."
}
{
"input": "private boolean initialized = true;public void someMethod() {\nif (!initialized) {\n\n\n// perform initialization tasks\n...\ninitialized = true;\n}",
"output": "This program snippet has a vulnerability.Here, a boolean initiailized field is consulted to ensure that initialization tasks are only completed once. However, the field is mistakenly set to true during static initialization, so the initialization code is never reached."
}
{
"input": "char str[20];strcat(str, \"hello world\");printf(\"%s\", str);",
"output": "This program snippet has a vulnerability.The following code intends to concatenate a string to a variable and print the string.This might seem innocent enough, but str was not initialized, so it contains random memory. As a result, str[0] might not contain the null terminator, so the copy might start at an offset other than 0. The consequences can vary, depending on the underlying memory.If a null terminator is found before str[8], then some bytes of random garbage will be printed before the \"hello world\" string. The memory might contain sensitive information from previous uses, such as a password (which might occur as a result of CWE-14 or CWE-244). In this example, it might not be a big deal, but consider what could happen if large amounts of memory are printed out before the null terminator is found. If a null terminator isn't found before str[8], then a buffer overflow could occur, since strcat will first look for the null terminator, then copy 12 bytes starting with that location. Alternately, a buffer over-read might occur (CWE-126) if a null terminator isn't found before the end of the memory segment is reached, leading to a segmentation fault and crash."
}
{
"input": "char *test_string;\n if (i != err_val)\n {\ntest_string = \"Hello World!\";\n }\n printf(\"%s\", test_string);",
"output": "This program snippet has a vulnerability.This example will leave test_string in an unknown condition when i is the same value as err_val, because test_string is not initialized (CWE-456). Depending on where this code segment appears (e.g. within a function body), test_string might be random if it is stored on the heap or stack. If the variable is declared in static memory, it might be zero or NULL. Compiler optimization might contribute to the unpredictability of this address. When the printf() is reached, test_string might be an unexpected address, so the printf might print junk strings (CWE-457). \n\n\t\t\t To fix this code, there are a couple approaches to\n\t\t\t making sure that test_string has been properly set once\n\t\t\t it reaches the printf().\nOne solution would be to set test_string to an\n\t\t\t acceptable default before the conditional:\nAnother solution is to ensure that each\n\t\t\t branch of the conditional - including the default/else\n\t\t\t branch - could ensure that test_string is set:"
}
{
"input": "private boolean initialized = true;public void someMethod() {\nif (!initialized) {\n\n\n// perform initialization tasks\n...\ninitialized = true;\n}",
"output": "This program snippet has a vulnerability.Here, a boolean initiailized field is consulted to ensure that initialization tasks are only completed once. However, the field is mistakenly set to true during static initialization, so the initialization code is never reached."
}
{
"input": "char str[20];strcat(str, \"hello world\");printf(\"%s\", str);",
"output": "This program snippet has a vulnerability.The following code intends to concatenate a string to a variable and print the string.This might seem innocent enough, but str was not initialized, so it contains random memory. As a result, str[0] might not contain the null terminator, so the copy might start at an offset other than 0. The consequences can vary, depending on the underlying memory.If a null terminator is found before str[8], then some bytes of random garbage will be printed before the \"hello world\" string. The memory might contain sensitive information from previous uses, such as a password (which might occur as a result of CWE-14 or CWE-244). In this example, it might not be a big deal, but consider what could happen if large amounts of memory are printed out before the null terminator is found. If a null terminator isn't found before str[8], then a buffer overflow could occur, since strcat will first look for the null terminator, then copy 12 bytes starting with that location. Alternately, a buffer over-read might occur (CWE-126) if a null terminator isn't found before the end of the memory segment is reached, leading to a segmentation fault and crash."
}
{
"input": "char *test_string;\n if (i != err_val)\n {\ntest_string = \"Hello World!\";\n }\n printf(\"%s\", test_string);",
"output": "This program snippet has a vulnerability.This example will leave test_string in an unknown condition when i is the same value as err_val, because test_string is not initialized (CWE-456). Depending on where this code segment appears (e.g. within a function body), test_string might be random if it is stored on the heap or stack. If the variable is declared in static memory, it might be zero or NULL. Compiler optimization might contribute to the unpredictability of this address. When the printf() is reached, test_string might be an unexpected address, so the printf might print junk strings (CWE-457). \n\n\t\t\t To fix this code, there are a couple approaches to\n\t\t\t making sure that test_string has been properly set once\n\t\t\t it reaches the printf().\nOne solution would be to set test_string to an\n\t\t\t acceptable default before the conditional:\nAnother solution is to ensure that each\n\t\t\t branch of the conditional - including the default/else\n\t\t\t branch - could ensure that test_string is set:"
}
{
"input": "def main():\n\n sum = 0\n numbers = eval(input(\"Enter a space-separated list of numbers: \"))\n for num in numbers:\n\n sum = sum + num\n\n print(f\"Sum of {numbers} = {sum}\")\n \n main()",
"output": "This program snippet has a vulnerability.This simple script asks a user to supply a list of numbers as input and adds them together.The eval() function can take the user-supplied list and convert it into a Python list object, therefore allowing the programmer to use list comprehension methods to work with the data. However, if code is supplied to the eval() function, it will execute that code. For example, a malicious user could supply the following string:This would delete all the files in the current directory. For this reason, it is not recommended to use eval() with untrusted input.A way to accomplish this without the use of eval() is to apply an integer conversion on the input within a try/except block. If the user-supplied input is not numeric, this will raise a ValueError. By avoiding eval(), there is no opportunity for the input string to be executed as code.An alternative option is to use the ast.literal_eval() function from Python's ast module. This function considers only Python literals as valid data types and will not execute any code contained within the user input."
}