aboutsummaryrefslogtreecommitdiff
path: root/cmd/stvanity/main.go
blob: 8917163b47410292bbbbb4807091a69932128264 (plain)
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
// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"errors"
	"flag"
	"fmt"
	"math/big"
	mr "math/rand"
	"os"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/syncthing/syncthing/lib/protocol"
)

type result struct {
	id       protocol.DeviceID
	priv     *ecdsa.PrivateKey
	derBytes []byte
}

func main() {
	flag.Parse()
	prefix := strings.ToUpper(strings.ReplaceAll(flag.Arg(0), "-", ""))
	if len(prefix) > 7 {
		prefix = prefix[:7] + "-" + prefix[7:]
	}

	found := make(chan result)
	stop := make(chan struct{})
	var count atomic.Int64

	// Print periodic progress reports.
	go printProgress(prefix, &count)

	// Run one certificate generator per CPU core.
	var wg sync.WaitGroup
	for i := 0; i < runtime.GOMAXPROCS(-1); i++ {
		wg.Add(1)
		go func() {
			generatePrefixed(prefix, &count, found, stop)
			wg.Done()
		}()
	}

	// Save the result, when one has been found.
	res := <-found
	close(stop)
	wg.Wait()

	fmt.Println("Found", res.id)
	saveCert(res.priv, res.derBytes)
	fmt.Println("Saved to cert.pem, key.pem")
}

// Try certificates until one is found that has the prefix at the start of
// the resulting device ID. Increments count atomically, sends the result to
// found, returns when stop is closed.
func generatePrefixed(prefix string, count *atomic.Int64, found chan<- result, stop <-chan struct{}) {
	notBefore := time.Now()
	notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)

	template := x509.Certificate{
		SerialNumber: new(big.Int).SetInt64(mr.Int63()),
		Subject: pkix.Name{
			CommonName: "syncthing",
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}

	priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for {
		select {
		case <-stop:
			return
		default:
		}

		derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		id := protocol.NewDeviceID(derBytes)
		count.Add(1)

		if strings.HasPrefix(id.String(), prefix) {
			select {
			case found <- result{id, priv, derBytes}:
			case <-stop:
			}
			return
		}
	}
}

func printProgress(prefix string, count *atomic.Int64) {
	started := time.Now()
	wantBits := 5 * len(prefix)
	if wantBits > 63 {
		fmt.Printf("Want %d bits for prefix %q, refusing to boil the ocean.\n", wantBits, prefix)
		os.Exit(1)
	}
	expectedIterations := float64(int(1) << uint(wantBits))
	fmt.Printf("Want %d bits for prefix %q, about %.2g certs to test (statistically speaking)\n", wantBits, prefix, expectedIterations)

	for range time.NewTicker(15 * time.Second).C {
		tried := count.Load()
		elapsed := time.Since(started)
		rate := float64(tried) / elapsed.Seconds()
		expected := timeStr(expectedIterations / rate)
		fmt.Printf("Trying %.0f certs/s, tested %d so far in %v, expect ~%s total time to complete\n", rate, tried, elapsed/time.Second*time.Second, expected)
	}
}

func saveCert(priv interface{}, derBytes []byte) {
	certOut, err := os.Create("cert.pem")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = certOut.Close()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	block, err := pemBlockForKey(priv)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	err = pem.Encode(keyOut, block)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = keyOut.Close()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func pemBlockForKey(priv interface{}) (*pem.Block, error) {
	switch k := priv.(type) {
	case *rsa.PrivateKey:
		return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
	case *ecdsa.PrivateKey:
		b, err := x509.MarshalECPrivateKey(k)
		if err != nil {
			return nil, err
		}
		return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
	default:
		return nil, errors.New("unknown key type")
	}
}

func timeStr(seconds float64) string {
	if seconds < 60 {
		return fmt.Sprintf("%.0fs", seconds)
	}
	if seconds < 3600 {
		return fmt.Sprintf("%.0fm", seconds/60)
	}
	if seconds < 86400 {
		return fmt.Sprintf("%.0fh", seconds/3600)
	}
	if seconds < 86400*365 {
		return fmt.Sprintf("%.0f days", seconds/3600)
	}
	return fmt.Sprintf("%.0f years", seconds/86400/365)
}