Integrating D-Link alarm into Home Security benchmark
[iot2.git] / iotjava / iotruntime / master / ProcessJailConfig.java
1 package iotruntime.master;
2
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.io.BufferedReader;
6 import java.io.BufferedWriter;
7 import java.io.FileWriter;
8 import java.io.PrintWriter;
9 import java.io.IOException;
10 import java.nio.file.Files;
11 import java.nio.file.Paths;
12 import java.nio.charset.StandardCharsets;
13 import java.util.HashMap;
14 import java.util.Map;
15
16 /** Class ProcessJailConfig is a class that configures the compute
17  *  nodes in our network with the relevant process jail policies;
18  *  <p>
19  *  We use Tomoyo 2.5 as a Mandatory Access Control (MAC) that is
20  *  simple, easy to maintain, and lightweight (suitable for embedded
21  *  devices).
22  *
23  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
24  * @version     2.0
25  * @since       2017-04-07
26  */
27 public final class ProcessJailConfig {
28
29         /**
30          * ProcessJailConfig constants
31          */
32         private static final String STR_SSH_USERNAME_ROUTER = "root";
33         private static final String STR_SSH_USERNAME_HOST   = "iotuser";
34         private static final String STR_TCP_PROTOCOL = "tcp";
35         private static final String STR_UDP_PROTOCOL = "udp";
36         private static final String STR_TCPGW_PROTOCOL = "tcpgw";
37         private static final String STR_NO_PROTOCOL = "nopro";
38
39         private static final String STR_MAC_POLICY_EXT          = ".tomoyo.pol";
40         private static final String STR_OBJECT_NAME             = "<object-name>";
41         private static final String STR_OBJECT_CLASS_NAME       = "<object-class-name>";
42         private static final String STR_MASTER_IP_ADDRESS       = "<master-ip-address>";
43         private static final String STR_MASTER_COM_PORT         = "<master-com-port>";
44         private static final String STR_RMI_REG_PORT            = "<rmi-reg-port>";
45         private static final String STR_RMI_STUB_PORT           = "<rmi-stub-port>";
46         private static final String STR_DEV_IP_ADDRESS          = "<dev-ip-address>";
47         private static final String STR_DEV_COM_PORT            = "<dev-com-port>";
48         private static final String STR_DEV_PORT                        = "<dev-port>";
49         
50     private static final int INT_HTTP_PORT = 80;
51     private static final int INT_DNS_PORT  = 53;
52
53
54         /**
55          * ProcessJailConfig properties
56          */
57         private Map<String, PrintWriter> mapHostToFile;
58         private Map<String, String> mapMACtoIPAdd;
59
60
61         /**
62          * Constructor
63          */
64         public ProcessJailConfig() {
65                 // This maps hostname to file PrintWriter
66                 mapHostToFile = new HashMap<String, PrintWriter>();
67                 mapMACtoIPAdd = null;
68         }
69
70
71         /**
72          * renewPrintWriter() renews the mapHostToFile object that lists all PrintWriters
73          *
74          * @return  void
75          */
76         public void renewPrintWriter() {
77
78                 mapHostToFile = new HashMap<String, PrintWriter>();
79         }
80
81
82         /**
83          * getPrintWriter() gets the right PrintWriter object to print policies to the right file
84          *
85          * @param   strConfigHost String hostname to be configured
86          * @return  PrintWriter
87          */
88         private PrintWriter getPrintWriter(String strConfigHost) {
89
90                 // Return object if existing
91                 if (mapHostToFile.containsKey(strConfigHost)) {
92                         return mapHostToFile.get(strConfigHost);
93                 } else {
94                 // Simply create a new one if it doesn't exist
95                         FileWriter fw = null;
96                         try {
97                                 fw = new FileWriter(strConfigHost + STR_MAC_POLICY_EXT);
98                         } catch (IOException ex) {
99                                 ex.printStackTrace();
100                         }
101                         PrintWriter pwConfig = new PrintWriter(new BufferedWriter(fw));
102                         mapHostToFile.put(strConfigHost, pwConfig);
103                         return pwConfig;
104                 }
105         }
106         
107
108         /**
109          * close() closes all PrintWriter objects
110          *
111          * @return  void
112          */
113         public void close() {
114
115                 for(PrintWriter pwConfig: mapHostToFile.values()) {
116                         pwConfig.close();
117                 }
118         }
119
120
121         /**
122          * sendMACPolicies() deploys policies on MAC implementation for process jailing
123          *
124          * @param   strConfigHost String hostname to be configured
125          * @return  void
126          */
127         public void sendMACPolicies(String strConfigHost) {
128
129                 String strCmdSend = "scp " + strConfigHost + STR_MAC_POLICY_EXT + " " + 
130                         STR_SSH_USERNAME_HOST + "@" + strConfigHost + ":~;";
131                 System.out.println(strCmdSend);
132                 runCommand(strCmdSend);
133                 String strCmdDeploy = "ssh " + STR_SSH_USERNAME_HOST + "@" + strConfigHost +
134                         " sudo tomoyo-loadpolicy -df < ~/" + strConfigHost + STR_MAC_POLICY_EXT + "; rm ~/" + strConfigHost + 
135                         STR_MAC_POLICY_EXT + ";";
136                 System.out.println(strCmdDeploy);
137                 runCommand(strCmdDeploy);
138         }
139
140
141         /**
142          * deployPolicies() method configures the policies
143          *
144          * @param   strCommand  String that contains command line
145          * @return  void
146          */
147         private void deployPolicies(String strCommand) {
148
149                 try {
150                         Runtime runtime = Runtime.getRuntime();
151                         Process process = runtime.exec(strCommand);
152                         process.waitFor();
153                 } catch (IOException ex) {
154                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
155                         ex.printStackTrace();
156                 } catch (InterruptedException ex) {
157                         System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
158                         ex.printStackTrace();
159                 }
160         }
161
162
163         /**
164          * setAddressListObject() method sets the map for IP and MAC addresses
165          * <p>
166          * This method gets the mapping from RouterConfig
167          */
168         public void setAddressListObject(Map<String, String> _mapMACtoIPAdd) {
169
170                 mapMACtoIPAdd = _mapMACtoIPAdd;
171         }
172
173
174         /**
175          * runCommand() method runs shell command
176          *
177          * @param   strCommand  String that contains command line
178          * @return  void
179          */
180         private void runCommand(String strCommand) {
181
182                 try {
183                         Runtime runtime = Runtime.getRuntime();
184                         Process process = runtime.exec(strCommand);
185                         process.waitFor();
186                 } catch (IOException ex) {
187                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
188                         ex.printStackTrace();
189                 } catch (InterruptedException ex) {
190                         System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
191                         ex.printStackTrace();
192                 }
193         }
194
195
196         /**
197          * getAddressList() method gets list of IP addresses
198          * <p>
199          * This method sends an inquiry to the router to look for
200          * the list of DHCP leased addresses and their mapping to MAC
201          * addresses
202          *
203          * @param  strRouterAddress  String that contains address of router
204          */
205         public void getAddressList(String strRouterAddress) {
206
207                 //HashMap<String,String> hmMACToIPAdd = new HashMap<String,String>();
208                 try {
209                         // We can replace "cat /tmp/dhcp.leases" with "cat /proc/net/arp"
210                         String cmd = "ssh " + STR_SSH_USERNAME_ROUTER + "@" + strRouterAddress +
211                          " cat /tmp/dhcp.leases";
212                         Runtime runtime = Runtime.getRuntime();
213                         Process process = runtime.exec(cmd);
214
215                         InputStream inStream = process.getInputStream();
216                         InputStreamReader isReader = new InputStreamReader(inStream);
217                         BufferedReader bReader = new BufferedReader(isReader);
218                         String strRead = null;
219                         while((strRead = bReader.readLine()) != null){
220                                 String[] str = strRead.split(" ");
221                                 mapMACtoIPAdd.put(str[1], str[2]);
222                         }
223                 } catch (IOException ex) {
224                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
225                         ex.printStackTrace();
226                 }
227         }
228
229
230         /**
231          * getIPFromMACAddress() method gets IP from MAC address
232          *
233          * @return  String  String that contains IP address from the MAC-IP mapping
234          */      
235         public String getIPFromMACAddress(String strMACAddress) {
236
237                 String strIPAddress = mapMACtoIPAdd.get(strMACAddress);
238                 if (strIPAddress == null) {
239                         throw new Error("RouterConfig: MAC address " + strMACAddress + 
240                                 " not found on the list! Please check if device is present in /tmp/dhcp.leases!");
241                 }
242                 return strIPAddress;
243         }
244
245
246         /**
247          * readFile() read the entire file and return a string
248          *
249          * @return  String  String that contains the content of the file
250          */      
251         public String readFile(String filePath) {
252
253                 String retStr = null;
254                 try {
255                         retStr = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
256                 } catch (IOException ex) {
257                         ex.printStackTrace();
258                 }
259                 return retStr;
260         }
261
262
263         /**
264          * configureProcessJailDeviceDriverPolicies() method configures the main MAC policies
265          * <p>
266          * This method configures the main policies between controller and device driver
267          *
268          * @param   strConfigHost                       String hostname to be configured
269          * @param   strObjectName                       String object name
270          * @param   strObjectClassName          String object class name
271          * @param   strFileName                         String policy file path and name
272          * @param   strMasterIPAddress          String master IP address
273          * @param   iComPort                            Integer communication port (controller-driver)
274          * @param   iRMIRegPort                         Integer RMI registry port
275          * @param   iRMIStubPort                        Integer RMI stub port
276          * @return  void
277          */
278         public void configureProcessJailDeviceDriverPolicies(String strConfigHost, String strObjectName, String strObjectClassName, 
279                         String strFileName, String strMasterIPAddress, int iComPort, int iRMIRegPort, int iRMIStubPort) {
280
281                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
282                 String strPolicyList = readFile(strFileName);
283                 // Replace the strings with the actual values
284                 String strNewPolicyList = strPolicyList.replace(STR_OBJECT_NAME, strObjectName).
285                         replace(STR_OBJECT_CLASS_NAME, strObjectClassName).
286                         replace(STR_MASTER_IP_ADDRESS, strMasterIPAddress).
287                         replace(STR_MASTER_COM_PORT, String.valueOf(iComPort));
288                         //replace(STR_RMI_REG_PORT, String.valueOf(iRMIRegPort)).
289                         //replace(STR_RMI_STUB_PORT, String.valueOf(iRMIStubPort));
290                 pwConfig.println("\n");
291                 pwConfig.print(strNewPolicyList);
292                 pwConfig.println("network inet stream bind/listen :: " + iRMIRegPort);
293                 pwConfig.println("network inet stream bind/listen :: " + iRMIStubPort);
294         }
295
296
297         /**
298          * configureProcessJailDevicePolicies() method configures the device MAC policies
299          * <p>
300          * This method configures the device policies between device driver and device
301          *
302          * @param   strConfigHost                       String hostname to be configured
303          * @param   strProtocol                         String protocol name
304          * @param       iDeviceComPort                  Integer device communication port
305          * @param   strDeviceIPAddress          String device IP address
306          * @param   iDevicePort                         Integer device port
307          * @return  void
308          */
309         public void configureProcessJailDevicePolicies(String strConfigHost, String strProtocol,
310                         int iDeviceComPort, String strDeviceIPAddress, int iDevicePort) {
311
312                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
313                 if (strProtocol.equals(STR_TCP_PROTOCOL)) {
314                         pwConfig.println("network inet stream connect ::ffff:" + strDeviceIPAddress + " " + String.valueOf(iDevicePort));
315                 } else {
316                         pwConfig.println("network inet dgram bind :: " + String.valueOf(iDeviceComPort));
317                         pwConfig.println("network inet dgram send ::ffff:" + strDeviceIPAddress + " " + String.valueOf(iDevicePort));
318                 }
319         }
320
321
322         /**
323          * configureProcessJailDevicePolicies() method configures the device MAC policies
324          * <p>
325          * This method configures the device policies between device driver and device
326          *
327          * @param   strConfigHost                       String hostname to be configured
328          * @param   strRouterAddress            String router address
329          * @param   iPort                                       Integer port
330          * @return  void
331          */
332         public void configureProcessJailGWDevicePolicies(String strConfigHost, String strRouterAddress, String strDeviceIPAddress, int iPort) {
333
334                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
335                 pwConfig.println("file read /home/iotuser/iot2/iotjava/iotruntime/\\*.jks");
336                 pwConfig.println("file read /etc/resolv.conf");
337                 pwConfig.println("file read /etc/hosts");
338         pwConfig.println("network inet stream connect ::ffff:" + strDeviceIPAddress + " " + String.valueOf(INT_HTTP_PORT));     // HTTP access for this address
339                 pwConfig.println("network inet dgram send " + strRouterAddress + " " + String.valueOf(iPort));
340         }
341
342
343         /**
344          * configureProcessJailDeviceDriverInetAddressPolicies() method configures the device MAC policies
345          * <p>
346          *
347          * @param   strConfigHost       String hostname to be configured
348          * @param   strAddress          String device IP address
349          * @return  void
350          */
351         public void configureProcessJailInetAddressPolicies(String strConfigHost, String strRouterAddress, String strAddress) {
352
353                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
354                 //System.out.println("\n\nDEBUG: Writing the config host address setup!!!\n\n");
355                 pwConfig.println("file read /etc/resolv.conf");
356                 pwConfig.println("file read /etc/hosts");
357                 pwConfig.println("file read /etc/host.conf");
358                 pwConfig.println("network inet dgram send " + strRouterAddress + " " + String.valueOf(INT_DNS_PORT));   // TCP/UDP access through router
359                 pwConfig.println("network inet stream connect ::ffff:" + strAddress + " " + String.valueOf(INT_HTTP_PORT));     // HTTP access for this address
360         }
361
362
363         /**
364          * configureProcessJailControllerPolicies() method configures the main MAC policies for controller
365          *
366          * @param   strControllerName           String controller name to be configured
367          * @param   strFileName                         String policy file path and name
368          * @param   strMasterIPAddress          String master IP address
369          * @param   iComPort                            Integer communication port (controller-driver)
370          * @return  void
371          */
372         public void configureProcessJailControllerPolicies(String strControllerName, String strFileName, 
373                         String strMasterIPAddress, int iComPort) {
374
375                 PrintWriter pwConfig = getPrintWriter(strControllerName);
376                 String strPolicyList = readFile(strFileName);
377                 // Replace the strings with the actual values
378                 String strNewPolicyList = strPolicyList.replace(STR_OBJECT_NAME, strControllerName).
379                         replace(STR_OBJECT_CLASS_NAME, strControllerName).
380                         replace(STR_MASTER_IP_ADDRESS, strMasterIPAddress).
381                         replace(STR_MASTER_COM_PORT, String.valueOf(iComPort));
382                 pwConfig.println("\n");
383                 pwConfig.print(strNewPolicyList);
384         }
385
386
387         /**
388          * configureProcessJailContRMIPolicies() method configures the MAC policies for RMI ports of controller
389          *
390          * @param   strControllerName           String controller name to be configured
391          * @param   strFileName                         String policy file path and name
392          * @param   strMasterIPAddress          String master IP address
393          * @param   iComPort                            Integer communication port (controller-driver)
394          * @return  void
395          */
396         public void configureProcessJailContRMIPolicies(String strControllerName, String strDeviceDriverIPAddress, 
397                         int iRMIRegPort, int iRMIStubPort) {
398
399                 PrintWriter pwConfig = getPrintWriter(strControllerName);
400                 // Replace the strings with the actual values
401                 pwConfig.println("network inet stream connect ::ffff:" + strDeviceDriverIPAddress + " " + String.valueOf(iRMIRegPort));
402                 pwConfig.println("network inet stream connect ::ffff:" + strDeviceDriverIPAddress + " " + String.valueOf(iRMIStubPort));
403         }
404
405
406         /**
407          * combineControllerMACPolicies() method combines the controller MAC policies into the right host policy file
408          *
409          * @param   strConfigHost                       String hostname to be configured
410          * @param   strFileName                         String policy file path and name
411          * @return  void
412          */
413         public void combineControllerMACPolicies(String strConfigHost, String strObjectControllerName, String strFileName) {
414
415                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
416                 PrintWriter pwCont = getPrintWriter(strObjectControllerName);
417                 pwCont.close();
418                 String strPolicyList = readFile(strFileName);
419                 pwConfig.println(strPolicyList);
420                 runCommand("rm -rf " + strFileName);
421         }
422 }
423
424