Skip to content

Commit f510388

Browse files
First commit
0 parents  commit f510388

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+12255
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cert.pem
2+
key.pem
3+
os-proxy

README.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# os-proxy
2+
3+
Proxies calls to the OpenStack API with a self-signed certificate.
4+
5+
All URLs in the OpenStack catalog are rewritten to point to the proxy itself, which will properly reverse proxy them to the original URL.
6+
7+
**Required configuration:**
8+
* **-a**: URL of the remote OpenStack Keystone.
9+
* **-u**: URL the proxy will be reachable at.
10+
* **-f**: Flavor of the proxy Nova instance.
11+
* **-i**: Image of the proxy Nova instance.
12+
* **-u**: Name or ID of the public network where to create the floating IP.
13+
14+
**Example:**
15+
```
16+
./proxy.sh \
17+
-a 'https://keystone.example.com:13000' \
18+
-u 'https://proxy.example.com:5443' \
19+
-f 'm1.s2.medium' \
20+
-i 'rhcos' \
21+
-n 'external'
22+
```

generate_cert.go

+167
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// Copyright 2009 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Generate a self-signed X.509 certificate for a TLS server. Outputs to
6+
// 'cert.pem' and 'key.pem' and will overwrite existing files.
7+
8+
package main
9+
10+
import (
11+
"crypto/ecdsa"
12+
"crypto/ed25519"
13+
"crypto/elliptic"
14+
"crypto/rand"
15+
"crypto/rsa"
16+
"crypto/x509"
17+
"crypto/x509/pkix"
18+
"encoding/pem"
19+
"flag"
20+
"fmt"
21+
"math/big"
22+
"net"
23+
"os"
24+
"strings"
25+
"time"
26+
)
27+
28+
var (
29+
validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011")
30+
validFor = flag.Duration("duration", 5*time.Hour, "Duration that certificate is valid for")
31+
isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority")
32+
rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set")
33+
ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521")
34+
ed25519Key = flag.Bool("ed25519", false, "Generate an Ed25519 key")
35+
)
36+
37+
func publicKey(priv interface{}) interface{} {
38+
switch k := priv.(type) {
39+
case *rsa.PrivateKey:
40+
return &k.PublicKey
41+
case *ecdsa.PrivateKey:
42+
return &k.PublicKey
43+
case ed25519.PrivateKey:
44+
return k.Public().(ed25519.PublicKey)
45+
default:
46+
return nil
47+
}
48+
}
49+
50+
func generateCertificate(host string) error {
51+
if len(host) == 0 {
52+
return fmt.Errorf("Missing required --host parameter")
53+
}
54+
55+
var priv interface{}
56+
var err error
57+
switch *ecdsaCurve {
58+
case "":
59+
if *ed25519Key {
60+
_, priv, err = ed25519.GenerateKey(rand.Reader)
61+
} else {
62+
priv, err = rsa.GenerateKey(rand.Reader, *rsaBits)
63+
}
64+
case "P224":
65+
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
66+
case "P256":
67+
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
68+
case "P384":
69+
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
70+
case "P521":
71+
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
72+
default:
73+
return fmt.Errorf("Unrecognized elliptic curve: %q", *ecdsaCurve)
74+
}
75+
if err != nil {
76+
return fmt.Errorf("Failed to generate private key: %v", err)
77+
}
78+
79+
// ECDSA, ED25519 and RSA subject keys should have the DigitalSignature
80+
// KeyUsage bits set in the x509.Certificate template
81+
keyUsage := x509.KeyUsageDigitalSignature
82+
// Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In
83+
// the context of TLS this KeyUsage is particular to RSA key exchange and
84+
// authentication.
85+
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
86+
keyUsage |= x509.KeyUsageKeyEncipherment
87+
}
88+
89+
var notBefore time.Time
90+
if len(*validFrom) == 0 {
91+
notBefore = time.Now()
92+
} else {
93+
notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom)
94+
if err != nil {
95+
return fmt.Errorf("Failed to parse creation date: %v", err)
96+
}
97+
}
98+
99+
notAfter := notBefore.Add(*validFor)
100+
101+
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
102+
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
103+
if err != nil {
104+
return fmt.Errorf("Failed to generate serial number: %v", err)
105+
}
106+
107+
template := x509.Certificate{
108+
SerialNumber: serialNumber,
109+
Subject: pkix.Name{
110+
Organization: []string{"Red Hat Inc."},
111+
},
112+
NotBefore: notBefore,
113+
NotAfter: notAfter,
114+
115+
KeyUsage: keyUsage,
116+
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
117+
BasicConstraintsValid: true,
118+
}
119+
120+
hosts := strings.Split(host, ",")
121+
for _, h := range hosts {
122+
if ip := net.ParseIP(h); ip != nil {
123+
template.IPAddresses = append(template.IPAddresses, ip)
124+
} else {
125+
template.DNSNames = append(template.DNSNames, h)
126+
}
127+
}
128+
129+
if *isCA {
130+
template.IsCA = true
131+
template.KeyUsage |= x509.KeyUsageCertSign
132+
}
133+
134+
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
135+
if err != nil {
136+
return fmt.Errorf("Failed to create certificate: %v", err)
137+
}
138+
139+
certOut, err := os.Create("cert.pem")
140+
if err != nil {
141+
return fmt.Errorf("Failed to open cert.pem for writing: %v", err)
142+
}
143+
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
144+
return fmt.Errorf("Failed to write data to cert.pem: %v", err)
145+
}
146+
if err := certOut.Close(); err != nil {
147+
return fmt.Errorf("Error closing cert.pem: %v", err)
148+
}
149+
// log.Print("wrote cert.pem\n")
150+
151+
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
152+
if err != nil {
153+
return fmt.Errorf("Failed to open key.pem for writing: %v", err)
154+
}
155+
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
156+
if err != nil {
157+
return fmt.Errorf("Unable to marshal private key: %v", err)
158+
}
159+
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
160+
return fmt.Errorf("Failed to write data to key.pem: %v", err)
161+
}
162+
if err := keyOut.Close(); err != nil {
163+
return fmt.Errorf("Error closing key.pem: %v", err)
164+
}
165+
// log.Print("wrote key.pem\n")
166+
return nil
167+
}

