-
Notifications
You must be signed in to change notification settings - Fork 3
/
lightning.go
283 lines (235 loc) · 7.28 KB
/
lightning.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
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
package lightning
import (
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"time"
utils "github.com/bolt-observer/go_common/utils"
"github.com/golang/glog"
"github.com/lightningnetwork/lnd/lncfg"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/macaroons"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/macaroon.v2"
)
func toPubKey(cert *x509.Certificate) string {
publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
publicKeyBlock := pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyDer,
}
return string(pem.EncodeToMemory(&publicKeyBlock))
}
func extractHostname(endpoint string) string {
proto := regexp.MustCompile("^[:a-zA-Z0-9_-]+//.*")
uri := endpoint
if !proto.MatchString(endpoint) {
uri = fmt.Sprintf("http://%s", endpoint)
}
u, err := url.Parse(uri)
if err != nil {
glog.Warningf("Could not parse endpoint: %s %v", endpoint, err)
return endpoint
}
return u.Hostname()
}
// CertificateVerification enum.
type CertificateVerification int
// Verification types.
const (
PublicCAorCert CertificateVerification = iota
PublicCA
AllowWhenPubKeySame
Strict
Insecure
SkipHostVerification
)
func getTLSConfig(certBytes []byte, hostname string, verification CertificateVerification) (*tls.Config, error) {
minVersion := uint16(tls.VersionTLS11)
switch verification {
case Insecure:
// Do not use this
return &tls.Config{InsecureSkipVerify: true, ServerName: "", VerifyConnection: func(cs tls.ConnectionState) error { return nil }}, nil
case SkipHostVerification:
// Do not use this
return &tls.Config{ServerName: "", VerifyConnection: func(cs tls.ConnectionState) error { return nil }, MinVersion: minVersion}, nil
case PublicCA:
// RootCAs could be nil too, but make it more explicit
cp, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
return &tls.Config{RootCAs: cp, MinVersion: minVersion}, nil
case PublicCAorCert:
cp, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
if !cp.AppendCertsFromPEM(certBytes) {
return nil, fmt.Errorf("append cert failed")
}
return &tls.Config{RootCAs: cp, MinVersion: minVersion}, nil
case Strict:
// Allow only the specified certificates (certificate-pinning)
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(certBytes) {
return nil, fmt.Errorf("append cert failed")
}
return &tls.Config{RootCAs: cp, MinVersion: minVersion}, nil
case AllowWhenPubKeySame:
// This is the idea that for Let's Encrypt for instance private key
// (and thus also public key stays the same) after renewal.
// It would be a great alternative to PUBLIC_CA_OR_CERT - allowing you to do
// some sort of certificate pinning despite allowing certificate renewals, however
// LND (https://github.com/lightningnetwork/lnd/pull/3011) actually recreates everything
// for autogenerated (self-signed) certificates
var (
blocks [][]byte
certPEMBlock []byte
)
certPEMBlock = certBytes
for {
var certDERBlock *pem.Block
certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
if certDERBlock == nil {
break
}
if certDERBlock.Type == "CERTIFICATE" {
blocks = append(blocks, certDERBlock.Bytes)
}
}
if len(blocks) == 0 {
return nil, fmt.Errorf("no certificate found")
}
cert, err := x509.ParseCertificate(blocks[0])
if err != nil {
return nil, fmt.Errorf("parse cert failed %v", err)
}
host := extractHostname(hostname)
err = cert.VerifyHostname(host)
if err != nil {
// TODO: this is to make it consistent with simple verification mode
glog.Warningf("verify hostname failed %v (%s)", err, host)
}
customVerify := func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
actualCert, err := x509.ParseCertificate(rawCerts[0])
if err != nil {
return err
}
err = actualCert.VerifyHostname(host)
if err != nil {
return err
}
// Verification method is based on public key from original certificate
if toPubKey(actualCert) != toPubKey(cert) {
return fmt.Errorf("pubkey is different")
}
return nil
}
return &tls.Config{
InsecureSkipVerify: true,
VerifyPeerCertificate: customVerify, MinVersion: minVersion,
}, nil
default:
return nil, fmt.Errorf("unsupported certificate verification mode: %v", verification)
}
}
// GetConnection - returns a GRPC client connection.
func GetConnection(getData GetDataCall) (*grpc.ClientConn, error) {
var (
creds credentials.TransportCredentials
macBytes []byte
)
if getData == nil {
return nil, fmt.Errorf("getData is nil")
}
data, err := getData()
if err != nil {
return nil, fmt.Errorf("data could not be fetched %v", err)
}
certBytes, err := utils.SafeBase64Decode(data.CertificateBase64)
if err != nil {
return nil, fmt.Errorf("base64 decoding failed %v", err)
}
verification := PublicCAorCert
if data.CertVerificationType != nil {
verification = CertificateVerification(*data.CertVerificationType)
}
tls, err := getTLSConfig(certBytes, data.Endpoint, verification)
if err != nil {
return nil, fmt.Errorf("getTlsConfig failed %v", err)
}
creds = credentials.NewTLS(tls)
opts := []grpc.DialOption{
grpc.WithTransportCredentials(creds),
}
macBytes, err = hex.DecodeString(data.MacaroonHex)
if err != nil {
return nil, fmt.Errorf("unable to decode macaroon %v", err)
}
mac := &macaroon.Macaroon{}
if err = mac.UnmarshalBinary(macBytes); err != nil {
return nil, fmt.Errorf("unable to unnmarshal macaroon %v", err)
}
cred, _ := macaroons.NewMacaroonCredential(mac)
opts = append(opts, grpc.WithPerRPCCredentials(cred))
genericDialer := lncfg.ClientAddressDialer(utils.GetEnvWithDefault("DEFAULT_GRPC_PORT", "10009"))
opts = append(opts, grpc.WithContextDialer(genericDialer))
maxMsg, err := strconv.Atoi(utils.GetEnvWithDefault("MAX_MSG_SIZE", "512"))
if err != nil {
return nil, fmt.Errorf("unable to decode maxMsg %s", err.Error())
}
maxSize := grpc.MaxCallRecvMsgSize(1024 * 1024 * maxMsg)
opts = append(opts, grpc.WithDefaultCallOptions(maxSize))
conn, err := grpc.Dial(data.Endpoint, opts...)
if err != nil {
return nil, fmt.Errorf("unable to dial %s", err.Error())
}
return conn, nil
}
// GetClient - get a lightning API client.
func GetClient(getData GetDataCall) (lnrpc.LightningClient, routerrpc.RouterClient, func(), error) {
conn, err := GetConnection(getData)
if err != nil {
return nil, nil, nil, err
}
cleanUp := func() {
conn.Close()
}
return lnrpc.NewLightningClient(conn), routerrpc.NewRouterClient(conn), cleanUp, nil
}
// IsMacaroonValid - verify whether macaroon is valid.
func IsMacaroonValid(mac *macaroon.Macaroon) (bool, time.Duration) {
minTime := time.Time{}
for _, v := range mac.Caveats() {
split := strings.Split(string(v.Id), " ")
if len(split) != 2 {
continue
}
if split[0] != "time-before" {
continue
}
time, err := time.Parse("2006-01-02T15:04:05.999999999Z", split[1])
if err != nil {
glog.Warningf("Could not parse time: %v", err)
continue
}
if minTime.IsZero() || time.Before(minTime) {
minTime = time
}
}
if minTime.IsZero() {
return true, time.Duration(1<<63 - 1)
}
now := time.Now().UTC().Add(5 * time.Second)
dur := minTime.Sub(now)
return int64(dur) > 0, dur
}