-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
307 lines (261 loc) · 8.01 KB
/
main.go
File metadata and controls
307 lines (261 loc) · 8.01 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package main
import (
"archive/zip"
"bytes"
"context"
"flag"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"github.com/gbm-dev/securecrt-export-bookmarks/internal/bookmark"
"github.com/gbm-dev/securecrt-export-bookmarks/internal/rdp"
"github.com/gbm-dev/securecrt-export-bookmarks/internal/securecrt"
)
const (
programName = "securecrt-export-bookmarks"
version = "1.3.0"
)
func main() {
// Parse flags
outputPath := flag.String("output", "", "Output file (.zip or .html)")
verbose := flag.Bool("verbose", false, "Enable verbose/debug output")
showVersion := flag.Bool("version", false, "Show version")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] <input.xml>\n\n", programName)
fmt.Fprintf(os.Stderr, "Converts SecureCRT session exports to browser bookmarks and RDP files.\n\n")
fmt.Fprintf(os.Stderr, "Options:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\nExamples:\n")
fmt.Fprintf(os.Stderr, " %s sessions.xml # Creates sessions.zip\n", programName)
fmt.Fprintf(os.Stderr, " %s sessions.xml -output export.zip # Creates export.zip\n", programName)
fmt.Fprintf(os.Stderr, " %s sessions.xml -output bookmarks.html # Creates HTML only\n", programName)
}
flag.Parse()
if *showVersion {
fmt.Printf("%s version %s\n", programName, version)
os.Exit(0)
}
// Get input file from positional args
args := flag.Args()
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "Error: input XML file required")
flag.Usage()
os.Exit(1)
}
inputFile := args[0]
// Setup logging
logger, logFileHandle := setupLogger(*verbose)
if logFileHandle != nil {
defer logFileHandle.Close()
}
// Determine output path
output := *outputPath
if output == "" {
// Default: same name as input but .zip
base := strings.TrimSuffix(filepath.Base(inputFile), filepath.Ext(inputFile))
output = base + ".zip"
} else {
// Auto-add extension if missing
ext := strings.ToLower(filepath.Ext(output))
if ext != ".zip" && ext != ".html" {
output = output + ".zip"
}
}
// Run the conversion
if err := run(inputFile, output, logger); err != nil {
logger.Error("conversion failed", "error", err)
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// setupLogger creates a logger that writes to console and errors.log
func setupLogger(verbose bool) (*slog.Logger, *os.File) {
consoleLevel := slog.LevelInfo
if verbose {
consoleLevel = slog.LevelDebug
}
// Open log file for errors
logFile, err := os.OpenFile("errors.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
// Continue without file logging
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: consoleLevel})), nil
}
consoleHandler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: consoleLevel})
fileHandler := slog.NewJSONHandler(logFile, &slog.HandlerOptions{Level: slog.LevelWarn})
return slog.New(&multiHandler{handlers: []slog.Handler{consoleHandler, fileHandler}}), logFile
}
// multiHandler writes to multiple slog handlers
type multiHandler struct {
handlers []slog.Handler
}
func (m *multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, h := range m.handlers {
if h.Enabled(ctx, level) {
return true
}
}
return false
}
func (m *multiHandler) Handle(ctx context.Context, r slog.Record) error {
for _, h := range m.handlers {
if h.Enabled(ctx, r.Level) {
if err := h.Handle(ctx, r); err != nil {
return err
}
}
}
return nil
}
func (m *multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handlers := make([]slog.Handler, len(m.handlers))
for i, h := range m.handlers {
handlers[i] = h.WithAttrs(attrs)
}
return &multiHandler{handlers: handlers}
}
func (m *multiHandler) WithGroup(name string) slog.Handler {
handlers := make([]slog.Handler, len(m.handlers))
for i, h := range m.handlers {
handlers[i] = h.WithGroup(name)
}
return &multiHandler{handlers: handlers}
}
// run performs the actual conversion
func run(inputPath, outputPath string, logger *slog.Logger) error {
logger.Info("starting conversion", "input", inputPath, "output", outputPath)
// Open input file
inputFile, err := os.Open(inputPath)
if err != nil {
return fmt.Errorf("failed to open input file: %w", err)
}
defer inputFile.Close()
// Parse SecureCRT XML
parser := securecrt.NewParser(logger)
sessions, err := parser.Parse(inputFile)
if err != nil {
return fmt.Errorf("failed to parse SecureCRT XML: %w", err)
}
// Count sessions by type
var webCount, rdpCount int
for _, s := range sessions {
if s.IsWeb() {
webCount++
}
if s.IsRDP() {
rdpCount++
}
}
logger.Info("found sessions", "web", webCount, "rdp", rdpCount)
fmt.Fprintf(os.Stderr, "Found %d web sessions, %d RDP sessions\n", webCount, rdpCount)
if webCount == 0 && rdpCount == 0 {
return fmt.Errorf("no HTTP/HTTPS/RDP sessions found in input file")
}
// Determine output type by extension
ext := strings.ToLower(filepath.Ext(outputPath))
if ext == ".html" {
return exportBookmarks(sessions, outputPath, logger)
}
return exportToZip(sessions, outputPath, logger)
}
// exportToZip exports all sessions to a single zip file
func exportToZip(sessions []securecrt.Session, zipPath string, logger *slog.Logger) error {
logger.Debug("creating zip file", "path", zipPath)
zipFile, err := os.Create(zipPath)
if err != nil {
return fmt.Errorf("failed to create zip file: %w", err)
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
var webCount, rdpCount int
// Export bookmarks to zip
var webSessions []securecrt.Session
for _, s := range sessions {
if s.IsWeb() {
webSessions = append(webSessions, s)
}
}
if len(webSessions) > 0 {
root := bookmark.NewFolder("SecureCRT Bookmarks")
for _, s := range webSessions {
b := bookmark.Bookmark{
Name: s.Name,
URL: s.URL(),
Path: strings.Join(s.Path, "/"),
}
root.AddBookmark(b, s.Path)
}
var buf bytes.Buffer
writer := bookmark.NewWriter(logger)
if err := writer.WriteHTML(&buf, root); err != nil {
return fmt.Errorf("failed to write HTML: %w", err)
}
w, err := zipWriter.Create("bookmarks.html")
if err != nil {
return fmt.Errorf("failed to create zip entry: %w", err)
}
if _, err := w.Write(buf.Bytes()); err != nil {
return fmt.Errorf("failed to write to zip: %w", err)
}
webCount = len(webSessions)
}
// Export RDP files to zip
for _, s := range sessions {
if !s.IsRDP() {
continue
}
pathParts := append([]string{"rdp"}, s.Path...)
pathParts = append(pathParts, s.SafeFilename()+".rdp")
zipEntryPath := strings.Join(pathParts, "/")
rdpContent := rdp.GenerateRDPContent(s.RDPAddress())
w, err := zipWriter.Create(zipEntryPath)
if err != nil {
return fmt.Errorf("failed to create zip entry: %w", err)
}
if _, err := w.Write(rdpContent); err != nil {
return fmt.Errorf("failed to write to zip: %w", err)
}
rdpCount++
}
fmt.Fprintf(os.Stderr, "Created %s (%d bookmarks, %d RDP files)\n", zipPath, webCount, rdpCount)
return nil
}
// exportBookmarks exports web sessions as browser bookmarks HTML
func exportBookmarks(sessions []securecrt.Session, outputPath string, logger *slog.Logger) error {
var webSessions []securecrt.Session
for _, s := range sessions {
if s.IsWeb() {
webSessions = append(webSessions, s)
}
}
if len(webSessions) == 0 {
return fmt.Errorf("no HTTP/HTTPS sessions found for bookmark export")
}
root := bookmark.NewFolder("SecureCRT Bookmarks")
for _, s := range webSessions {
b := bookmark.Bookmark{
Name: s.Name,
URL: s.URL(),
Path: strings.Join(s.Path, "/"),
}
root.AddBookmark(b, s.Path)
}
var out io.Writer = os.Stdout
if outputPath != "" {
outFile, err := os.Create(outputPath)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer outFile.Close()
out = outFile
}
writer := bookmark.NewWriter(logger)
if err := writer.WriteHTML(out, root); err != nil {
return fmt.Errorf("failed to write HTML: %w", err)
}
fmt.Fprintf(os.Stderr, "Bookmarks written to %s\n", outputPath)
return nil
}