summaryrefslogtreecommitdiff
path: root/src/main/java/org/schemaspy/DBFuzzer.java
blob: 64ca58e4bc6baab50aa8d7e1e90b90bdf89b2def (plain)
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

package org.schemaspy;

import java.lang.invoke.MethodHandles;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

import org.parboiled.parserunners.ProfilingParseRunner;
import org.schemaspy.model.*;
import org.schemaspy.model.Table;
import org.schemaspy.model.GenericTree;
import org.schemaspy.model.GenericTreeNode;
import org.schemaspy.service.DatabaseService;
import org.schemaspy.service.SqlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class DBFuzzer
{

    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private SchemaAnalyzer analyzer; // Passed from the schemaAnalyser object from the runAnalyzer part. Contains sqlService object used to perform sql Queries

    private GenericTree mutationTree = new GenericTree();

    public DBFuzzer(SchemaAnalyzer analyzer)
    {
      this.analyzer = analyzer;
    }

    public boolean processFirstMutation(GenericTreeNode rootMutation)
    {
        boolean returnStatus=true;
        int nbUpdates = 0;
        try
        {
            if(rootMutation.getChosenChange() != null)
            {
                nbUpdates = rootMutation.inject(analyzer.getSqlService(),analyzer.getDb(),mutationTree,false);
                if(nbUpdates > 0)
                {
                    LOGGER.info("GenericTreeNode was sucessfull");
                }
                else
                    LOGGER.info("QueryError");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            returnStatus = false;
        }


        //Evaluation
        if(nbUpdates != 0)
        {
            try {
                // the evaluator sets a mark for representing how interesting the mutation was
                //Process tmpProcess = new ProcessBuilder("/bin/bash", "./emulated_program.sh").start(); // this should go soon now.
                //mark = Integer.parseInt(getEvaluatorResponse(tmpProcess));
                //currentMutation.setInterest_mark(mark);
                //currentMutation.setWeight(mark);
                //currentMutation.propagateWeight(); //update parents weight according to this node new weight

                int mark = 0;

                LOGGER.info("Target is : " + analyzer.getCommandLineArguments().getTarget());
                Process evaluatorProcess = new ProcessBuilder("/bin/bash", "./stackTraceCParser.sh", analyzer.getCommandLineArguments().getTarget(), Integer.toString(rootMutation.getId())).start();
                evaluatorProcess.waitFor();
                ReportVector mutationReport = new ReportVector(rootMutation);
                mutationReport.parseFile("errorReports/parsedStackTrace_" + rootMutation.getId());
                mutationReport.setStackTraceHash(mutationReport.hashStackTrace(mutationTree));
                rootMutation.setReportVector(mutationReport);
                mark = new Scorer().score(rootMutation, mutationTree);
                rootMutation.setInterest_mark(mark);
                rootMutation.setWeight(mark);
                rootMutation.propagateWeight();
                System.out.println("marking : " + mark);
                System.out.println("Weight : " + rootMutation.getWeight());
            }
            catch (Exception e)
            {
                e.printStackTrace();
                returnStatus = false;
            }
        }

        return returnStatus;
    }

    public boolean fuzz (Config config)
    {
        boolean returnStatus = true;
        int TreeDepth = 0;
        int maxDepth = Integer.parseInt(analyzer.getCommandLineArguments().getMaxDepth());
        int mark = 0;
        int nbUpdates = 0;


        //adding CASCADE to all foreign key tableColumns.
        settingTemporaryCascade(false); // need to drop and recreate database

        LOGGER.info("Starting Database Fuzzing");

        GenericTreeNode currentMutation;
        // Building root Mutation. Could be extended by looking for a relevant first SingleChange as rootMutation
        do {
            Row randomRow = pickRandomRow();
            currentMutation = new GenericTreeNode(randomRow, nextId(),analyzer.getSqlService());
        } while(currentMutation.getPotential_changes().isEmpty());
        currentMutation.setChosenChange(currentMutation.getPotential_changes().get(0));
        currentMutation.initPostChangeRow();
        mutationTree.setRoot(currentMutation);

        if(!processFirstMutation(currentMutation))
            return false;
        /*
        * Main loop. Picks and inject a mutation chosen based on its weight (currently equal to its mark)
        * After injecting and retrieving the marking for the evaluator,
        * undoes necessary mutations from the tree to setup for next mutation
        */
        while(TreeDepth != maxDepth)
        {
          //Choosing next mutation
          currentMutation = chooseNextMutation();
          while(!this.isNewMutation(currentMutation))
          {
            System.out.println("this GenericTreeNode has already been tried ");
            currentMutation = chooseNextMutation();
          }

          if(currentMutation.getInitial_state_row().compare(currentMutation.getPost_change_row()))
              System.out.println("ICI");

          System.out.println("chosen mutation "+currentMutation);
          System.out.println("parent mutation "+currentMutation.getParent());

            if(!currentMutation.getParent().compare(mutationTree.getLastMutation()))
            {
              try
              {
                mutationTree.getLastMutation().undoToMutation(currentMutation.getParent(),analyzer,mutationTree);

              }
              catch(Exception e)
              {
                e.printStackTrace();
              }
            }
            //Injection
            try
            {
                if(currentMutation.getChosenChange() != null)
                {
                    nbUpdates = currentMutation.inject(analyzer.getSqlService(),analyzer.getDb(),mutationTree,false);
                    if(nbUpdates > 0)
                    {
                        LOGGER.info("GenericTreeNode was sucessfull");
                        currentMutation.updatePotentialChangeAfterInjection();
                        mutationTree.addToTree(currentMutation);
                    }
                    else if (nbUpdates == 0 || nbUpdates == -1)
                    {
                        if (nbUpdates == 0)
                            LOGGER.info("QueryError. This update affected 0 rows.");
                        else
                        {
                            LOGGER.info("GenericTreeNode was sucessfull");
                            currentMutation.updatePotentialChangeAfterInjection();
                            mutationTree.addToTree(currentMutation);
                        }

                        if(!currentMutation.getParent().compare(mutationTree.getLastMutation()))
                        {
                            try
                            {
                                currentMutation.getParent().undoToMutation(mutationTree.getLastMutation(),analyzer,mutationTree);
                            }
                            catch(Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                    else
                        LOGGER.info("Injection returned unknown error code.");


                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
                returnStatus = false;
            }

            //Evaluation\
            if(nbUpdates != 0)
            {
                try {
                    // the evaluator sets a mark for representing how interesting the mutation was
                    //Process tmpProcess = new ProcessBuilder("/bin/bash", "./emulated_program.sh").start(); // this should go soon now.
                    //mark = Integer.parseInt(getEvaluatorResponse(tmpProcess));
                    //currentMutation.setInterest_mark(mark);
                    //currentMutation.setWeight(mark);
                    //currentMutation.propagateWeight(); //update parents weight according to this node new weight

                    LOGGER.info("Target is : " + analyzer.getCommandLineArguments().getTarget());
                    ProcessBuilder ep = new ProcessBuilder("/bin/bash", "./stackTraceCParser.sh", analyzer.getCommandLineArguments().getTarget(), Integer.toString(currentMutation.getId()), analyzer.getCommandLineArguments().getNestedArguments());
                    ArrayList<GenericTreeNode> pathToRoot = currentMutation.pathToRoot();
                    Collections.reverse(pathToRoot);
                    for(int i=0; i< pathToRoot.size();i++)
                    {
                        ep.environment().put("mut_"+pathToRoot.get(i).getId(),pathToRoot.get(i).getChosenChange().toString());
                    }
                    Process evaluatorProcess = ep.start();
                    evaluatorProcess.waitFor();
                    ReportVector mutationReport = new ReportVector(currentMutation);
                    mutationReport.parseFile("errorReports/parsedStackTrace_" + currentMutation.getId()); // initialises the reportVector stacktrace
                    mutationReport.setStackTraceHash(mutationReport.hashStackTrace(mutationTree));
                    currentMutation.setReportVector(mutationReport);
                    if(currentMutation.getReportVector().isErrorTriggered() == true)
                        mark = new Scorer().score(currentMutation, mutationTree);
                    else
                        mark = 0;
                    currentMutation.setInterest_mark(mark);
                    currentMutation.setWeight(mark);
                    currentMutation.propagateWeight();
                    System.out.println("marking : " + mark);
                    System.out.println("Weight : " + currentMutation.getWeight());
                } catch (Exception e) {
                    e.printStackTrace();
                    returnStatus = false;
                }
                TreeDepth = mutationTree.checkMaxDepth(mutationTree.getRoot());
            }
      }

        removeTemporaryCascade();
        printMutationTree();
        if(analyzer.getCommandLineArguments().getReport() != null) {
            if (analyzer.getCommandLineArguments().getReport().equals("y") || analyzer.getCommandLineArguments().getReport().equals("yes")) {
                LOGGER.info("CLEAN UP");
                try {
                    Process evaluatorProcess = new ProcessBuilder("/bin/bash", "./cleanup.sh").start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        boolean tmp = revertToOriginalDatabaseState(mutationTree);
        System.out.println(" reverting to original state ended up in "+tmp+"ending process");
      return returnStatus;
    }


    //Extract Random row from the db specified in sqlService
    public Row pickRandomRow()
    {
        Row res = null;
        do {
          Table randomTable = pickRandomTable();

          //String theQuery = "SELECT * FROM " + randomTable.getName() + " ORDER BY RANDOM() LIMIT 1";
          String theQuery = "SELECT * FROM "+randomTable.getName()+" ORDER BY RANDOM() LIMIT 1"; // Change test_table2 to test_table here to swap back to line finding
          PreparedStatement stmt;

          try
          {
              stmt = analyzer.getSqlService().prepareStatement(theQuery);
              ResultSet rs = stmt.executeQuery();
              res = new QueryResponseParser().parse(rs, analyzer.getDb().getTablesMap().get(randomTable.getName())).getRows().get(0); // randomTable should be in the get()
          }
          catch (Exception e)
          {
              LOGGER.info("This query threw an error while looking for a row" + e);
          }
        }
        while(res == null);
            return res;
    }

    public Table pickRandomTable()
    {
        Random rand = new Random();

        int i = 0, n = rand.nextInt(analyzer.getDb().getTablesMap().entrySet().size());

          for (Map.Entry<String, Table> entry : analyzer.getDb().getTablesMap().entrySet())
          {
            if(n == i)
              return entry.getValue();
            i++;
          }
          throw new RuntimeException("Random table wasn't found"); // should never be reached
    }


    public boolean settingTemporaryCascade(Boolean undo)
    {
          Iterator i;
          ForeignKeyConstraint currentFK;
          String dropSetCascade = "";
          for(Map.Entry<String,Collection<ForeignKeyConstraint>> entry : analyzer.getDb().getLesForeignKeys().entrySet())
          {
              i = entry.getValue().iterator();
              while(i.hasNext())
              {
                 currentFK = (ForeignKeyConstraint) i.next();
                 dropSetCascade = "ALTER TABLE "+currentFK.getChildTable().getName()+" DROP CONSTRAINT "+currentFK.getName()+ " CASCADE";
                 try
                 {
                     PreparedStatement stmt = analyzer.getSqlService().prepareStatement(dropSetCascade, analyzer.getDb(),null);
                     stmt.execute();
                 }
                 catch(Exception e)
                 {
                     e.printStackTrace();
                 }
          }

     }

      for(Map.Entry<String,Collection<ForeignKeyConstraint>> entry : analyzer.getDb().getLesForeignKeys().entrySet())
      {
          i = entry.getValue().iterator();
          while(i.hasNext())
          {
              currentFK = (ForeignKeyConstraint) i.next();
              if(!undo)
                  dropSetCascade = "ALTER TABLE "+currentFK.getChildTable().getName()+" ADD CONSTRAINT "+currentFK.getName()+" FOREIGN KEY ("+currentFK.getParentColumns().get(0).getName()+" ) REFERENCES "+currentFK.getParentTable().getName()+"("+currentFK.getChildColumns().get(0).getName()+") ON UPDATE CASCADE";
              else
              {
                  dropSetCascade = "ALTER TABLE "+currentFK.getChildTable().getName()+" ADD CONSTRAINT "+currentFK.getName()+" FOREIGN KEY ("+currentFK.getParentColumns().get(0).getName()+" ) REFERENCES "+currentFK.getParentTable().getName()+"("+currentFK.getChildColumns().get(0).getName()+")";
              }
              try
              {
                  PreparedStatement stmt = analyzer.getSqlService().prepareStatement(dropSetCascade, analyzer.getDb(),null);
                  stmt.execute();
              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
          }

      }
      if(!undo)
        LOGGER.info("temporary set all fk constraints to cascade");
      else
        LOGGER.info("set all the constraints back to original");

      return true;
    }

    public boolean removeTemporaryCascade()
    {
      return settingTemporaryCascade(true);
    }


    public String getEvaluatorResponse(Process p)
    {
        String response = "";
        try
        {

          BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
          String line;
          while ((line = r.readLine())!=null) {
            response = response+line;
          }
          r.close();
        }
        catch(Exception e)
        {
          System.out.println("error while reading process output"+e);
        }
        return response;
    }


    /*
    * Pick a mutation for next iteration of the main loop.
    *
    */
    public GenericTreeNode chooseNextMutation()
    {
        GenericTreeNode previousMutation = mutationTree.getLastMutation();
        double markingDiff = previousMutation.getInterest_mark();
        Random rand = new Random();

        if (mutationTree.getNumberOfNodes() > 1) // first mutation doesnt have a predecessor
        {
            markingDiff = previousMutation.getInterest_mark() - mutationTree.find(mutationTree.getLastId()).getInterest_mark();
        }

        if (mutationTree.getRoot() != null)
        {
            if (markingDiff > 0.0 ) //
            {
                System.out.println("creation1");
                int randNumber = rand.nextInt(previousMutation.getPotential_changes().size());
                GenericTreeNode nextMut = new GenericTreeNode(previousMutation.getPost_change_row(), nextId(), mutationTree.getRoot(), previousMutation,false,analyzer.getSqlService());
                nextMut.setChosenChange(previousMutation.getPotential_changes().get(randNumber));
                nextMut.initPostChangeRow();
                return nextMut;
            }
            else
            {
                Random changeOrDepthen = new Random(); // 1 inside tree, 2 is pick new random row

                if(changeOrDepthen.nextInt(2) == 1)
                {
                    System.out.println("creation2");
                    SingleChange tmp = mutationTree.getRoot().singleChangeBasedOnWeight();
                    GenericTreeNode nextMut = new GenericTreeNode(tmp.getAttachedToMutation().getPost_change_row(), nextId(), mutationTree.getRoot(), tmp.getAttachedToMutation(),false,analyzer.getSqlService());
                    nextMut.setChosenChange(tmp);
                    nextMut.initPostChangeRow();
                    return nextMut;
                }
                else
                {
                    System.out.println("creation3");
                    Row nextRow;
                    GenericTreeNode nextMut;
                    do
                    {
                        nextRow = pickRandomRow();
                        nextMut = new GenericTreeNode(nextRow, nextId(), mutationTree.getRoot(), previousMutation, true, analyzer.getSqlService());
                    }while(nextMut.getPotential_changes().isEmpty());

                    Random nextSingleChangeId = new Random();
                    nextMut.setChosenChange(nextMut.getPotential_changes().get(nextSingleChangeId.nextInt(nextMut.getPotential_changes().size())));
                    nextMut.initPostChangeRow();
                    return nextMut;
                }
            }
        }
        throw new Error("No mutation returned. That should not happen");
    }

    public boolean isNewMutation(GenericTreeNode newMut)
    {
        if(mutationTree.getRoot().compare(newMut) || newMut.isSingleChangeOnCurrentPath(mutationTree.getRoot()))
            return false;

        SingleChange chosenChange = newMut.getChosenChange();
        return !chosenChange.compareValues();
    }

    public void printMutationTree()
    {
        if(mutationTree.getNumberOfNodes() == 0)
            System.out.println("tree is empty");
        else {
            String displayer = "";
            for (int i = 1; i <= mutationTree.getNumberOfNodes(); i++) {
                for (int j = 0; j < mutationTree.find(i).getDepth(); j++) {
                    displayer = displayer + ("--");
                }
                displayer = displayer + (mutationTree.find(i).toString() + "\n");
            }
            System.out.println(displayer);
        }
    }

    public boolean revertToOriginalDatabaseState(GenericTree mutationTree)
    {
        int max = mutationTree.getLastId();
        boolean res= true;
        int tmp;

        for (int i = max; i > 0; i--)
        {
            tmp = mutationTree.find(i).undo(analyzer.getSqlService(),analyzer.getDb(),mutationTree);
            if(tmp == 0)
                res = false;
        }
        return res;
    }

    public int nextId()
    {
        return mutationTree.getLastId()+1;
    }


}