| 1 | package certificatetransparency |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha1" //nolint:gosec |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "hash" |
| 12 | "log" |
| 13 | "math/big" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/d-Rickyy-b/certstream-server-go/internal/models" |
| 19 | |
| 20 | ct "github.com/google/certificate-transparency-go" |
| 21 | "github.com/google/certificate-transparency-go/x509" |
| 22 | "github.com/google/certificate-transparency-go/x509/pkix" |
| 23 | ) |
| 24 | |
| 25 | // parseData converts a *ct.RawLogEntry struct into a certstream.Data struct by copying some values and calculating others. |
| 26 | func parseData(entry *ct.RawLogEntry, operatorName, logName, ctURL, logType string) (models.Data, error) { |
| 27 | var certLink string |
| 28 | // There is no direct link for tiled ct logs |
| 29 | if logType == models.SourceIsRFC6962 { |
| 30 | certLink = fmt.Sprintf("%s/ct/v1/get-entries?start=%d&end=%d", ctURL, entry.Index, entry.Index) |
| 31 | } |
| 32 | |
| 33 | // Create main data structure |
| 34 | data := models.Data{ |
| 35 | CertIndex: uint64(entry.Index), |
| 36 | CertLink: certLink, |
| 37 | Seen: float64(time.Now().UnixMilli()) / 1_000, |
| 38 | Source: models.Source{ |
| 39 | Name: logName, |
| 40 | URL: ctURL, |
| 41 | Timestamp: float64(entry.Leaf.TimestampedEntry.Timestamp) / 1_000, |
| 42 | Operator: operatorName, |
| 43 | NormalizedURL: normalizeCtlogURL(ctURL), |
| 44 | Type: logType, |
| 45 | }, |
| 46 | UpdateType: "X509LogEntry", |
| 47 | } |
| 48 | |
| 49 | // Convert RawLogEntry to ct.LogEntry |
| 50 | logEntry, conversionErr := entry.ToLogEntry() |
| 51 | if conversionErr != nil { |
| 52 | log.Println("Could not convert entry to LogEntry: ", conversionErr) |
| 53 | return models.Data{}, conversionErr |
| 54 | } |
| 55 | |
| 56 | var cert *x509.Certificate |
| 57 | var rawData []byte |
| 58 | var isPrecert bool |
| 59 | |
| 60 | switch { |
| 61 | case logEntry.X509Cert != nil: |
| 62 | cert = logEntry.X509Cert |
| 63 | rawData = logEntry.X509Cert.Raw |
| 64 | isPrecert = false |
| 65 | case logEntry.Precert != nil: |
| 66 | cert = logEntry.Precert.TBSCertificate |
| 67 | rawData = logEntry.Precert.Submitted.Data |
| 68 | isPrecert = true |
| 69 | default: |
| 70 | return models.Data{}, errors.New("could not parse entry: no certificate found") |
| 71 | } |
| 72 | |
| 73 | // Calculate certificate hash from the raw DER bytes of the certificate |
| 74 | data.LeafCert = leafCertFromX509cert(*cert) |
| 75 | |
| 76 | // recalculate hashes if the certificate is a precertificate |
| 77 | if isPrecert { |
| 78 | calculatedHash := calculateSHA1(rawData) |
| 79 | data.LeafCert.Fingerprint = calculatedHash |
| 80 | data.LeafCert.SHA1 = calculatedHash |
| 81 | data.LeafCert.SHA256 = calculateSHA256(rawData) |
| 82 | |
| 83 | // Since we use the TBSCertificate to parse the LeafCert, the PoisonByte indicator cannot be set by our parser. |
| 84 | // According to RFC 6962 Section 3.2 the `"tbs_certificate" is the DER-encoded TBSCertificate (see [RFC5280]) |
| 85 | // component of the Precertificate -- that is, without the signature and the poison extension.` |
| 86 | // Since the PoisonByte Extension `is to ensure that the Precertificate cannot be validated by a standard |
| 87 | // X.509v3 client`, we can safely set it for each precertificate. |
| 88 | data.LeafCert.Extensions.CTLPoisonByte = true |
| 89 | } |
| 90 | |
| 91 | certAsDER := base64.StdEncoding.EncodeToString(entry.Cert.Data) |
| 92 | data.LeafCert.AsDER = certAsDER |
| 93 | |
| 94 | var parseErr error |
| 95 | data.Chain, parseErr = parseCertificateChain(logEntry) |
| 96 | if parseErr != nil { |
| 97 | log.Println("Could not parse certificate chain: ", parseErr) |
| 98 | return models.Data{}, parseErr |
| 99 | } |
| 100 | |
| 101 | return data, nil |
| 102 | } |
| 103 | |
| 104 | // parseCertificateChain returns the certificate chain in form of a []LeafCert from the given *ct.LogEntry. |
| 105 | func parseCertificateChain(logEntry *ct.LogEntry) ([]models.LeafCert, error) { |
| 106 | chain := make([]models.LeafCert, len(logEntry.Chain)) |
| 107 | |
| 108 | for i, chainEntry := range logEntry.Chain { |
| 109 | myCert, parseErr := x509.ParseCertificate(chainEntry.Data) |
| 110 | if parseErr != nil || myCert == nil { |
| 111 | log.Println("Error parsing certificate: ", parseErr) |
| 112 | return nil, parseErr |
| 113 | } |
| 114 | |
| 115 | leafCert := leafCertFromX509cert(*myCert) |
| 116 | chain[i] = leafCert |
| 117 | } |
| 118 | |
| 119 | return chain, nil |
| 120 | } |
| 121 | |
| 122 | // leafCertFromX509cert converts a x509.Certificate to the custom LeafCert data structure. |
| 123 | func leafCertFromX509cert(cert x509.Certificate) models.LeafCert { |
| 124 | leafCert := models.LeafCert{ |
| 125 | AllDomains: cert.DNSNames, |
| 126 | Extensions: models.Extensions{}, |
| 127 | NotAfter: cert.NotAfter.Unix(), |
| 128 | NotBefore: cert.NotBefore.Unix(), |
| 129 | SerialNumber: formatSerialNumber(cert.SerialNumber), |
| 130 | SignatureAlgorithm: parseSignatureAlgorithm(cert.SignatureAlgorithm), |
| 131 | IsCA: cert.IsCA, |
| 132 | } |
| 133 | |
| 134 | // The zero value of DomainsEntry.Data is nil, but we want an empty array - especially for JSON marshaling later. |
| 135 | if leafCert.AllDomains == nil { |
| 136 | leafCert.AllDomains = []string{} |
| 137 | } |
| 138 | |
| 139 | leafCert.Subject = buildSubject(cert.Subject) |
| 140 | if *leafCert.Subject.CN != "" && !leafCert.IsCA { |
| 141 | domainAlreadyAdded := slices.Contains(leafCert.AllDomains, *leafCert.Subject.CN) |
| 142 | |
| 143 | if !domainAlreadyAdded { |
| 144 | leafCert.AllDomains = append(leafCert.AllDomains, *leafCert.Subject.CN) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | leafCert.Issuer = buildSubject(cert.Issuer) |
| 149 | |
| 150 | leafCert.AsDER = base64.StdEncoding.EncodeToString(cert.Raw) |
| 151 | leafCert.Fingerprint = calculateSHA1(cert.Raw) |
| 152 | leafCert.SHA1 = leafCert.Fingerprint |
| 153 | leafCert.SHA256 = calculateSHA256(cert.Raw) |
| 154 | |
| 155 | // TODO fix Extensions - check x509util.go |
| 156 | for _, extension := range cert.Extensions { |
| 157 | switch { |
| 158 | case extension.Id.Equal(x509.OIDExtensionAuthorityKeyId): |
| 159 | leafCert.Extensions.AuthorityKeyIdentifier = formatKeyID(cert.AuthorityKeyId) |
| 160 | case extension.Id.Equal(x509.OIDExtensionKeyUsage): |
| 161 | keyUsage := keyUsageToString(cert.KeyUsage) |
| 162 | leafCert.Extensions.KeyUsage = &keyUsage |
| 163 | case extension.Id.Equal(x509.OIDExtensionSubjectKeyId): |
| 164 | leafCert.Extensions.SubjectKeyIdentifier = formatKeyID(cert.SubjectKeyId) |
| 165 | case extension.Id.Equal(x509.OIDExtensionBasicConstraints): |
| 166 | isCA := strings.ToUpper(fmt.Sprintf("CA:%t", cert.IsCA)) |
| 167 | leafCert.Extensions.BasicConstraints = &isCA |
| 168 | case extension.Id.Equal(x509.OIDExtensionSubjectAltName): |
| 169 | var buf bytes.Buffer |
| 170 | for _, name := range cert.DNSNames { |
| 171 | commaAppend(&buf, "DNS:"+name) |
| 172 | } |
| 173 | |
| 174 | for _, email := range cert.EmailAddresses { |
| 175 | commaAppend(&buf, "email:"+email) |
| 176 | } |
| 177 | |
| 178 | for _, ip := range cert.IPAddresses { |
| 179 | commaAppend(&buf, "IP Address:"+ip.String()) |
| 180 | } |
| 181 | |
| 182 | subjectAltName := buf.String() |
| 183 | leafCert.Extensions.SubjectAltName = &subjectAltName |
| 184 | case extension.Id.Equal(x509.OIDExtensionAuthorityInfoAccess): |
| 185 | var buf bytes.Buffer |
| 186 | for _, issuer := range cert.IssuingCertificateURL { |
| 187 | commaAppend(&buf, "URI:"+issuer) |
| 188 | } |
| 189 | |
| 190 | for _, ocsp := range cert.OCSPServer { |
| 191 | commaAppend(&buf, "URI:"+ocsp) |
| 192 | } |
| 193 | |
| 194 | result := buf.String() |
| 195 | leafCert.Extensions.AuthorityInfoAccess = &result |
| 196 | case extension.Id.Equal(x509.OIDExtensionCTPoison): |
| 197 | leafCert.Extensions.CTLPoisonByte = true |
| 198 | case extension.Id.Equal(x509.OIDExtensionCertificatePolicies): |
| 199 | var result string |
| 200 | for _, policy := range cert.PolicyIdentifiers { |
| 201 | // The current way of joining the string leaves us with a trailing newline, |
| 202 | // but that's how the original certstream server does it too. |
| 203 | result += fmt.Sprintf("Policy: %s\n", policy) |
| 204 | } |
| 205 | leafCert.Extensions.CertificatePolicies = &result |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | return leafCert |
| 210 | } |
| 211 | |
| 212 | // buildSubject generates a Subject struct from the given pkix.Name. |
| 213 | func buildSubject(certSubject pkix.Name) models.Subject { |
| 214 | subject := models.Subject{ |
| 215 | C: parseName(certSubject.Country), |
| 216 | CN: &certSubject.CommonName, |
| 217 | L: parseName(certSubject.Locality), |
| 218 | O: parseName(certSubject.Organization), |
| 219 | OU: parseName(certSubject.OrganizationalUnit), |
| 220 | ST: parseName(certSubject.StreetAddress), |
| 221 | } |
| 222 | |
| 223 | var aggregated string |
| 224 | |
| 225 | if subject.C != nil { |
| 226 | aggregated += fmt.Sprintf("/C=%s", *subject.C) |
| 227 | } |
| 228 | |
| 229 | if subject.CN != nil { |
| 230 | aggregated += fmt.Sprintf("/CN=%s", *subject.CN) |
| 231 | } |
| 232 | |
| 233 | if subject.L != nil { |
| 234 | aggregated += fmt.Sprintf("/L=%s", *subject.L) |
| 235 | } |
| 236 | |
| 237 | if subject.O != nil { |
| 238 | aggregated += fmt.Sprintf("/O=%s", *subject.O) |
| 239 | } |
| 240 | |
| 241 | if subject.OU != nil { |
| 242 | aggregated += fmt.Sprintf("/OU=%s", *subject.OU) |
| 243 | } |
| 244 | |
| 245 | if subject.ST != nil { |
| 246 | aggregated += fmt.Sprintf("/ST=%s", *subject.ST) |
| 247 | } |
| 248 | |
| 249 | subject.Aggregated = &aggregated |
| 250 | |
| 251 | return subject |
| 252 | } |
| 253 | |
| 254 | // formatKeyID transforms the AuthorityKeyIdentifier to be more readable. |
| 255 | func formatKeyID(keyID []byte) *string { |
| 256 | tmp := hex.EncodeToString(keyID) |
| 257 | var digest string |
| 258 | |
| 259 | for i := 0; i < len(tmp); i += 2 { |
| 260 | digest = digest + ":" + tmp[i:i+2] |
| 261 | } |
| 262 | |
| 263 | digest = strings.TrimLeft(digest, ":") |
| 264 | digest = fmt.Sprintf("keyid:%s", digest) |
| 265 | |
| 266 | return &digest |
| 267 | } |
| 268 | |
| 269 | func formatSerialNumber(serialNumber *big.Int) string { |
| 270 | sn := fmt.Sprintf("%X", serialNumber) |
| 271 | if len(sn)%2 == 1 { |
| 272 | sn = "0" + sn |
| 273 | } |
| 274 | |
| 275 | return sn |
| 276 | } |
| 277 | |
| 278 | func parseName(input []string) *string { |
| 279 | if input == nil { |
| 280 | return nil |
| 281 | } |
| 282 | |
| 283 | var result string |
| 284 | for _, s := range input { |
| 285 | if len(result) > 0 { |
| 286 | result += "," |
| 287 | } |
| 288 | |
| 289 | result += s |
| 290 | } |
| 291 | |
| 292 | return &result |
| 293 | } |
| 294 | |
| 295 | // calculateHash takes a hash.Hash implementation and calculates the hash of the given data. |
| 296 | // It returns the hash in the format "XX:XX:XX:...". |
| 297 | func calculateHash(data []byte, certHasher hash.Hash) string { |
| 298 | _, e := certHasher.Write(data) |
| 299 | if e != nil { |
| 300 | log.Printf("Error while hashing cert: %s\n", e) |
| 301 | return "" |
| 302 | } |
| 303 | |
| 304 | certHash := fmt.Sprintf("%02x", certHasher.Sum(nil)) |
| 305 | certHash = strings.ToUpper(certHash) |
| 306 | |
| 307 | var result bytes.Buffer |
| 308 | for i := 0; i < len(certHash); i++ { |
| 309 | if i%2 == 0 && i > 0 { |
| 310 | result.WriteByte(':') |
| 311 | } |
| 312 | c := certHash[i] |
| 313 | result.WriteByte(c) |
| 314 | } |
| 315 | |
| 316 | return result.String() |
| 317 | } |
| 318 | |
| 319 | // calculateSHA1 calculates the SHA1 fingerprint of the given data. |
| 320 | func calculateSHA1(data []byte) string { |
| 321 | return calculateHash(data, sha1.New()) //nolint:gosec |
| 322 | } |
| 323 | |
| 324 | // calculateSHA256 calculates the SHA256 fingerprint of the given data. |
| 325 | func calculateSHA256(data []byte) string { |
| 326 | return calculateHash(data, sha256.New()) |
| 327 | } |
| 328 | |
| 329 | func parseSignatureAlgorithm(signatureAlgoritm x509.SignatureAlgorithm) string { |
| 330 | switch signatureAlgoritm { |
| 331 | case x509.MD2WithRSA: |
| 332 | return "md2, rsa" |
| 333 | case x509.MD5WithRSA: |
| 334 | return "md5, rsa" |
| 335 | case x509.SHA1WithRSA: |
| 336 | return "sha1, rsa" |
| 337 | case x509.SHA256WithRSA: |
| 338 | return "sha256, rsa" |
| 339 | case x509.SHA384WithRSA: |
| 340 | return "sha384, rsa" |
| 341 | case x509.SHA512WithRSA: |
| 342 | return "sha512, rsa" |
| 343 | case x509.SHA256WithRSAPSS: |
| 344 | return "sha256, rsa-pss" |
| 345 | case x509.SHA384WithRSAPSS: |
| 346 | return "sha384, rsa-pss" |
| 347 | case x509.SHA512WithRSAPSS: |
| 348 | return "sha512, rsa-pss" |
| 349 | case x509.DSAWithSHA1: |
| 350 | return "dsa, sha1" |
| 351 | case x509.DSAWithSHA256: |
| 352 | return "dsa, sha256" |
| 353 | case x509.ECDSAWithSHA1: |
| 354 | return "ecdsa, sha1" |
| 355 | case x509.ECDSAWithSHA256: |
| 356 | return "ecdsa, sha256" |
| 357 | case x509.ECDSAWithSHA384: |
| 358 | return "ecdsa, sha384" |
| 359 | case x509.ECDSAWithSHA512: |
| 360 | return "ecdsa, sha512" |
| 361 | case x509.PureEd25519: |
| 362 | return "ed25519" |
| 363 | case x509.UnknownSignatureAlgorithm: |
| 364 | fallthrough |
| 365 | default: |
| 366 | return "unknown" |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // commaAppend lets you append a string with a comma prepended to a buffer. |
| 371 | func commaAppend(buf *bytes.Buffer, s string) { |
| 372 | if buf.Len() > 0 { |
| 373 | buf.WriteString(", ") |
| 374 | } |
| 375 | |
| 376 | buf.WriteString(s) |
| 377 | } |
| 378 | |
| 379 | func keyUsageToString(k x509.KeyUsage) string { |
| 380 | var buf bytes.Buffer |
| 381 | if k&x509.KeyUsageDigitalSignature != 0 { |
| 382 | commaAppend(&buf, "Digital Signature") |
| 383 | } |
| 384 | |
| 385 | if k&x509.KeyUsageContentCommitment != 0 { |
| 386 | commaAppend(&buf, "Content Commitment") |
| 387 | } |
| 388 | |
| 389 | if k&x509.KeyUsageKeyEncipherment != 0 { |
| 390 | commaAppend(&buf, "Key Encipherment") |
| 391 | } |
| 392 | |
| 393 | if k&x509.KeyUsageDataEncipherment != 0 { |
| 394 | commaAppend(&buf, "Data Encipherment") |
| 395 | } |
| 396 | |
| 397 | if k&x509.KeyUsageKeyAgreement != 0 { |
| 398 | commaAppend(&buf, "Key Agreement") |
| 399 | } |
| 400 | |
| 401 | if k&x509.KeyUsageCertSign != 0 { |
| 402 | commaAppend(&buf, "Certificate Signing") |
| 403 | } |
| 404 | |
| 405 | if k&x509.KeyUsageCRLSign != 0 { |
| 406 | commaAppend(&buf, "CRL Signing") |
| 407 | } |
| 408 | |
| 409 | if k&x509.KeyUsageEncipherOnly != 0 { |
| 410 | commaAppend(&buf, "Encipher Only") |
| 411 | } |
| 412 | |
| 413 | if k&x509.KeyUsageDecipherOnly != 0 { |
| 414 | commaAppend(&buf, "Decipher Only") |
| 415 | } |
| 416 | |
| 417 | return buf.String() |
| 418 | } |
| 419 | |
| 420 | // ParseCertstreamEntry creates an Entry from a ct.RawLogEntry. |
| 421 | func ParseCertstreamEntry(rawEntry *ct.RawLogEntry, operatorName, logname, ctURL, logType string) (models.Entry, error) { |
| 422 | if rawEntry == nil { |
| 423 | return models.Entry{}, errors.New("certstream entry is nil") |
| 424 | } |
| 425 | |
| 426 | data, err := parseData(rawEntry, operatorName, logname, ctURL, logType) |
| 427 | if err != nil { |
| 428 | return models.Entry{}, err |
| 429 | } |
| 430 | |
| 431 | entry := models.Entry{ |
| 432 | Data: data, |
| 433 | MessageType: "certificate_update", |
| 434 | } |
| 435 | |
| 436 | return entry, nil |
| 437 | } |