-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
209 lines (181 loc) · 5.76 KB
/
Copy pathmain.go
File metadata and controls
209 lines (181 loc) · 5.76 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
package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/xml"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/gemalto/kmip-go"
"github.com/gemalto/kmip-go/kmip14"
ttlv2 "github.com/gemalto/kmip-go/ttlv"
)
func main() {
// Define flags
serverAddr := flag.String("server", "", "KMIP server address and port (e.g., localhost:5696) (required)")
keyFile := flag.String("key", "", "Client private key file in PEM format (required)")
certFile := flag.String("cert", "", "Client certificate file in PEM format (required)")
caFile := flag.String("cacert", "", "CA certificate file in PEM format for server verification (optional)")
inputFile := flag.String("in", "", "Input file for the KMIP request. If not specified, reads from stdin (optional)")
inputFormat := flag.String("input-format", "hex", "The format of the input request. Can be 'hex' or 'xml' (optional)")
outputFormat := flag.String("output-format", "hex", "The format for printing the response. Can be 'hex' or 'xml' (optional)")
help := flag.Bool("help", false, "Show help message (optional)")
flag.Usage = printCustomHelp
flag.Parse()
if *help || *serverAddr == "" || *keyFile == "" || *certFile == "" {
printCustomHelp()
return
}
// setup logger
log.SetFlags(0)
// Create client connection
conn, err := setupConnection(*serverAddr, *keyFile, *certFile, *caFile)
if err != nil {
log.Fatalf("Failed to establish connection: %v", err)
}
defer conn.Close()
// Read request
requestBytes, err := readRequest(*inputFile, *inputFormat)
if err != nil {
log.Fatalf("Failed to read request: %v", err)
}
// Send request and get response
responseTTLV, _, err := sendRequest(conn, requestBytes)
if err != nil {
log.Fatalf("Failed to send request: %v", err)
}
// Print response
if err := printResponse(responseTTLV, *outputFormat); err != nil {
log.Fatalf("Failed to print response: %v", err)
}
}
func setupConnection(serverAddr, keyFile, certFile, caFile string) (*tls.Conn, error) {
cer, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load client key pair: %w", err)
}
conf := &tls.Config{
Certificates: []tls.Certificate{cer},
MinVersion: tls.VersionTLS12,
}
if caFile != "" {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("failed to read CA certificate: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
conf.RootCAs = caCertPool
} else {
// for dev/testing only, if no CA is provided
conf.InsecureSkipVerify = true
}
conn, err := tls.Dial("tcp", serverAddr, conf)
if err != nil {
return nil, fmt.Errorf("failed to connect to server: %w", err)
}
return conn, nil
}
func readRequest(inputFile, inputFormat string) ([]byte, error) {
var reader io.Reader
if inputFile != "" {
f, err := os.Open(inputFile)
if err != nil {
return nil, fmt.Errorf("failed to open input file %q: %w", inputFile, err)
}
defer f.Close()
reader = f
} else {
fmt.Println("Enter KMIP request, then press Ctrl+D (or Ctrl+Z on Windows) to send:")
reader = os.Stdin
}
requestBytes, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("failed to read request: %w", err)
}
requestStr := strings.TrimSpace(string(requestBytes))
if inputFormat == "xml" {
hexRequest, err := xmlToHex(strings.NewReader(requestStr))
if err != nil {
return nil, fmt.Errorf("failed to convert XML request to hex: %w", err)
}
return hex.DecodeString(hexRequest)
}
return hex.DecodeString(requestStr)
}
func sendRequest(conn io.ReadWriter, request []byte) (ttlv2.TTLV, string, error) {
_, err := conn.Write(request)
if err != nil {
return nil, "Unable to write request", err
}
decoder := ttlv2.NewDecoder(bufio.NewReader(conn))
resp, err := decoder.NextTTLV()
if err != nil {
return nil, "Unable to decode response TTLV", err
}
var respMsg kmip.ResponseMessage
err = decoder.DecodeValue(&respMsg, resp)
if err != nil {
// still return the raw response even if decoding fails
return resp, "", fmt.Errorf("failed to decode response message: %w", err)
}
// // Check header result status
// if respMsg.ResponseHeader.ResultStatus != kmip14.ResultStatusSuccess {
// return resp, "", fmt.Errorf("KMIP batch operation failed: %s - %s",
// respMsg.ResponseHeader.ResultStatus.String(),
// respMsg.ResponseHeader.ResultMessage)
// }
// Check each batch item's result status
for i, item := range respMsg.BatchItem {
if item.ResultStatus != kmip14.ResultStatusSuccess {
return resp, "", fmt.Errorf("KMIP operation in batch item %d failed: %s - %s",
i,
item.ResultStatus.String(),
item.ResultMessage)
}
}
hexResponse := fmt.Sprintf("%x", []byte(resp))
return resp, hexResponse, nil
}
func printResponse(response ttlv2.TTLV, format string) error {
switch format {
case "xml":
s, err := xml.MarshalIndent(response, "", " ")
if err != nil {
return fmt.Errorf("error printing XML: %w", err)
}
fmt.Println(string(s))
case "hex":
fmt.Println(hex.EncodeToString(response))
default:
return fmt.Errorf("unknown output format: %s", format)
}
return nil
}
func xmlToHex(r io.Reader) (string, error) {
var raw ttlv2.TTLV
decoder := xml.NewDecoder(r)
if err := decoder.Decode(&raw); err != nil {
if err == io.EOF {
return "", nil
}
return "", err
}
return hex.EncodeToString(raw), nil
}
// Print custom help message
func printCustomHelp() {
fmt.Println("A command-line tool for sending KMIP requests to a server.")
fmt.Println("\nUsage:")
fmt.Println(" kmip-cli -server <ip:port> -key <keyfile> -cert <certfile> [options]")
fmt.Println("\nOptions:")
flag.PrintDefaults()
fmt.Println("\nExample:")
fmt.Println(` echo "42007801..." | kmip-cli -server localhost:5696 -key client.key -cert client.pem`)
}