Skip to content
Snippets Groups Projects
AutoSecurityGenerationDiplodocusTest.java 12.4 KiB
Newer Older
package tmltranslator;

import common.ConfigurationTTool;
import myutil.FileUtils;
import myutil.TraceManager;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import test.AbstractTest;
import tmltranslator.patternhandling.SecurityGenerationForTMAP;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.json.*;

import static org.junit.Assert.*;

public class AutoSecurityGenerationDiplodocusTest extends AbstractTest {
    private final static String DIR_GEN = "tmltranslator/AutoSecGenDiplodocusTest/GeneratedFiles/";
    private final static String DIR_MODELS = "tmltranslator/AutoSecGenDiplodocusTest/Models/";
    private final static String JSON_FILE_NAME = "features.json";
    private final static String PATH_MODEL = "pathModel";
    private final static String CHANNELS_LIST = "channels";
    private final static String HSM_LIST = "HSM";
    private final static String PATH_GOLDEN = "pathGolden";
    private final static String IS_DIRECT_CONNECT_HSM = "DirectConnectHSMs";
    private final static int ENCRYPTION_COMPUTATION = 100;
    private final static int DECRYPTION_COMPUTATION = 100;
    private final static int OVERHEAD = 100;

    static String PROVERIF_DIR;
    static String MODELS_DIR;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        String baseResourcesDir = getBaseResourcesDir();

