Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nullPointer at Enforcer #53

Closed
amelleHamouch opened this issue Feb 13, 2020 · 8 comments · Fixed by #75
Closed

nullPointer at Enforcer #53

amelleHamouch opened this issue Feb 13, 2020 · 8 comments · Fixed by #75
Assignees
Labels

Comments

@amelleHamouch
Copy link

cas
Capturecas
null

It doesn't reach the condition , when I instanciate the Enforcer I immediatly entre the exception , please help

@hsluoyz hsluoyz transferred this issue from casbin/casbin Feb 13, 2020
@hsluoyz
Copy link
Member

hsluoyz commented Feb 13, 2020

Can you debug it and find the crashing line?

@hsluoyz hsluoyz self-assigned this Feb 13, 2020
@amelleHamouch
Copy link
Author

Line 69 , Enforcer enforcer = new Enforcer(tempConfPath, tempPoliciesPath);
says the enforcer is null

@hsluoyz
Copy link
Member

hsluoyz commented Feb 13, 2020

I can't squeeze out a bit information time to time like this. Can you provide a full working and runnable example to reproduce?

@amelleHamouch
Copy link
Author

amelleHamouch commented Feb 13, 2020

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.kapiasolutions.karma.filter;

import com.kapiasolutions.karma.util.LogUtil;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.casbin.jcasbin.main.Enforcer;

/**
*

  • @author ahamouch
    */
    @Provider
    public class JCasbinFilter implements ContainerRequestFilter {

    String conf;
    String policies;
    String key = "";

    @OverRide
    public void filter(ContainerRequestContext crc) throws IOException {

     try {
         InitialContext initialContext = new InitialContext();
         Context environmentContext = (Context) initialContext.lookup("java:/comp/env");
         configureCasbinFiles(environmentContext);
         UriInfo uriInfo = crc.getUriInfo();
         Request request = crc.getRequest();
         String requestPath = uriInfo.getPath();
         int index = requestPath.lastIndexOf("/");
         String object = requestPath.substring(index);
         String verb = request.getMethod();
         String domain = requestPath.replace(object, "");
         String confContent = decryptFile(key, conf);
         String polContent = decryptFile(key, policies);
    
         // adresse des fichier temporaires
         String tempConfPath = writeTempFile(confContent, conf);
         String tempPoliciesPath = writeTempFile(polContent, policies);
    
         //Utilisation de Enforcer de Casbin en lui passant les informations récupéré sur la requête
         Enforcer enforcer = new Enforcer(tempConfPath, tempPoliciesPath);
         //Si False accès non autorisé , requête annulée , envoi de la invalidAccessLevelResponse
         if (enforcer.enforce(object, domain, verb) == false) {
             String msg = String.format("You are not allowed to access this service", requestPath);
             CacheControl cc = new CacheControl();
             cc.setNoStore(true);
             Response invalidAccessLevelResponse = Response.status(Response.Status.FORBIDDEN)
                     .entity(msg)
                     .cacheControl(cc)
                     .build();
             crc.abortWith(invalidAccessLevelResponse);
         }
    
     } catch (NamingException ex) {
         LogUtil.showLog(ex);
     } catch (Exception ex) {
         Logger.getLogger(JCasbinFilter.class.getName()).log(Level.SEVERE, null, ex);
     }
    

    }

    //Création de la Réponse en cas d'accès refusé
    //Configuration de Casbin via les variables d'environnement
    private void configureCasbinFiles(Context environmentContext) throws NamingException {

     this.conf = (String) environmentContext.lookup("casbinConf");
     this.policies = (String) environmentContext.lookup("casbinPolicies");
    

    }

    //Lecture et récupération des données cryptées
    public static byte[] readCasbinFile(String path) throws Exception {

     byte[] encoded;
     encoded = Files.readAllBytes(Paths.get(path));
     return encoded;
    

    }

    //Génération de la clé à partir du String
    public static SecretKey generateKey(String keyStr) throws NoSuchAlgorithmException {
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecureRandom random = new SecureRandom(keyStr.getBytes());
    keygen.init(random);
    SecretKey secretKey = keygen.generateKey();
    return secretKey;
    }

    //Le fichier est décrypté ici
    public String decryptFile(String key, String path) throws Exception {
    SecretKey secretkey = generateKey(key);
    byte[] cipherText = readCasbinFile(path);
    byte[] IV = new byte[16];
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(secretkey.getEncoded(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(IV);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] decryptedText = cipher.doFinal(cipherText);
    String decrypt = new String(decryptedText);

     return decrypt;
    

    }

    //Création du fichier temporaire de config Casbin
    public String writeTempFile(String contentConf, String confFilePath) throws IOException {

     if (confFilePath.contains("model.conf")) {
         String tempPath = confFilePath.replace("model.conf", "tempModel.conf");
    
         FileWriter writer = new FileWriter(tempPath, false);
         writer.write(contentConf);
         writer.close();
         return tempPath;
     } else {
         String tempPath = confFilePath.replace("karma.policy", "Tempkarma.policy");
         FileWriter writer = new FileWriter(tempPath, false);
         writer.write(contentConf);
         writer.close();
         return tempPath;
     }
    

    }
    }

@hsluoyz
Copy link
Member

hsluoyz commented Feb 13, 2020

It's better in a GitHub repo, with project files, POM file, etc. So I can run it at once without copy-paste and setup a lot of code.

@amelleHamouch
Copy link
Author

eh ..I don't have the right to share this code unfortunately ><

@hsluoyz
Copy link
Member

hsluoyz commented Feb 13, 2020

You should provide a minimized example, only show the bug.

@dimi-nk
Copy link

dimi-nk commented Jun 7, 2020

I bumped into a similar issue last night. The code that parses the policy.csv expects everything to be delimited with ", " and nothing else. I'll make a PR to make that a bit more lenient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants