César Calvo
2016-09-28 e1d59acfb21c99b8b1b0ca0504b599f9ac444d19
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
package net.curisit.securis.utils;
import java.io.InputStream;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.curisit.securis.SeCurisException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
 * Retrieve HW info
 * 
 * @author cesarcalvo
 * 
 */
public class HWInfo {
   private static final Logger log = LogManager.getLogger(HWInfo.class);
   public static String getOsName() {
       return System.getProperty("os.name");
   }
   public static String getArch() {
       return System.getProperty("os.arch");
   }
   public static int getNumCpus() {
       return Runtime.getRuntime().availableProcessors();
   }
   /**
    * Gets MAC address using Java. Java does not show information about down interfaces
    * 
    * @return
    */
   public static List<String> getMACAddress() throws SeCurisException {
       log.info("Retrieving HW info with Java VM");
       List<byte[]> macs = new ArrayList<byte[]>();
       try {
           for (NetworkInterface network : Collections.list(NetworkInterface.getNetworkInterfaces())) {
               if (!network.isLoopback() && !network.isVirtual() && !network.isPointToPoint() && network.getHardwareAddress() != null) {
                   macs.add(network.getHardwareAddress());
                   log.debug("Interface added {}, MAC: {}", network.getName(), network.getHardwareAddress());
                   logInterface(network);
               }
           }
           if (macs.isEmpty()) {
               throw new SeCurisException("Unable to get MAC address");
           }
           List<String> macAddresses = new ArrayList<String>();
           for (byte[] mac : macs) {
               macAddresses.add(printMacAddress(mac));
           }
           log.info("MAC Addresses: {}", macAddresses);
           return macAddresses;
       } catch (Exception e) {
           throw new SeCurisException("Unable to get MAC address", e);
       } 
   }
   /**
    * Gets MAC address natively using ipconfig or ifconfig.
    * @return
    * @throws CurisException
    */
   public static List<String> getMACAddressNatively() throws SeCurisException {
       try {
           log.info("Retrieving HW info natively");
           String output;
           if (isWindows()) {
               output = executeCommand(new String[] {"ipconfig", "/all"});
           } else {
               output = executeCommand(new String[] {"ifconfig", "-a"});
           }
           //String output = FileUtils.readFileToString(new File("/Users/cesar/Downloads/ipconfig_no_mac.txt"), "UTF-8");
           log.debug("Command output {}", output);
           List<String> macs = extractMacs(output);
           log.debug("Macs found: {}", macs);
           return macs;
       } catch (SeCurisException ce) {
           throw ce;
       }
   }
   
   /**
    * Tries to retrieve MAC address natively, if it fails then it tries to retrieve it using Java
    * @return
    * @throws CurisException
    */
   public static List<String> getMACAddressNativelyFailback() throws SeCurisException {
       try {
           return getMACAddressNatively();
       } catch (SeCurisException e) {
           log.info("Error getting HW info natively" .concat(e.getMessage()));            
           return getMACAddress();
       }
   }    
   
   /**
    * Finds MAC in a string.  Match string like this:
    * Unix: 60:03:08:95:ae:d0
    * Windows: 0A-00-27-00-00-00
    * 
    * @param line
    * @return
    * @throws CurisException
    */
   private static List<String> extractMacs(String line) throws SeCurisException {
       Pattern pattern = Pattern.compile("(?m)( )([0-9a-fA-F][0-9a-fA-F][:-]){5}([0-9a-fA-F][0-9a-fA-F])($| )");
       
       List<String> macs = new ArrayList<>();
       Matcher matcher = pattern.matcher(line);
       while(matcher.find()){
           String mac = matcher.group().trim().replaceAll(":", "-").toUpperCase();
           if (!mac.equals("00-00-00-00-00-00")) {
               macs.add(mac);
           }
       }
       
       if (macs.isEmpty()) {
           throw new SeCurisException("Mac is not found");
       }
       
       return macs;
   }    
   /**
    * Executes the given command and return the standard output.
    * @param command
    * @return
    * @throws Exception
    */
   private static String executeCommand(String[] command) throws SeCurisException {
       try {
           Process process = new ProcessBuilder(command).start();
           InputStream is = process.getInputStream();
                   
           String output = IOUtils.toString(is, "UTF-8"); 
           if (process == null || process.exitValue() != 0) {
               throw new SeCurisException(String.format("Error executing command %s", StringUtils.join(command, " ")));
           }        
           return output;
       } catch (Exception e) {
           throw new SeCurisException(String.format("Error executing command %s", StringUtils.join(command, " ")), e);
       }
   }
   
   /**
    * Returns true is OOSS is windows
    * @return
    */
   public static boolean isWindows() {
       String os = System.getProperty("os.name").toLowerCase();
       return (os.indexOf("win") >= 0);
   }    
   /**
    * Get microprocessor name
    * 
    * @return
    */
   public static String getCPUName() throws SeCurisException {
       return System.getenv("PROCESSOR_IDENTIFIER");
   }
   private static void logInterface(NetworkInterface network) {
       log.debug("Interface name: {}", network.getName());
       log.debug("Interface display name: {}", network.getDisplayName());
       try {
           log.debug("Interface mac: {}", printMacAddress(network.getHardwareAddress()));
       } catch (SocketException e) {
           // Silent
       }
   }
   private static String printMacAddress(byte[] mac) {
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < mac.length; i++) {
           sb.append(String.format("%s%02X", (i > 0) ? "-" : "", mac[i]));
       }
       return sb.toString();
   }
}