go.mod

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module github.com/shiftstack/os-proxy
2+
3+
go 1.14
4+
5+
require (
6+
github.com/BurntSushi/xdg v0.0.0-20130804141135-e80d3446fea1
7+
github.com/gofrs/uuid v3.3.0+incompatible
8+
gopkg.in/yaml.v2 v2.3.0
9+
)

go.sum

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
github.com/BurntSushi/xdg v0.0.0-20130804141135-e80d3446fea1 h1:wm6oM17JoxfyN6IuKH8r3bU7Q2DjYRADJWgSHNfUXiY=
2+
github.com/BurntSushi/xdg v0.0.0-20130804141135-e80d3446fea1/go.mod h1:GTqQ4bvL7tTmcOwcZ3VVzwjWulHgjD2uamy76yuySp0=
3+
github.com/gofrs/uuid v3.3.0+incompatible h1:8K4tyRfvU1CYPgJsveYFQMhpFd/wXNM7iK6rR7UHz84=
4+
github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
5+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
6+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
7+
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
8+
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

main.go

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package main
2+
3+
import (
4+
"flag"
5+
"fmt"
6+
"io/ioutil"
7+
"log"
8+
"net/http"
9+
"net/url"
10+
"os"
11+
"strings"
12+
13+
"github.com/BurntSushi/xdg"
14+
"github.com/shiftstack/os-proxy/proxy"
15+
"gopkg.in/yaml.v2"
16+
)
17+
18+
const (
19+
defaultPort = "5443"
20+
)
21+
22+
var (
23+
proxyURL = flag.String("proxyurl", "", "The host this proxy will be reachable")
24+
osAuthURL = flag.String("authurl", "", "OpenStack entrypoint (OS_AUTH_URL)")
25+
)
26+
27+
func getAuthURL(cloudName string) (string, error) {
28+
cloudsPath, err := xdg.Paths{XDGSuffix: "openstack"}.ConfigFile("clouds.yaml")
29+
if err != nil {
30+
return "", err
31+
}
32+
33+
cloudsFile, err := os.Open(cloudsPath)
34+
if err != nil {
35+
return "", err
36+
}
37+
defer cloudsFile.Close()
38+
39+
var clouds struct {
40+
Clouds map[string]struct {
41+
Auth struct {
42+
URL string `yaml:"auth_url"`
43+
} `yaml:"auth"`
44+
} `yaml:"clouds"`
45+
}
46+
47+
cloudsContent, err := ioutil.ReadAll(cloudsFile)
48+
if err != nil {
49+
return "", err
50+
}
51+
52+
if err := yaml.Unmarshal(cloudsContent, &clouds); err != nil {
53+
return "", err
54+
55+
}
56+
57+
if _, ok := clouds.Clouds[cloudName]; !ok {
58+
return "", fmt.Errorf("cloud %q not found", cloudName)
59+
}
60+
61+
return clouds.Clouds[cloudName].Auth.URL, nil
62+
}
63+
64+
func main() {
65+
flag.Parse()
66+
67+
if *proxyURL == "" {
68+
log.Fatal("Missing required --proxyurl parameter")
69+
}
70+
71+
if *osAuthURL == "" {
72+
if osCloud := os.Getenv("OS_CLOUD"); osCloud != "" {
73+
log.Print("Missing --authurl parameter; parsing from clouds.yaml")
74+
var err error
75+
*osAuthURL, err = getAuthURL(osCloud)
76+
if err != nil {
77+
log.Fatalf("Error parsing auth_url from cloud %q: %v", osCloud, err)
78+
}
79+
} else {
80+
log.Fatal("Missing --authurl parameter. Set it or set the relative OS_CLOUD environment to enable parsing it from clouds.yaml.")
81+
}
82+
}
83+
84+
var proxyHost, proxyPort string
85+
{
86+
u, err := url.Parse(*proxyURL)
87+
if err != nil {
88+
log.Fatal(err)
89+
}
90+
proxyHost = u.Host
91+
proxyPort = u.Port()
92+
if proxyPort == "" {
93+
proxyPort = defaultPort
94+
}
95+
}
96+
97+
p, err := proxy.NewOpenstackProxy(*proxyURL, *osAuthURL)
98+
if err != nil {
99+
panic(err)
100+
}
101+
102+
log.Printf("Rewriting URLs to %q", proxyHost)
103+
log.Printf("Proxying %q", *osAuthURL)
104+
105+
{
106+
proxyDomain := strings.SplitN(proxyHost, ":", 2)[0]
107+
if err := generateCertificate(proxyDomain); err != nil {
108+
log.Fatal(err)
109+
}
110+
log.Printf("Certificate correctly generated for %q", proxyDomain)
111+
}
112+
113+
log.Printf("Starting the server on %q...", proxyPort)
114+
log.Fatal(
115+
http.ListenAndServeTLS(":"+proxyPort, "cert.pem", "key.pem", p),
116+
)
117+
}

0 commit comments

Comments
 (0)