        PROVERIF_DIR = baseResourcesDir + DIR_GEN;
        MODELS_DIR = baseResourcesDir + DIR_MODELS;
        RESOURCES_DIR = baseResourcesDir + DIR_MODELS;

    }

    public AutoSecurityGenerationDiplodocusTest() {
        super();
    }

    @Before
    public void setUp() throws Exception {
        TraceManager.devPolicy = TraceManager.TO_CONSOLE;
        ConfigurationTTool.ProVerifVerifierPath = "proverif";
        TraceManager.addDev("Starting test for Security Generation");
        Path path = Paths.get(PROVERIF_DIR);
        if (!Files.exists(path)) {
            Files.createDirectory(path);
        }
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSecurityModels() throws Exception {
        // Test if proverif is installed in the path
        TraceManager.addDev("Testing if \"proverif\" is in the PATH");
        assertTrue(canExecute("proverif"));
        TraceManager.addDev("Starting function testSecurityModels");
        File dir = new File(MODELS_DIR);
        Collection<File> allFiles = FileUtils.listFiles(dir, null, true);
        List<File> jsonFiles = new ArrayList<>();
        for (Iterator iterator = allFiles.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            if (file.getName().equals(JSON_FILE_NAME)) {
                jsonFiles.add(file);
            }
        }

        for (File jsonFile : jsonFiles) {
            String fileName = jsonFile.getAbsolutePath();
            String tab = fileName.split("/")[fileName.split("/").length - 2];
            TraceManager.addDev("\n\n********** Generating security for " + tab + " ********\n");
            String jsonString = new String(Files.readAllBytes(Paths.get(fileName)));
            JSONObject jo = new JSONObject(jsonString);
            String pathModel = getBaseResourcesDir() + jo.getString(PATH_MODEL);
            String pathDirJsonFile = fileName.substring(0, fileName.lastIndexOf("/") + 1);

            TMLMappingTextSpecification tmts = new TMLMappingTextSpecification(tab);
            File f = new File(pathModel);
            TraceManager.addDev("Loading file: " + f.getAbsolutePath());
            String spec = null;
            try {
                spec = FileUtils.loadFileData(f);
            } catch (Exception e) {
                TraceManager.addDev("Exception executing: loading " + tab);
                fail();
            }
            String pathDirModel = pathModel.substring(0, pathModel.lastIndexOf("/") + 1);
            TraceManager.addDev("Testing spec " + tab);
            assertNotNull(spec);
            TraceManager.addDev("Going to parse " + tab);
            boolean parsed = tmts.makeTMLMapping(spec, pathDirModel);
            assertTrue(parsed);

            TraceManager.addDev("Checking syntax " + tab);
            // Checking syntax
            TMLMapping tmap = tmts.getTMLMapping();

            TMLSyntaxChecking syntax = new TMLSyntaxChecking(tmap);
            syntax.checkSyntax();

            if (syntax.hasErrors() > 0) {
                for (TMLError error: syntax.getErrors()) {
                    TraceManager.addDev("Error: " + error.toString());
                }
            }

            assertEquals(0, syntax.hasErrors());
            TMLModeling<?> tml = tmap.getTMLModeling();
            String tabName = tml.getTasks().get(0).getName().substring(0, tml.getTasks().get(0).getName().indexOf("__"));
            JSONArray selectedChannels = jo.getJSONArray(CHANNELS_LIST);
            for (int i = 0; i < selectedChannels.length(); i++) {
                for (String channelName : selectedChannels.getJSONObject(i).keySet()) {
                    JSONArray channelSecGoals = selectedChannels.getJSONObject(i).getJSONArray(channelName);
                    boolean confGoal = channelSecGoals.getBoolean(0);
                    boolean weakAuthGoal = channelSecGoals.getBoolean(1);
                    boolean strongAuthGoal = channelSecGoals.getBoolean(2);
                    TMLChannel ch = tmap.getChannelByName(tabName + "__" + channelName);
                    if (ch != null) {
                        ch.setSecurityGoalConf(confGoal);
                        ch.checkConf = confGoal;
                        ch.setSecurityGoalWeakAuth(weakAuthGoal);
                        if (strongAuthGoal) {
                            ch.setSecurityGoalWeakAuth(true);
                            ch.setSecurityGoalStrongAuth(true);
                        }

                        if (weakAuthGoal || strongAuthGoal) {
                            ch.checkAuth = true;
                        }
                    }
                }
            }

            JSONArray selectedTasksHSMJA = jo.getJSONArray(HSM_LIST);
            List<String> selectedTasksHSM = new ArrayList<>();

            boolean isDirectConnectHSM = jo.getBoolean(IS_DIRECT_CONNECT_HSM);
            for (int i = 0; i < selectedTasksHSMJA.length(); i++) {
                selectedTasksHSM.add(selectedTasksHSMJA.getString(i));
            }
            ConfigurationTTool.ProVerifCodeDirectory = pathDirJsonFile;

            SecurityGenerationForTMAP secgen = new SecurityGenerationForTMAP(tabName, tmap, Integer.toString(ENCRYPTION_COMPUTATION),
                    Integer.toString(OVERHEAD), Integer.toString(DECRYPTION_COMPUTATION), selectedTasksHSM, isDirectConnectHSM, 600);
            tmap = secgen.startThread();

            if (tmap != null) {
                tmap = secgen.autoMapKeys();
            }

            tmap.resetMinimalMapping();
            TraceManager.addDev("Checking syntax of generated model " + tab);
            // Checking syntax
            TMLSyntaxChecking syntaxGenerated = new TMLSyntaxChecking(tmap);
            syntaxGenerated.checkSyntax();

            if (syntaxGenerated.hasErrors() > 0) {
                for (TMLError error: syntaxGenerated.getErrors()) {
                    TraceManager.addDev("Error: " + error.toString());
                }
            }
            assertEquals(0, syntaxGenerated.hasErrors());

            TMLMappingTextSpecification<Class<?>> specNew = new TMLMappingTextSpecification<Class<?>>(tab);
            specNew.toTextFormat((TMLMapping<Class<?>>) tmap);

            specNew.saveFile(pathDirJsonFile, "spec");

            TraceManager.addDev("End creating model with Security generation for " + tab);

            // Generate golden model spec
            TraceManager.addDev("Generating golden model spec for " + tab);
            String pathGolden = getBaseResourcesDir() + jo.getString(PATH_GOLDEN);
            TMLMappingTextSpecification tmtsGolden = new TMLMappingTextSpecification(tab);

            File fGolden = new File(pathGolden);
            TraceManager.addDev("Loading file: " + fGolden.getAbsolutePath());
            String specGolden = null;
            try {
                specGolden = FileUtils.loadFileData(fGolden);
            } catch (Exception e) {
                TraceManager.addDev("Exception executing: loading " + tab);
                fail();
            }
            TraceManager.addDev("Testing spec " + tab);
            assertNotNull(specGolden);
            TraceManager.addDev("Going to parse golden Model" + tab);
            String pathDirGolden = pathGolden.substring(0, pathGolden.lastIndexOf("/") + 1);
            boolean parsedGoden = tmtsGolden.makeTMLMapping(specGolden, pathDirGolden);
            assertTrue(parsedGoden);

            TraceManager.addDev("Checking syntax of golden model " + tab);
            // Checking syntax
            TMLMapping tmapGolden = tmtsGolden.getTMLMapping();

            TMLSyntaxChecking syntaxGolden = new TMLSyntaxChecking(tmapGolden);
            syntaxGolden.checkSyntax();

            if (syntaxGolden.hasErrors() > 0) {
                for (TMLError error: syntaxGolden.getErrors()) {
                    TraceManager.addDev("Error: " + error.toString());
                }
            }

            assertEquals(0, syntaxGolden.hasErrors());
            TraceManager.addDev("Comparing golden model with generated model " + tab);

            for (Object obj : tmap.getTMLModeling().getTasks()) {
                TMLTask task = (TMLTask) obj;
                String[] taskNameSplit = task.getName().split("__");
                task.setName(taskNameSplit[taskNameSplit.length - 1]);
            }
            for (Object obj : tmap.getTMLModeling().getChannels()) {
                TMLChannel ch = (TMLChannel) obj;
                String[] channelNameSplit = ch.getName().split("__");
                ch.setName(channelNameSplit[channelNameSplit.length - 1]);
            }
            for (Object obj : tmap.getTMLModeling().getEvents()) {
                TMLEvent evt = (TMLEvent) obj;
                String[] eventNameSplit = evt.getName().split("__");
                evt.setName(eventNameSplit[eventNameSplit.length - 1]);
            }
            for (Object obj : tmap.getTMLModeling().getRequests()) {
                TMLRequest req = (TMLRequest) obj;
                String[] requestNameSplit = req.getName().split("__");
                req.setName(requestNameSplit[requestNameSplit.length - 1]);
            }

            for (Object obj : tmapGolden.getTMLModeling().getTasks()) {
                TMLTask task = (TMLTask) obj;
                String[] taskNameSplit = task.getName().split("__");
                task.setName(taskNameSplit[taskNameSplit.length - 1]);
            }
            for (Object obj : tmapGolden.getTMLModeling().getChannels()) {
                TMLChannel ch = (TMLChannel) obj;
                String[] channelNameSplit = ch.getName().split("__");
                ch.setName(channelNameSplit[channelNameSplit.length - 1]);
            }
            for (Object obj : tmapGolden.getTMLModeling().getEvents()) {
                TMLEvent evt = (TMLEvent) obj;
                String[] eventNameSplit = evt.getName().split("__");
                evt.setName(eventNameSplit[eventNameSplit.length - 1]);
            }
            for (Object obj : tmapGolden.getTMLModeling().getRequests()) {
                TMLRequest req = (TMLRequest) obj;
                String[] requestNameSplit = req.getName().split("__");
                req.setName(requestNameSplit[requestNameSplit.length - 1]);
            }

            for (Object obj : tmapGolden.getTMLModeling().getChannels()) {
                TMLChannel ch = (TMLChannel) obj;
                if (tmap.getChannelByName(ch.getName()) != null) {
                    ch.setSecurityGoalConf(tmap.getChannelByName(ch.getName()).isSecurityGoalConf());
                    ch.setSecurityGoalWeakAuth(tmap.getChannelByName(ch.getName()).isSecurityGoalWeakAuth());
                    ch.setSecurityGoalStrongAuth(tmap.getChannelByName(ch.getName()).isSecurityGoalStrongAuth());
                    ch.checkConf = tmap.getChannelByName(ch.getName()).isCheckConfChannel();
                    ch.checkAuth = tmap.getChannelByName(ch.getName()).isCheckAuthChannel();
                }
            }
            assertTrue(tmapGolden.equalsSpec(tmap));
            TraceManager.addDev("Verifying Tmap equality ended " + tab);

            TraceManager.addDev("Test for " + tab + " tab is ended");
        }
    }
}