-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
249 lines (216 loc) · 7.08 KB
/
main.go
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//go:build windows
package main
import (
"errors"
"flag"
"golang.org/x/sys/windows"
"io"
"log"
"os"
"os/user"
"regexp"
"strings"
ntfs "www.velocidex.com/golang/go-ntfs/parser"
)
const (
NTFSAttrType_Data = 128
NTFSAttrID_Normal = 0
NTFSAttrID_ADS = 5
)
var (
inFile = flag.String("in", "", "input file")
outFile = flag.String("out", "", "output file")
ErrReturnedNil = errors.New("result returned nil reference")
ErrInvalidInput = errors.New("invalid input")
ErrDeviceInaccessible = errors.New("raw device is not accessible")
ErrPrivilegedAccountWanted = errors.New("require privileged token, please uac elevate")
SoftVersion string = ""
)
func CheckIfElevated() error {
u, err := user.Current()
if err != nil {
return err
}
log.Printf("Current running as: %s (%s) ", u.Name, u.Username)
if !windows.GetCurrentProcessToken().IsElevated() {
return ErrPrivilegedAccountWanted
}
log.Println("Current process already elevated to administrator, go ahead.")
return nil
}
func init() {
flag.Parse()
log.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)
}
func main() {
log.Println("go-rawcopy by kmahyyg (2022) - " + SoftVersion)
if err := CheckIfElevated(); err != nil {
panic(err)
}
npath := EnsureNTFSPath(*inFile)
// fullpath can leave with prefixing backslash, and this library require file path in slash (*nix format)
npathRela := strings.Join(npath[1:], "//")
err := TryRetrieveFile(npath[0], npathRela)
if err != nil {
log.Fatalln(err)
}
}
func EnsureNTFSPath(volFilePath string) []string {
return strings.Split(volFilePath, "\\")
}
// TryRetrieveFile create a NTFSContext for specific volume and find the corresponding file,
// after found the corresponding MFT Entry, read the (ATTR(Type=16)-$STANDARD_INFORMATION)
// to retrieve file metadata. Then use OpenStream to try extract file from (ATTR(Type=128)-$DATA),
// read data via raw device require pagedReader, each read operation must fit a cluster size,
// which by default, is 4096 bytes.
func TryRetrieveFile(volDiskLetter string, filePath string) error {
log.Println("Check Drive Letter.")
// check user input
var IsDiskLetter = regexp.MustCompile(`^[a-zA-Z]:$`).MatchString
if !IsDiskLetter(volDiskLetter) {
return ErrInvalidInput
}
log.Println("Open Raw Device Handle.")
// use UNC path to access raw device to bypass limitation of file lock
volFd, err := os.Open("\\\\.\\" + volDiskLetter)
if err != nil {
return ErrDeviceInaccessible
}
log.Println("Create PagedReader with page 4096, cache size 65536.")
// build a pagedReader for raw device to feed the NTFSContext initializor
ntfsPagedReader, err := ntfs.NewPagedReader(volFd, 0x1000, 0x10000)
if err != nil {
return err
}
log.Println("Create NTFSContext.")
// build NTFS context for root device
ntfsVolCtx, err := ntfs.GetNTFSContext(ntfsPagedReader, 0)
if err != nil {
return err
}
log.Println("Start to find root directory.")
// get volume root
ntfsVolRoot, err := ntfsVolCtx.GetMFT(5)
if err != nil {
return err
}
log.Println("Try to find file MFT_Entry Location.")
// ref: https://www.andreafortuna.org/2017/07/18/how-to-extract-data-and-timeline-from-master-file-table-on-ntfs-filesystem/
// a resident file might contain multiple VCN attributes and sub-streams, use OpenStream to retrieve data
// here, we found corresponding MFT Entry first.
corrFileEntry, err := ntfsVolRoot.Open(ntfsVolCtx, filePath)
if err != nil {
return err
}
log.Println("Metadata checking...")
// after found MFT_ENTRY, retrieve file metadata information located in corresponding data-stream attribute
corrFileInfo, err := corrFileEntry.StandardInformation(ntfsVolCtx)
if err != nil {
return err
}
fulPath, err := ntfs.GetFullPath(ntfsVolCtx, corrFileEntry)
if err != nil {
return err
}
err = PrintFileMetadata(corrFileInfo, volDiskLetter+"/"+fulPath)
if err != nil {
return err
}
log.Println("Retrieving data streaming from attr.")
// retrieve file data by read $DATA
// check handwritten.go inside NTFS library for more details
// ref: www.velocidex.com/golang/[email protected]/parser/handwritten.go:63
//
corrFileReader, err := ntfs.OpenStream(ntfsVolCtx, corrFileEntry, NTFSAttrType_Data, NTFSAttrID_Normal)
if err != nil {
return err
}
// If there is an ADS, try read. ADS signature is filename including ":"
// check it before you apply extractData function.
//
//corrFileADSReader, err := ntfs.OpenStream(ntfsVolCtx, corrFileEntry, NTFSAttrType_Data, NTFSAttrID_ADS)
//if err != nil {
// return err
//}
//
log.Println("Well, let's start copy now.")
err = CopyToDestinationFile(corrFileReader, *outFile)
if err != nil {
return err
}
log.Println("Copy done. Try to applying original file time.")
err = ApplyOriginalMetadata(volDiskLetter+"/"+fulPath, corrFileInfo, *outFile)
if err != nil {
return err
}
log.Println("Workload successfully finished.")
return nil
}
func ApplyOriginalMetadata(path string, info *ntfs.STANDARD_INFORMATION, dst string) error {
winFileHd, err := windows.Open(dst, windows.O_RDWR, 0)
defer windows.CloseHandle(winFileHd)
if err != nil {
return err
}
// golang official os package does not support Creation Time change due to non-POSIX complaint
// use windows specific API only.
cTime4Win := windows.NsecToFiletime(info.Create_time().UnixNano())
aTime4Win := windows.NsecToFiletime(info.File_accessed_time().UnixNano())
mTime4Win := windows.NsecToFiletime(info.File_altered_time().UnixNano())
err = windows.SetFileTime(winFileHd, &cTime4Win, &aTime4Win, &mTime4Win)
if err != nil {
return err
}
return nil
}
func PrintFileMetadata(stdinfo *ntfs.STANDARD_INFORMATION, fullpath string) error {
if stdinfo == nil {
return ErrReturnedNil
}
log.Printf(`
File Path: %s
File CTime: %s
File MTime: %s
MFT MTime: %s
File ATime: %s
Size: %d
`, fullpath, stdinfo.Create_time().String(), stdinfo.File_altered_time().String(),
stdinfo.Mft_altered_time().String(), stdinfo.File_accessed_time().String(), stdinfo.Size())
return nil
}
func CopyToDestinationFile(src ntfs.RangeReaderAt, dstfile string) error {
if src == nil {
return ErrReturnedNil
}
log.Println("Copying to " + dstfile)
dstFd, err := os.Create(dstfile)
defer dstFd.Sync()
defer dstFd.Close()
if err != nil {
return err
}
for idx, rn := range src.Ranges() {
log.Printf("\tSplit Run %03d : Range Start From %v - Length: %v , IsSparse %v \n", idx, rn.Offset, rn.Length, rn.IsSparse)
}
convertedReader := ConvertFromReaderAtToReader(src, 0)
wBytes, err := io.Copy(dstFd, convertedReader)
log.Printf("Written %d Bytes to Destination Done. \n", wBytes)
if err != nil {
return err
}
return nil
}
type readerFromRangedReaderAt struct {
r io.ReaderAt
offset int64
}
func ConvertFromReaderAtToReader(r io.ReaderAt, o int64) *readerFromRangedReaderAt {
return &readerFromRangedReaderAt{r: r, offset: o}
}
func (rd *readerFromRangedReaderAt) Read(b []byte) (n int, err error) {
n, err = rd.r.ReadAt(b, rd.offset)
if n > 0 {
rd.offset += int64(n)
}
return
}