|
| 1 | +package analysis |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "crypto/sha256" |
| 7 | + "fmt" |
| 8 | + "html/template" |
| 9 | + "io" |
| 10 | + "microscope/formats" |
| 11 | + "microscope/formats/elf" |
| 12 | + "microscope/formats/pe" |
| 13 | + "microscope/heuristics" |
| 14 | + "os" |
| 15 | + "strconv" |
| 16 | + "time" |
| 17 | +) |
| 18 | + |
| 19 | +const ( |
| 20 | + FILE_HEADER_PHASE_1 = 5 // Numero di byte letti all'inizio della fase 1 (vedi documenti) per discriminare il file |
| 21 | +) |
| 22 | + |
| 23 | +var OutputTemplateHTML string |
| 24 | +var OutputTemplateTXT string |
| 25 | + |
| 26 | +func divide(a int, b int) int { |
| 27 | + return a / b |
| 28 | +} |
| 29 | + |
| 30 | +func PrintResult(Analyzed *formats.FileAnalyzed) { |
| 31 | + // lista delle funzioni passate al template |
| 32 | + funcMap := template.FuncMap{ |
| 33 | + "now": time.Now, |
| 34 | + "divide": divide, |
| 35 | + "PEprintArchitecture": pe.PrintArchitecture, |
| 36 | + "PEprintResource": pe.PrintResource, |
| 37 | + "PEprintSubsystem": pe.PrintSubsystem, |
| 38 | + "PEprintMajorOperatingVersion": pe.PrintMajorOperatingSystemVersion, |
| 39 | + "PEprintCharacteristics": pe.PrintCharacteristic, |
| 40 | + "ELFprintMachine": elf.PrintMachine, |
| 41 | + "ELFprintSectionType": elf.PrintSectionType, |
| 42 | + "ELFprintFileType": elf.PrintFileType, |
| 43 | + } |
| 44 | + |
| 45 | + if Analyzed.OutputFormat == "txt" { |
| 46 | + |
| 47 | + // carica un template .txt e popolalo con la struttura fileAnalyzed |
| 48 | + t := template.Must(template.New("output_template.txt").Funcs(funcMap).Parse(OutputTemplateTXT)) |
| 49 | + var processed bytes.Buffer |
| 50 | + |
| 51 | + err := t.Execute(&processed, Analyzed) |
| 52 | + if err != nil { |
| 53 | + fmt.Println("Non è stato possibile eseguire il template per questo motivo: " + err.Error()) |
| 54 | + return |
| 55 | + } |
| 56 | + outputPath := "./results/" + Analyzed.Name + "_analysis.txt" |
| 57 | + f, err := os.Create(outputPath) |
| 58 | + if err != nil { |
| 59 | + fmt.Println("Impossibile creare nuovo file.") |
| 60 | + return |
| 61 | + } |
| 62 | + w := bufio.NewWriter(f) |
| 63 | + _, err = w.WriteString(string(processed.Bytes())) |
| 64 | + if err != nil { |
| 65 | + fmt.Println("Impossibile scrivere il template sul file per il seguente errore: " + err.Error()) |
| 66 | + return |
| 67 | + } |
| 68 | + err = w.Flush() |
| 69 | + if err != nil { |
| 70 | + fmt.Println("Impossibile rimuovere il contenuto dell'IOBuffer.") |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + } else if Analyzed.OutputFormat == "html" { |
| 75 | + |
| 76 | + // carica un template html e popolalo con la struttura fileAnalyzed |
| 77 | + t := template.Must(template.New("output_template.html").Funcs(funcMap).Parse(OutputTemplateHTML)) |
| 78 | + |
| 79 | + var processed bytes.Buffer |
| 80 | + |
| 81 | + err := t.Execute(&processed, Analyzed) |
| 82 | + if err != nil { |
| 83 | + fmt.Println("Non è stato possibile eseguire il template per questo motivo: " + err.Error()) |
| 84 | + return |
| 85 | + } |
| 86 | + outputPath := "./results/" + Analyzed.Name + "_analysis.html" |
| 87 | + f, err := os.Create(outputPath) |
| 88 | + if err != nil { |
| 89 | + fmt.Println("Impossibile creare nuovo file.") |
| 90 | + return |
| 91 | + } |
| 92 | + w := bufio.NewWriter(f) |
| 93 | + _, err = w.WriteString(string(processed.Bytes())) |
| 94 | + if err != nil { |
| 95 | + fmt.Println("Impossibile scrivere il template sul file per il seguente errore: " + err.Error()) |
| 96 | + return |
| 97 | + } |
| 98 | + err = w.Flush() |
| 99 | + if err != nil { |
| 100 | + fmt.Println("Impossibile rimuovere il contenuto dell'IOBuffer.") |
| 101 | + return |
| 102 | + } |
| 103 | + } else { |
| 104 | + fmt.Println("Formato file non valido.") |
| 105 | + } |
| 106 | + |
| 107 | + fmt.Println("Microscope risultato. ") |
| 108 | + fmt.Println("Formato file : " + Analyzed.Format) |
| 109 | + fmt.Println("Architettura : " + Analyzed.Architecture) |
| 110 | + fmt.Println("Dimensione del file " + strconv.FormatInt(Analyzed.Size, 10)) |
| 111 | + fmt.Println("Punteggio " + strconv.FormatInt(int64(Analyzed.Score), 10)) |
| 112 | + |
| 113 | + if Analyzed.Score > Analyzed.Threshold { |
| 114 | + fmt.Println("!!!!!RANSOMWARE!!!!") |
| 115 | + } |
| 116 | + |
| 117 | + if Analyzed.Score > Analyzed.Threshold/2 && Analyzed.Score < Analyzed.Threshold { |
| 118 | + fmt.Println("È un possibile malware.") |
| 119 | + } |
| 120 | + |
| 121 | +} |
| 122 | + |
| 123 | +func ReadContentFile(file *os.File) []byte { |
| 124 | + // Molto importante impostare l'offset del file dall'inizio altrimenti c'è il rischio che la io.ReadAll |
| 125 | + // legga dal punto in cui l'offset è rimasto dalla funzione analysis |
| 126 | + newPosition, err := file.Seek(0, io.SeekStart) |
| 127 | + |
| 128 | + if err != nil { |
| 129 | + fmt.Println("Errore durante l'impostazione dell'offset " + err.Error()) |
| 130 | + return nil |
| 131 | + } |
| 132 | + |
| 133 | + if newPosition != 0 { |
| 134 | + fmt.Println("Errore durante l'impostazione dell'offset") |
| 135 | + return nil |
| 136 | + } |
| 137 | + |
| 138 | + content, err := io.ReadAll(file) |
| 139 | + if err != nil { |
| 140 | + fmt.Println("Impossibile leggere il contenuto del file per il seguente motivo " + err.Error()) |
| 141 | + return nil |
| 142 | + } |
| 143 | + return content |
| 144 | +} |
| 145 | + |
| 146 | +func StartAnalysis(file *os.File, Analyzed *formats.FileAnalyzed) { |
| 147 | + |
| 148 | + // Controlla i primi FILE_HEADER_PHASE_1 byte di file |
| 149 | + var header [FILE_HEADER_PHASE_1]byte |
| 150 | + // Ritorna il numero di byte letti |
| 151 | + n, err := io.ReadFull(file, header[:]) |
| 152 | + if err != nil || n != FILE_HEADER_PHASE_1 { |
| 153 | + fmt.Println("Impossibile leggere i primi 10 byte.") |
| 154 | + return |
| 155 | + } |
| 156 | + |
| 157 | + // Leggi contenuto del file |
| 158 | + Analyzed.Raw = ReadContentFile(file) |
| 159 | + h := sha256.New() |
| 160 | + h.Write(Analyzed.Raw) |
| 161 | + Analyzed.Hash = fmt.Sprintf("%x", h.Sum(nil)) |
| 162 | + |
| 163 | + // Se il file contiene un possibile elf header, allora.. |
| 164 | + if IsELFBinary(header) { |
| 165 | + Analyzed.Format = "ELF" |
| 166 | + // Procediamo con l'analisi dei segmenti ELF |
| 167 | + elf.ELFAnalysis(file, &Analyzed.ELFInterface) |
| 168 | + var machine uint16 |
| 169 | + switch headerFields := Analyzed.ELFInterface.Header.(type) { |
| 170 | + case elf.Header32: |
| 171 | + machine = headerFields.Machine |
| 172 | + case elf.Header64: |
| 173 | + machine = headerFields.Machine |
| 174 | + } |
| 175 | + |
| 176 | + Analyzed.Architecture = elf.PrintMachine(machine) |
| 177 | + } |
| 178 | + |
| 179 | + // Altrimenti controlla se è un possibile binario PE |
| 180 | + if isPEBinary(header) { |
| 181 | + Analyzed.Format = "PE" |
| 182 | + // Procediamo con l'analisi del file PE |
| 183 | + pe.Analysis(&Analyzed.PEInterface, Analyzed.Raw) |
| 184 | + Analyzed.Architecture = pe.PrintArchitecture(Analyzed.PEInterface.COFFHeader.Machine) |
| 185 | + } |
| 186 | + |
| 187 | + if Analyzed.Format == "PE" || Analyzed.Format == "ELF" { |
| 188 | + // Estrai le stringhe |
| 189 | + Analyzed.ExtractedStrings = ExtractStrings(file, 6, 256, true) |
| 190 | + |
| 191 | + // Applica le euristiche |
| 192 | + heuristics.Execute(Analyzed) |
| 193 | + |
| 194 | + // Stampa il risultato |
| 195 | + PrintResult(Analyzed) |
| 196 | + } else { |
| 197 | + fmt.Println("Questo tipo di file non è al momento supportato da MicroSCOPE.") |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +func IsELFBinary(content [FILE_HEADER_PHASE_1]byte) bool { |
| 202 | + // Controllo dei primi tre byte "ELF" |
| 203 | + if content[0] == 0x7f && content[1] == byte('E') && content[2] == byte('L') && content[3] == byte('F') { |
| 204 | + return true |
| 205 | + } |
| 206 | + |
| 207 | + return false |
| 208 | +} |
| 209 | + |
| 210 | +func isPEBinary(content [FILE_HEADER_PHASE_1]byte) bool { |
| 211 | + |
| 212 | + // TODO: Questa è una prima euristica molto veloce che consente subito di determinare se un file potrebbe essere un file PE oppure no |
| 213 | + // Rimangono da verificare tutti i casi limite |
| 214 | + // Potrebbe essere utile passare di nuovo il puntatore del file a questa funzione per cercare l'offset 0x3c che indica la struttura PE |
| 215 | + // e il successivo controllo sulla signature PE |
| 216 | + |
| 217 | + // Controlla lo stub per Microsoft MS-DOS (i primi due byte devono essere MZ dal nome del creatore del formato) |
| 218 | + if content[0] == byte('M') || content[1] == byte('Z') { |
| 219 | + return true |
| 220 | + } |
| 221 | + |
| 222 | + // Esistono anche binari che hanno la sigla "MZ" invertita |
| 223 | + |
| 224 | + if content[0] == byte('Z') || content[0] == byte('M') { |
| 225 | + return true |
| 226 | + } |
| 227 | + |
| 228 | + return false |
| 229 | +} |
0 commit comments