aboutsummaryrefslogtreecommitdiff
path: root/activitypub/pem.go
blob: 408be0cb8cb0abece0d82226ab084d5b67394a92 (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
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
package activitypub

import (
	crand "crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strings"

	"github.com/FChannel0/FChannel-Server/config"
	"github.com/FChannel0/FChannel-Server/util"
)

type Signature struct {
	KeyId     string
	Headers   []string
	Signature string
	Algorithm string
}

func CreatePem(actor Actor) error {
	privatekey, err := rsa.GenerateKey(crand.Reader, 2048)
	if err != nil {
		return util.MakeError(err, "CreatePem")
	}

	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privatekey)

	privateKeyBlock := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: privateKeyBytes,
	}

	privatePem, err := os.Create("./pem/board/" + actor.Name + "-private.pem")
	if err != nil {
		return util.MakeError(err, "CreatePem")
	}

	if err := pem.Encode(privatePem, privateKeyBlock); err != nil {
		return util.MakeError(err, "CreatePem")
	}

	publickey := &privatekey.PublicKey
	publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
	if err != nil {
		return util.MakeError(err, "CreatePem")
	}

	publicKeyBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyBytes,
	}

	publicPem, err := os.Create("./pem/board/" + actor.Name + "-public.pem")
	if err != nil {
		return util.MakeError(err, "CreatePem")
	}

	if err := pem.Encode(publicPem, publicKeyBlock); err != nil {
		return util.MakeError(err, "CreatePem")
	}

	_, err = os.Stat("./pem/board/" + actor.Name + "-public.pem")
	if os.IsNotExist(err) {
		return util.MakeError(err, "CreatePem")
	} else {
		return StorePemToDB(actor)
	}

	fmt.Println(`Created PEM keypair for the "` + actor.Name + `" board. Please keep in mind that
the PEM key is crucial in identifying yourself as the legitimate owner of the board,
so DO NOT LOSE IT!!! If you lose it, YOU WILL LOSE ACCESS TO YOUR BOARD!`)

	return nil
}

func CreatePublicKeyFromPrivate(actor *Actor, publicKeyPem string) error {
	publicFilename, err := GetActorPemFileFromDB(publicKeyPem)
	if err != nil {
		return util.MakeError(err, "CreatePublicKeyFromPrivate")
	}

	privateFilename := strings.ReplaceAll(publicFilename, "public.pem", "private.pem")
	if _, err := os.Stat(privateFilename); err == nil {
		// Not a lost cause
		priv, err := ioutil.ReadFile(privateFilename)
		if err != nil {
			return util.MakeError(err, "CreatePublicKeyFromPrivate")
		}

		block, _ := pem.Decode([]byte(priv))
		if block == nil || block.Type != "RSA PRIVATE KEY" {
			return errors.New("failed to decode PEM block containing public key")
		}

		key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return util.MakeError(err, "CreatePublicKeyFromPrivate")
		}

		publicKeyDer, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
		if err != nil {
			return util.MakeError(err, "CreatePublicKeyFromPrivate")
		}

		pubKeyBlock := pem.Block{
			Type:    "PUBLIC KEY",
			Headers: nil,
			Bytes:   publicKeyDer,
		}

		publicFileWriter, err := os.Create(publicFilename)
		if err != nil {
			return util.MakeError(err, "CreatePublicKeyFromPrivate")
		}

		if err := pem.Encode(publicFileWriter, &pubKeyBlock); err != nil {
			return util.MakeError(err, "CreatePublicKeyFromPrivate")
		}
	} else {
		fmt.Println(`\nUnable to locate private key from public key generation. Now,
this means that you are now missing the proof that you are the
owner of the "` + actor.Name + `" board. If you are the developer,
then your job is just as easy as generating a new keypair, but
if this board is live, then you'll also have to convince the other
owners to switch their public keys for you so that they will start
accepting your posts from your board from this site. Good luck ;)`)
		return errors.New("unable to locate private key")
	}
	return nil
}

func GetActorPemFromDB(pemID string) (PublicKeyPem, error) {
	var pem PublicKeyPem

	query := `select id, owner, file from publickeypem where id=$1`

	if err := config.DB.QueryRow(query, pemID).Scan(&pem.Id, &pem.Owner, &pem.PublicKeyPem); err != nil {
		return pem, util.MakeError(err, "GetActorPemFromDB")
	}

	dir, _ := os.Getwd()
	dir = dir + "" + strings.Replace(pem.PublicKeyPem, ".", "", 1)
	f, err := os.ReadFile(dir)
	if err != nil {
		return pem, util.MakeError(err, "GetActorPemFromDB")
	}

	pem.PublicKeyPem = strings.ReplaceAll(string(f), "\r\n", `\n`)

	return pem, nil
}

func GetActorPemFileFromDB(pemID string) (string, error) {
	query := `select file from publickeypem where id=$1`
	rows, err := config.DB.Query(query, pemID)
	if err != nil {
		return "", util.MakeError(err, "GetActorPemFileFromDB")
	}

	defer rows.Close()

	var file string
	rows.Next()
	rows.Scan(&file)

	return file, nil
}

func StorePemToDB(actor Actor) error {
	query := "select publicKeyPem from actor where id=$1"
	rows, err := config.DB.Query(query, actor.Id)
	if err != nil {
		return util.MakeError(err, "StorePemToDB")
	}

	defer rows.Close()

	var result string
	rows.Next()
	rows.Scan(&result)

	if result != "" {
		return errors.New("already storing public key for actor")
	}

	publicKeyPem := actor.Id + "#main-key"
	query = "update actor set publicKeyPem=$1 where id=$2"
	if _, err := config.DB.Exec(query, publicKeyPem, actor.Id); err != nil {
		return util.MakeError(err, "StorePemToDB")
	}

	file := "./pem/board/" + actor.Name + "-public.pem"
	query = "insert into publicKeyPem (id, owner, file) values($1, $2, $3)"
	_, err = config.DB.Exec(query, publicKeyPem, actor.Id, file)
	return util.MakeError(err, "StorePemToDB")
}

func ParseHeaderSignature(signature string) Signature {
	var nsig Signature

	keyId := regexp.MustCompile(`keyId=`)
	headers := regexp.MustCompile(`headers=`)
	sig := regexp.MustCompile(`signature=`)
	algo := regexp.MustCompile(`algorithm=`)

	signature = strings.ReplaceAll(signature, "\"", "")
	parts := strings.Split(signature, ",")

	for _, e := range parts {
		if keyId.MatchString(e) {
			nsig.KeyId = keyId.ReplaceAllString(e, "")
			continue
		}

		if headers.MatchString(e) {
			header := headers.ReplaceAllString(e, "")
			nsig.Headers = strings.Split(header, " ")
			continue
		}

		if sig.MatchString(e) {
			nsig.Signature = sig.ReplaceAllString(e, "")
			continue
		}

		if algo.MatchString(e) {
			nsig.Algorithm = algo.ReplaceAllString(e, "")
			continue
		}
	}

	return nsig
}