idx
int64 0
522k
| project
stringclasses 631
values | commit_id
stringlengths 7
40
| project_url
stringclasses 630
values | commit_url
stringlengths 4
164
| commit_message
stringlengths 0
11.5k
| target
int64 0
1
| func
stringlengths 5
484k
| func_hash
float64 1,559,120,642,045,605,000,000,000B
340,279,892,905,069,500,000,000,000,000B
| file_name
stringlengths 4
45
| file_hash
float64 25,942,829,220,065,710,000,000,000B
340,272,304,251,680,200,000,000,000,000B
⌀ | cwe
sequencelengths 0
1
| cve
stringlengths 4
16
| cve_desc
stringlengths 0
2.3k
| nvd_url
stringlengths 37
49
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,563 | tcpdump | 4601c685e7fd19c3724d5e499c69b8d3ec49933e | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/4601c685e7fd19c3724d5e499c69b8d3ec49933e | CVE-2017-13019: Clean up PGM option processing.
Add #defines for option lengths or the lengths of the fixed-length part
of the option. Sometimes those #defines differ from what was there
before; what was there before was wrong, probably because the option
lengths given in RFC 3208 were sometimes wrong - some lengths included
the length of the option header, some lengths didn't.
Don't use "sizeof(uintXX_t)" for sizes in the packet, just use the
number of bytes directly.
For the options that include an IPv4 or IPv6 address, check the option
length against the length of what precedes the address before fetching
any of that data.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
| 197,306,675,310,624,960,000,000,000,000,000,000,000 | print-pgm.c | 172,166,990,047,650,200,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13019 | The PGM parser in tcpdump before 4.9.2 has a buffer over-read in print-pgm.c:pgm_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13019 |
2,564 | tcpdump | 26a6799b9ca80508c05cac7a9a3bef922991520b | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/26a6799b9ca80508c05cac7a9a3bef922991520b | CVE-2017-13018/PGM: Add a missing bounds check.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
| 252,571,658,770,575,170,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-13018 | The PGM parser in tcpdump before 4.9.2 has a buffer over-read in print-pgm.c:pgm_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13018 |
2,565 | tcpdump | 11b426ee05eb62ed103218526f1fa616851c43ce | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/11b426ee05eb62ed103218526f1fa616851c43ce | CVE-2017-13017/DHCPv6: Add a missing option length check.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | dhcp6opt_print(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
const struct dhcp6opt *dh6o;
const u_char *tp;
size_t i;
uint16_t opttype;
size_t optlen;
uint8_t auth_proto;
u_int authinfolen, authrealmlen;
int remain_len; /* Length of remaining options */
int label_len; /* Label length */
uint16_t subopt_code;
uint16_t subopt_len;
if (cp == ep)
return;
while (cp < ep) {
if (ep < cp + sizeof(*dh6o))
goto trunc;
dh6o = (const struct dhcp6opt *)cp;
ND_TCHECK(*dh6o);
optlen = EXTRACT_16BITS(&dh6o->dh6opt_len);
if (ep < cp + sizeof(*dh6o) + optlen)
goto trunc;
opttype = EXTRACT_16BITS(&dh6o->dh6opt_type);
ND_PRINT((ndo, " (%s", tok2str(dh6opt_str, "opt_%u", opttype)));
ND_TCHECK2(*(cp + sizeof(*dh6o)), optlen);
switch (opttype) {
case DH6OPT_CLIENTID:
case DH6OPT_SERVERID:
if (optlen < 2) {
/*(*/
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
switch (EXTRACT_16BITS(tp)) {
case 1:
if (optlen >= 2 + 6) {
ND_PRINT((ndo, " hwaddr/time type %u time %u ",
EXTRACT_16BITS(&tp[2]),
EXTRACT_32BITS(&tp[4])));
for (i = 8; i < optlen; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
case 2:
if (optlen >= 2 + 8) {
ND_PRINT((ndo, " vid "));
for (i = 2; i < 2 + 8; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
case 3:
if (optlen >= 2 + 2) {
ND_PRINT((ndo, " hwaddr type %u ",
EXTRACT_16BITS(&tp[2])));
for (i = 4; i < optlen; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
default:
ND_PRINT((ndo, " type %d)", EXTRACT_16BITS(tp)));
break;
}
break;
case DH6OPT_IA_ADDR:
if (optlen < 24) {
/*(*/
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0])));
ND_PRINT((ndo, " pltime:%u vltime:%u",
EXTRACT_32BITS(&tp[16]),
EXTRACT_32BITS(&tp[20])));
if (optlen > 24) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 24, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_ORO:
case DH6OPT_ERO:
if (optlen % 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
for (i = 0; i < optlen; i += 2) {
ND_PRINT((ndo, " %s",
tok2str(dh6opt_str, "opt_%u", EXTRACT_16BITS(&tp[i]))));
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_PREFERENCE:
if (optlen != 1) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", *tp));
break;
case DH6OPT_ELAPSED_TIME:
if (optlen != 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", EXTRACT_16BITS(tp)));
break;
case DH6OPT_RELAY_MSG:
ND_PRINT((ndo, " ("));
tp = (const u_char *)(dh6o + 1);
dhcp6_print(ndo, tp, optlen);
ND_PRINT((ndo, ")"));
break;
case DH6OPT_AUTH:
if (optlen < 11) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
auth_proto = *tp;
switch (auth_proto) {
case DH6OPT_AUTHPROTO_DELAYED:
ND_PRINT((ndo, " proto: delayed"));
break;
case DH6OPT_AUTHPROTO_RECONFIG:
ND_PRINT((ndo, " proto: reconfigure"));
break;
default:
ND_PRINT((ndo, " proto: %d", auth_proto));
break;
}
tp++;
switch (*tp) {
case DH6OPT_AUTHALG_HMACMD5:
/* XXX: may depend on the protocol */
ND_PRINT((ndo, ", alg: HMAC-MD5"));
break;
default:
ND_PRINT((ndo, ", alg: %d", *tp));
break;
}
tp++;
switch (*tp) {
case DH6OPT_AUTHRDM_MONOCOUNTER:
ND_PRINT((ndo, ", RDM: mono"));
break;
default:
ND_PRINT((ndo, ", RDM: %d", *tp));
break;
}
tp++;
ND_PRINT((ndo, ", RD:"));
for (i = 0; i < 4; i++, tp += 2)
ND_PRINT((ndo, " %04x", EXTRACT_16BITS(tp)));
/* protocol dependent part */
authinfolen = optlen - 11;
switch (auth_proto) {
case DH6OPT_AUTHPROTO_DELAYED:
if (authinfolen == 0)
break;
if (authinfolen < 20) {
ND_PRINT((ndo, " ??"));
break;
}
authrealmlen = authinfolen - 20;
if (authrealmlen > 0) {
ND_PRINT((ndo, ", realm: "));
}
for (i = 0; i < authrealmlen; i++, tp++)
ND_PRINT((ndo, "%02x", *tp));
ND_PRINT((ndo, ", key ID: %08x", EXTRACT_32BITS(tp)));
tp += 4;
ND_PRINT((ndo, ", HMAC-MD5:"));
for (i = 0; i < 4; i++, tp+= 4)
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp)));
break;
case DH6OPT_AUTHPROTO_RECONFIG:
if (authinfolen != 17) {
ND_PRINT((ndo, " ??"));
break;
}
switch (*tp++) {
case DH6OPT_AUTHRECONFIG_KEY:
ND_PRINT((ndo, " reconfig-key"));
break;
case DH6OPT_AUTHRECONFIG_HMACMD5:
ND_PRINT((ndo, " type: HMAC-MD5"));
break;
default:
ND_PRINT((ndo, " type: ??"));
break;
}
ND_PRINT((ndo, " value:"));
for (i = 0; i < 4; i++, tp+= 4)
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp)));
break;
default:
ND_PRINT((ndo, " ??"));
break;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_RAPID_COMMIT: /* nothing todo */
ND_PRINT((ndo, ")"));
break;
case DH6OPT_INTERFACE_ID:
case DH6OPT_SUBSCRIBER_ID:
/*
* Since we cannot predict the encoding, print hex dump
* at most 10 characters.
*/
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " "));
for (i = 0; i < optlen && i < 10; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_RECONF_MSG:
tp = (const u_char *)(dh6o + 1);
switch (*tp) {
case DH6_RENEW:
ND_PRINT((ndo, " for renew)"));
break;
case DH6_INFORM_REQ:
ND_PRINT((ndo, " for inf-req)"));
break;
default:
ND_PRINT((ndo, " for ?\?\?(%02x))", *tp));
break;
}
break;
case DH6OPT_RECONF_ACCEPT: /* nothing todo */
ND_PRINT((ndo, ")"));
break;
case DH6OPT_SIP_SERVER_A:
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS:
case DH6OPT_NIS_SERVERS:
case DH6OPT_NISP_SERVERS:
case DH6OPT_BCMCS_SERVER_A:
case DH6OPT_PANA_AGENT:
case DH6OPT_LQ_CLIENT_LINK:
if (optlen % 16) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
for (i = 0; i < optlen; i += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[i])));
ND_PRINT((ndo, ")"));
break;
case DH6OPT_SIP_SERVER_D:
case DH6OPT_DOMAIN_LIST:
tp = (const u_char *)(dh6o + 1);
while (tp < cp + sizeof(*dh6o) + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, cp + sizeof(*dh6o) + optlen)) == NULL)
goto trunc;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_STATUS_CODE:
if (optlen < 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s)", dhcp6stcode(EXTRACT_16BITS(&tp[0]))));
break;
case DH6OPT_IA_NA:
case DH6OPT_IA_PD:
if (optlen < 12) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " IAID:%u T1:%u T2:%u",
EXTRACT_32BITS(&tp[0]),
EXTRACT_32BITS(&tp[4]),
EXTRACT_32BITS(&tp[8])));
if (optlen > 12) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 12, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_IA_TA:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " IAID:%u", EXTRACT_32BITS(tp)));
if (optlen > 4) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 4, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_IA_PD_PREFIX:
if (optlen < 25) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s/%d", ip6addr_string(ndo, &tp[9]), tp[8]));
ND_PRINT((ndo, " pltime:%u vltime:%u",
EXTRACT_32BITS(&tp[0]),
EXTRACT_32BITS(&tp[4])));
if (optlen > 25) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 25, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_LIFETIME:
case DH6OPT_CLT_TIME:
if (optlen != 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", EXTRACT_32BITS(tp)));
break;
case DH6OPT_REMOTE_ID:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d ", EXTRACT_32BITS(tp)));
/*
* Print hex dump first 10 characters.
*/
for (i = 4; i < optlen && i < 14; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_LQ_QUERY:
if (optlen < 17) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
switch (*tp) {
case 1:
ND_PRINT((ndo, " by-address"));
break;
case 2:
ND_PRINT((ndo, " by-clientID"));
break;
default:
ND_PRINT((ndo, " type_%d", (int)*tp));
break;
}
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[1])));
if (optlen > 17) {
/* there are query-options */
dhcp6opt_print(ndo, tp + 17, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_CLIENT_DATA:
tp = (const u_char *)(dh6o + 1);
if (optlen > 0) {
/* there are encapsulated options */
dhcp6opt_print(ndo, tp, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_LQ_RELAY_DATA:
if (optlen < 16) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s ", ip6addr_string(ndo, &tp[0])));
/*
* Print hex dump first 10 characters.
*/
for (i = 16; i < optlen && i < 26; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_NTP_SERVER:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
while (tp < cp + sizeof(*dh6o) + optlen - 4) {
subopt_code = EXTRACT_16BITS(tp);
tp += 2;
subopt_len = EXTRACT_16BITS(tp);
tp += 2;
if (tp + subopt_len > cp + sizeof(*dh6o) + optlen)
goto trunc;
ND_PRINT((ndo, " subopt:%d", subopt_code));
switch (subopt_code) {
case DH6OPT_NTP_SUBOPTION_SRV_ADDR:
case DH6OPT_NTP_SUBOPTION_MC_ADDR:
if (subopt_len != 16) {
ND_PRINT((ndo, " ?"));
break;
}
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0])));
break;
case DH6OPT_NTP_SUBOPTION_SRV_FQDN:
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, tp, tp + subopt_len) == NULL)
goto trunc;
break;
default:
ND_PRINT((ndo, " ?"));
break;
}
tp += subopt_len;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_AFTR_NAME:
if (optlen < 3) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
remain_len = optlen;
ND_PRINT((ndo, " "));
/* Encoding is described in section 3.1 of RFC 1035 */
while (remain_len && *tp) {
label_len = *tp++;
if (label_len < remain_len - 1) {
(void)fn_printn(ndo, tp, label_len, NULL);
tp += label_len;
remain_len -= (label_len + 1);
if(*tp) ND_PRINT((ndo, "."));
} else {
ND_PRINT((ndo, " ?"));
break;
}
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_NEW_POSIX_TIMEZONE: /* all three of these options */
case DH6OPT_NEW_TZDB_TIMEZONE: /* are encoded similarly */
case DH6OPT_MUDURL: /* although GMT might not work */
if (optlen < 5) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, "="));
(void)fn_printn(ndo, tp, (u_int)optlen, NULL);
ND_PRINT((ndo, ")"));
break;
default:
ND_PRINT((ndo, ")"));
break;
}
cp += sizeof(*dh6o) + optlen;
}
return;
trunc:
ND_PRINT((ndo, "[|dhcp6ext]"));
}
| 33,155,060,227,659,363,000,000,000,000,000,000,000 | print-dhcp6.c | 290,574,228,139,358,000,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13017 | The DHCPv6 parser in tcpdump before 4.9.2 has a buffer over-read in print-dhcp6.c:dhcp6opt_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13017 |
2,566 | tcpdump | c177cb3800a9a68d79b2812f0ffcb9479abd6eb8 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/c177cb3800a9a68d79b2812f0ffcb9479abd6eb8 | CVE-2017-13016/ES-IS: Fix printing of addresses in RD PDUs.
Always print the SNPA, and flag it as such; only print it as a MAC
address if it's 6 bytes long.
Identify the NET as such.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add tests using the capture files supplied by the reporter(s), modified
so the capture files won't be rejected as an invalid capture. | 1 | esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
| 218,871,800,300,892,970,000,000,000,000,000,000,000 | print-isoclns.c | 84,623,992,754,612,400,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13016 | The ISO ES-IS parser in tcpdump before 4.9.2 has a buffer over-read in print-isoclns.c:esis_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13016 |
2,567 | tcpdump | 985122081165753c7442bd7824c473eb9ff56308 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/985122081165753c7442bd7824c473eb9ff56308 | CVE-2017-13015/EAP: Add more bounds checks.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | eap_print(netdissect_options *ndo,
register const u_char *cp,
u_int length)
{
const struct eap_frame_t *eap;
const u_char *tptr;
u_int tlen, type, subtype;
int count=0, len;
tptr = cp;
tlen = length;
eap = (const struct eap_frame_t *)cp;
ND_TCHECK(*eap);
/* in non-verbose mode just lets print the basic info */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
return;
}
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
tptr += sizeof(const struct eap_frame_t);
tlen -= sizeof(const struct eap_frame_t);
switch (eap->type) {
case EAP_FRAME_TYPE_PACKET:
type = *(tptr);
len = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, ", %s (%u), id %u, len %u",
tok2str(eap_code_values, "unknown", type),
type,
*(tptr+1),
len));
ND_TCHECK2(*tptr, len);
if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */
subtype = *(tptr+4);
ND_PRINT((ndo, "\n\t\t Type %s (%u)",
tok2str(eap_type_values, "unknown", *(tptr+4)),
*(tptr + 4)));
switch (subtype) {
case EAP_TYPE_IDENTITY:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Identity: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NOTIFICATION:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Notification: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NAK:
count = 5;
/*
* one or more octets indicating
* the desired authentication
* type one octet per type
*/
while (count < len) {
ND_PRINT((ndo, " %s (%u),",
tok2str(eap_type_values, "unknown", *(tptr+count)),
*(tptr + count)));
count++;
}
break;
case EAP_TYPE_TTLS:
ND_PRINT((ndo, " TTLSv%u",
EAP_TTLS_VERSION(*(tptr + 5)))); /* fall through */
case EAP_TYPE_TLS:
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
break;
case EAP_TYPE_FAST:
ND_PRINT((ndo, " FASTv%u",
EAP_TTLS_VERSION(*(tptr + 5))));
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_AKA:
case EAP_TYPE_SIM:
ND_PRINT((ndo, " subtype [%s] 0x%02x,",
tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)),
*(tptr + 5)));
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_MD5_CHALLENGE:
case EAP_TYPE_OTP:
case EAP_TYPE_GTC:
case EAP_TYPE_EXPANDED_TYPES:
case EAP_TYPE_EXPERIMENTAL:
default:
break;
}
}
break;
case EAP_FRAME_TYPE_LOGOFF:
case EAP_FRAME_TYPE_ENCAP_ASF_ALERT:
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|EAP]"));
}
| 331,600,373,994,432,900,000,000,000,000,000,000,000 | print-eap.c | 158,241,263,588,201,200,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13015 | The EAP parser in tcpdump before 4.9.2 has a buffer over-read in print-eap.c:eap_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13015 |
2,568 | tcpdump | cc356512f512e7fa423b3674db4bb31dbe40ffec | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/cc356512f512e7fa423b3674db4bb31dbe40ffec | CVE-2017-13014/White Board: Do more bounds checks.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
While we're at it, print a truncation error if the packets are
truncated, rather than just, in effect, ignoring the result of the
routines that print particular packet types. | 1 | wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (const struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (const struct pgstate *)io;
}
return ((const u_char *)ps <= ep? 0 : -1);
}
| 235,316,159,481,129,770,000,000,000,000,000,000,000 | print-wb.c | 99,433,165,740,537,440,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13014 | The White Board protocol parser in tcpdump before 4.9.2 has a buffer over-read in print-wb.c:wb_prep(), several functions. | https://nvd.nist.gov/vuln/detail/CVE-2017-13014 |
2,572 | tcpdump | 8509ef02eceb2bbb479cea10fe4a7ec6395f1a8b | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/8509ef02eceb2bbb479cea10fe4a7ec6395f1a8b | CVE-2017-13012/ICMP: Add a missing bounds check.
Check before fetching the length from the included packet's IPv4 header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
| 278,682,006,888,697,420,000,000,000,000,000,000,000 | print-icmp.c | 198,282,554,091,103,430,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13012 | The ICMP parser in tcpdump before 4.9.2 has a buffer over-read in print-icmp.c:icmp_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13012 |
2,573 | tcpdump | 9f0730bee3eb65d07b49fd468bc2f269173352fe | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/9f0730bee3eb65d07b49fd468bc2f269173352fe | CVE-2017-13011/Properly check for buffer overflow in bittok2str_internal().
Also, make the buffer bigger.
This fixes a buffer overflow discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture. | 1 | bittok2str_internal(register const struct tok *lp, register const char *fmt,
register u_int v, const char *sep)
{
static char buf[256]; /* our stringbuffer */
int buflen=0;
register u_int rotbit; /* this is the bit we rotate through all bitpositions */
register u_int tokval;
const char * sepstr = "";
while (lp != NULL && lp->s != NULL) {
tokval=lp->v; /* load our first value */
rotbit=1;
while (rotbit != 0) {
/*
* lets AND the rotating bit with our token value
* and see if we have got a match
*/
if (tokval == (v&rotbit)) {
/* ok we have found something */
buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s",
sepstr, lp->s);
sepstr = sep;
break;
}
rotbit=rotbit<<1; /* no match - lets shift and try again */
}
lp++;
}
if (buflen == 0)
/* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
(void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v);
return (buf);
}
| 5,329,624,229,776,096,000,000,000,000,000,000,000 | util-print.c | 159,998,677,330,794,870,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-13011 | Several protocol parsers in tcpdump before 4.9.2 could cause a buffer overflow in util-print.c:bittok2str_internal(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13011 |
2,575 | tcpdump | 877b66b398518d9501513e0860c9f3a8acc70892 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/877b66b398518d9501513e0860c9f3a8acc70892 | CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s). | 1 | l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
| 179,436,561,114,024,040,000,000,000,000,000,000,000 | print-beep.c | 226,808,505,814,341,870,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13010 | The BEEP parser in tcpdump before 4.9.2 has a buffer over-read in print-beep.c:l_strnstart(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13010 |
2,576 | tcpdump | db8c799f6dfc68765c9451fcbfca06e662f5bd5f | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/db8c799f6dfc68765c9451fcbfca06e662f5bd5f | CVE-2017-13009/IPv6 mobility: Add a bounds check.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
While we're at it:
Add a comment giving the RFC for IPv6 mobility headers.
Clean up some bounds checks to make it clearer what they're checking, by
matching the subsequent EXTRACT_ calls or memcpy.
For the binding update, if none of the flag bits are set, don't check
the individual flag bits. | 1 | mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 1);
if (bp[hlen] & 0xf0)
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 2);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(-1);
}
| 234,313,348,879,631,130,000,000,000,000,000,000,000 | print-mobility.c | 226,475,948,374,881,400,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13009 | The IPv6 mobility parser in tcpdump before 4.9.2 has a buffer over-read in print-mobility.c:mobility_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13009 |
2,577 | tcpdump | ca336198e8bebccc18502de27672fdbd6eb34856 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/ca336198e8bebccc18502de27672fdbd6eb34856 | CVE-2017-13007/PKTAP: Pass a properly updated struct pcap_pkthdr to the sub-dissector.
The sub-dissector expects that the length and captured length will
reflect the actual remaining data in the packet, not the raw amount
including the PKTAP header; pass an updated header, just as we do for
PPI.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s). | 1 | pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
hdrlen += printer(ndo, h, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
| 200,408,431,775,823,500,000,000,000,000,000,000,000 | print-pktap.c | 242,050,816,181,732,100,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13007 | The Apple PKTAP parser in tcpdump before 4.9.2 has a buffer over-read in print-pktap.c:pktap_if_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13007 |
2,591 | tcpdump | b45a9a167ca6a3ef2752ae9d48d56ac14b001bfd | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/b45a9a167ca6a3ef2752ae9d48d56ac14b001bfd | CVE-2017-13005/NFS: Add two bounds checks before fetching data
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s). | 1 | xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
| 55,998,268,801,158,500,000,000,000,000,000,000,000 | print-nfs.c | 325,597,668,871,085,650,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13005 | The NFS parser in tcpdump before 4.9.2 has a buffer over-read in print-nfs.c:xid_map_enter(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13005 |
2,592 | tcpdump | a25211918f2e790c67d859d20ccf8dbb81da1598 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/a25211918f2e790c67d859d20ccf8dbb81da1598 | CVE-2017-13003/Clean up the LMP dissector.
Do a lot more bounds and length checks.
Add a EXTRACT_8BITS() macro, for completeness, and so as not to confuse
people into thinking that, to fetch a 1-byte value from a packet, they
need to use EXTRACT_16BITS() to fetch a 2-byte value and then use
shifting and masking to extract the desired byte. Use that rather than
using EXTRACT_16BITS() to fetch a 2-byte value and then shifting and
masking to extract the desired byte.
Don't treat IPv4 addresses and unnumbered interface IDs the same; the
first should be printed as an IPv4 address but the latter should just be
printed as numbers. Handle IPv6 addresses in more object types while
we're at it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump;
int offset,subobj_type,subobj_len,total_subobj_len;
int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
if(lmp_obj_len % 4 || lmp_obj_len < 4)
return;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
case LMP_CTYPE_UNMD:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
total_subobj_len = lmp_obj_len - 16;
offset = 12;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_16BITS(obj_tptr+offset)>>8;
subobj_len = EXTRACT_16BITS(obj_tptr+offset)&0x00FF;
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+offset+2)>>8),
EXTRACT_16BITS(obj_tptr+offset+2)>>8));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF),
EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF));
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
offset = 0;
while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_16BITS(obj_tptr) & 0x00FF));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
link_type = EXTRACT_16BITS(obj_tptr)>>8;
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH) {
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_16BITS(obj_tptr) & 0x00FF),
EXTRACT_16BITS(obj_tptr) & 0x00FF));
}
if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET) {
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_16BITS(obj_tptr) & 0x00FF),
EXTRACT_16BITS(obj_tptr) & 0x00FF));
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2)>>8)));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2)>>8 & 0x00FF)));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+6) & 0x00FF)));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2) & 0x00FF)));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
| 207,905,445,019,781,550,000,000,000,000,000,000,000 | print-lmp.c | 285,803,191,062,121,900,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13003 | The LMP parser in tcpdump before 4.9.2 has a buffer over-read in print-lmp.c:lmp_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13003 |
2,593 | tcpdump | cbddb98484ea8ec1deece351abd56e063d775b38 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/cbddb98484ea8ec1deece351abd56e063d775b38 | CVE-2017-13002/AODV: Add some missing bounds checks.
In aodv_extension() do a bounds check on the extension header before we
look at it.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
While we're at it, add the RFC number, and check the validity of the
length for the Hello extension. | 1 | aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
| 90,330,714,944,185,620,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-13002 | The AODV parser in tcpdump before 4.9.2 has a buffer over-read in print-aodv.c:aodv_extension(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13002 |
2,594 | tcpdump | 7a923447fd49a069a0fd3b6c3547438ab5ee2123 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/7a923447fd49a069a0fd3b6c3547438ab5ee2123 | CVE-2017-13001/NFS: Don't copy more data than is in the file handle.
Also, put the buffer on the stack; no reason to make it static. (65
bytes isn't a lot.)
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s). | 1 | nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
static char temp[NFSX_V3FHMAX+1];
/* Make sure string is null-terminated */
strncpy(temp, sfsname, NFSX_V3FHMAX);
temp[sizeof(temp) - 1] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
| 339,616,538,929,006,480,000,000,000,000,000,000,000 | print-nfs.c | 100,575,108,855,301,120,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13001 | The NFS parser in tcpdump before 4.9.2 has a buffer over-read in print-nfs.c:nfs_printfh(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13001 |
2,595 | tcpdump | 8512734883227c11568bb35da1d48b9f8466f43f | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/8512734883227c11568bb35da1d48b9f8466f43f | CVE-2017-13000/IEEE 802.15.4: Fix bug introduced two fixes prior.
We've already advanced the pointer past the PAN ID, if present; it now
points to the address, so don't add 2 to it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| 226,608,746,932,513,560,000,000,000,000,000,000,000 | print-802_15_4.c | 288,503,972,323,871,480,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-13000 | The IEEE 802.15.4 parser in tcpdump before 4.9.2 has a buffer over-read in print-802_15_4.c:ieee802_15_4_if_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-13000 |
2,596 | tcpdump | 979dcefd7b259e9e233f77fe1c5312793bfd948f | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/979dcefd7b259e9e233f77fe1c5312793bfd948f | CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes.
Probably a copy-and-pasteo.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
| 265,874,135,992,817,670,000,000,000,000,000,000,000 | print-isoclns.c | 89,784,539,627,020,220,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12998 | The IS-IS parser in tcpdump before 4.9.2 has a buffer over-read in print-isoclns.c:isis_print_extd_ip_reach(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12998 |
2,597 | tcpdump | 6fca58f5f9c96749a575f52e20598ad43f5bdf30 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/6fca58f5f9c96749a575f52e20598ad43f5bdf30 | CVE-2017-12996/PIMv2: Make sure PIM TLVs have the right length.
We do bounds checks based on the TLV length, so if the TLV's length is
too short, and we don't check for that, we could end up fetching data
past the end of the TLV - including past the length of the captured data
in the packet.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s). | 1 | pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
| 185,739,536,581,136,030,000,000,000,000,000,000,000 | print-pim.c | 29,615,296,717,801,916,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12996 | The PIMv2 parser in tcpdump before 4.9.2 has a buffer over-read in print-pim.c:pimv2_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12996 |
2,598 | tcpdump | 3a76fd7c95fced2c2f8c8148a9055c3a542eff29 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/3a76fd7c95fced2c2f8c8148a9055c3a542eff29 | CVE-2017-12995/Check for DNS compression pointers that don't point backwards.
This is what BIND 9.11.0-P2 does; it not only detects pointers that
loop, as "point backwards" means "point before anything we've processed
so far, including what we're processing right now", so the pointer can't
point to itself (as that's what we're processing right now).
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
Also, add some infinite-pointer-loop captures.
More checks should be done. We might, for example, want to make sure
the upper 2 bits of the label length/pointer byte are 00 or 11, and that
if we encounter a pointer and jump backwards to what we think is a label
the label ends before the beginning of the last label we processed, to
make sure the pointer doesn't point backwards into the *middle* of a
label, and also make sure the entire name is <= 255 bytes long. | 1 | ns_nprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp)
{
register u_int i, l;
register const u_char *rp = NULL;
register int compress = 0;
int chars_processed;
int elt;
int data_size = ndo->ndo_snapend - bp;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
chars_processed = 1;
if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) {
compress = 0;
rp = cp + l;
}
if (i != 0)
while (i && cp < ndo->ndo_snapend) {
if ((i & INDIR_MASK) == INDIR_MASK) {
if (!compress) {
rp = cp + 1;
compress = 1;
}
if (!ND_TTEST2(*cp, 1))
return(NULL);
cp = bp + (((i << 8) | *cp) & 0x3fff);
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
/*
* If we've looked at every character in
* the message, this pointer will make
* us look at some character again,
* which means we're looping.
*/
if (chars_processed >= data_size) {
ND_PRINT((ndo, "<LOOP>"));
return (NULL);
}
continue;
}
if ((i & INDIR_MASK) == EDNS0_MASK) {
elt = (i & ~INDIR_MASK);
switch(elt) {
case EDNS0_ELT_BITLABEL:
if (blabel_print(ndo, cp) == NULL)
return (NULL);
break;
default:
/* unknown ELT */
ND_PRINT((ndo, "<ELT %d>", elt));
return(NULL);
}
} else {
if (fn_printn(ndo, cp, l, ndo->ndo_snapend))
return(NULL);
}
cp += l;
chars_processed += l;
ND_PRINT((ndo, "."));
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
if (!compress)
rp += l + 1;
}
else
ND_PRINT((ndo, "."));
return (rp);
}
| 307,707,688,388,100,500,000,000,000,000,000,000,000 | print-domain.c | 48,636,011,061,912,920,000,000,000,000,000,000,000 | [
"CWE-835"
] | CVE-2017-12995 | The DNS parser in tcpdump before 4.9.2 could enter an infinite loop due to a bug in print-domain.c:ns_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12995 |
2,599 | tcpdump | ffde45acf3348f8353fb4064a1b21683ee6b5ddf | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/ffde45acf3348f8353fb4064a1b21683ee6b5ddf | CVE-2017-12994/BGP: Move a test inside a loop.
The loop can be executed more than once (that's kinda the whole point of
a loop), so the check has to be made each time through the loop, not
just once before the loop is executed.
Do some additional length checks while we're at it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_TCHECK2(tptr[0], 5);
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
ND_TCHECK2(tptr[0], 3);
tlen = len;
while (tlen >= 3) {
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length - 3);
switch (type) {
case BGP_AIGP_TLV:
ND_TCHECK2(tptr[3], 8);
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr+3)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr+3,"\n\t ", length-3);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
| 110,718,534,424,942,980,000,000,000,000,000,000,000 | print-bgp.c | 81,233,617,923,263,840,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12994 | The BGP parser in tcpdump before 4.9.2 has a buffer over-read in print-bgp.c:bgp_attr_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12994 |
2,605 | tcpdump | b534e304568585707c4a92422aeca25cf908ff02 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/b534e304568585707c4a92422aeca25cf908ff02 | CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s). | 1 | juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
| 83,772,776,983,518,260,000,000,000,000,000,000,000 | print-juniper.c | 242,693,750,230,223,500,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12993 | The Juniper protocols parser in tcpdump before 4.9.2 has a buffer over-read in print-juniper.c, several functions. | https://nvd.nist.gov/vuln/detail/CVE-2017-12993 |
2,608 | tcpdump | e942fb84fbe3a73a98a00d2a279425872b5fb9d2 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/e942fb84fbe3a73a98a00d2a279425872b5fb9d2 | CVE-2017-12992/RIPng: Clean up bounds checking.
Do bounds checking as we access items.
Scan the list of netinfo6 entries based on the supplied packet length,
without taking the captured length into account; let the aforementioned
bounds checking handle that.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s). | 1 | ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length)
{
register const struct rip6 *rp = (const struct rip6 *)dat;
register const struct netinfo6 *ni;
register u_int amt;
register u_int i;
int j;
int trunc;
if (ndo->ndo_snapend < dat)
return;
amt = ndo->ndo_snapend - dat;
i = min(length, amt);
if (i < (sizeof(struct rip6) - sizeof(struct netinfo6)))
return;
i -= (sizeof(struct rip6) - sizeof(struct netinfo6));
switch (rp->rip6_cmd) {
case RIP6_REQUEST:
j = length / sizeof(*ni);
if (j == 1
&& rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6
&& IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) {
ND_PRINT((ndo, " ripng-req dump"));
break;
}
if (j * sizeof(*ni) != length - 4)
ND_PRINT((ndo, " ripng-req %d[%u]:", j, length));
else
ND_PRINT((ndo, " ripng-req %d:", j));
trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);
for (ni = rp->rip6_nets; i >= sizeof(*ni);
i -= sizeof(*ni), ++ni) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t"));
else
ND_PRINT((ndo, " "));
rip6_entry_print(ndo, ni, 0);
}
break;
case RIP6_RESPONSE:
j = length / sizeof(*ni);
if (j * sizeof(*ni) != length - 4)
ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length));
else
ND_PRINT((ndo, " ripng-resp %d:", j));
trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);
for (ni = rp->rip6_nets; i >= sizeof(*ni);
i -= sizeof(*ni), ++ni) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t"));
else
ND_PRINT((ndo, " "));
rip6_entry_print(ndo, ni, ni->rip6_metric);
}
if (trunc)
ND_PRINT((ndo, "[|ripng]"));
break;
default:
ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length));
break;
}
if (rp->rip6_vers != RIP6_VERSION)
ND_PRINT((ndo, " [vers %d]", rp->rip6_vers));
}
| 219,968,970,773,034,400,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-12992 | The RIPng parser in tcpdump before 4.9.2 has a buffer over-read in print-ripng.c:ripng_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12992 |
2,609 | tcpdump | 50a44b6b8e4f7c127440dbd4239cf571945cc1e7 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/50a44b6b8e4f7c127440dbd4239cf571945cc1e7 | CVE-2017-12991/BGP: Add missing bounds check.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_TCHECK2(tptr[0], 5);
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
ND_TCHECK2(tptr[0], 3);
tlen = len;
while (tlen >= 3) {
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length - 3);
switch (type) {
case BGP_AIGP_TLV:
ND_TCHECK2(tptr[3], 8);
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr+3)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr+3,"\n\t ", length-3);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
| 175,580,301,168,905,900,000,000,000,000,000,000,000 | print-bgp.c | 297,244,120,048,752,600,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12991 | The BGP parser in tcpdump before 4.9.2 has a buffer over-read in print-bgp.c:bgp_attr_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12991 |
2,613 | tcpdump | db24063b01cba8e9d4d88b7d8ac70c9000c104e4 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/db24063b01cba8e9d4d88b7d8ac70c9000c104e4 | CVE-2017-12989/RESP: Make sure resp_get_length() advances the pointer for invalid lengths.
Make sure that it always sends *endp before returning and that, for
invalid lengths where we don't like a character in the length string,
what it sets *endp to is past the character in question, so we don't
run the risk of infinitely looping (or doing something else random) if a
character in the length is invalid.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)
{
int result;
u_char c;
int saw_digit;
int neg;
int too_large;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
too_large = 0;
neg = 0;
if (*bp == '-') {
neg = 1;
bp++;
len--;
}
result = 0;
saw_digit = 0;
for (;;) {
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
c = *bp;
if (!(c >= '0' && c <= '9')) {
if (!saw_digit)
goto invalid;
break;
}
c -= '0';
if (result > (INT_MAX / 10)) {
/* This will overflow an int when we multiply it by 10. */
too_large = 1;
} else {
result *= 10;
if (result == INT_MAX && c > (INT_MAX % 10)) {
/* This will overflow an int when we add c */
too_large = 1;
} else
result += c;
}
bp++;
len--;
saw_digit = 1;
}
if (!saw_digit)
goto invalid;
/*
* OK, the next thing should be \r\n.
*/
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\r')
goto invalid;
bp++;
len--;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\n')
goto invalid;
bp++;
len--;
*endp = bp;
if (neg) {
/* -1 means "null", anything else is invalid */
if (too_large || result != 1)
return (-4);
result = -1;
}
return (too_large ? -3 : result);
trunc:
return (-2);
invalid:
return (-5);
}
| 167,321,145,110,708,070,000,000,000,000,000,000,000 | print-resp.c | 272,971,736,668,673,780,000,000,000,000,000,000,000 | [
"CWE-835"
] | CVE-2017-12989 | The RESP parser in tcpdump before 4.9.2 could enter an infinite loop due to a bug in print-resp.c:resp_get_length(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12989 |
2,614 | tcpdump | 8934a7d6307267d301182f19ed162563717e29e3 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/8934a7d6307267d301182f19ed162563717e29e3 | CVE-2017-12988/TELNET: Add a missing bounds check.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)
{
int i, x;
u_int c;
const u_char *osp, *p;
#define FETCH(c, sp, length) \
do { \
if (length < 1) \
goto pktend; \
ND_TCHECK(*sp); \
c = *sp++; \
length--; \
} while (0)
osp = sp;
FETCH(c, sp, length);
if (c != IAC)
goto pktend;
FETCH(c, sp, length);
if (c == IAC) { /* <IAC><IAC>! */
if (print)
ND_PRINT((ndo, "IAC IAC"));
goto done;
}
i = c - TELCMD_FIRST;
if (i < 0 || i > IAC - TELCMD_FIRST)
goto pktend;
switch (c) {
case DONT:
case DO:
case WONT:
case WILL:
case SB:
/* DONT/DO/WONT/WILL x */
FETCH(x, sp, length);
if (x >= 0 && x < NTELOPTS) {
if (print)
ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x]));
} else {
if (print)
ND_PRINT((ndo, "%s %#x", telcmds[i], x));
}
if (c != SB)
break;
/* IAC SB .... IAC SE */
p = sp;
while (length > (u_int)(p + 1 - sp)) {
ND_TCHECK2(*p, 2);
if (p[0] == IAC && p[1] == SE)
break;
p++;
}
if (*p != IAC)
goto pktend;
switch (x) {
case TELOPT_AUTHENTICATION:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype)));
break;
case TELOPT_ENCRYPT:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype)));
break;
default:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds)));
break;
}
while (p > sp) {
FETCH(x, sp, length);
if (print)
ND_PRINT((ndo, " %#x", x));
}
/* terminating IAC SE */
if (print)
ND_PRINT((ndo, " SE"));
sp += 2;
break;
default:
if (print)
ND_PRINT((ndo, "%s", telcmds[i]));
goto done;
}
done:
return sp - osp;
trunc:
ND_PRINT((ndo, "%s", tstr));
pktend:
return -1;
#undef FETCH
}
| 107,867,064,229,076,670,000,000,000,000,000,000,000 | print-telnet.c | 184,247,914,215,497,200,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12988 | The telnet parser in tcpdump before 4.9.2 has a buffer over-read in print-telnet.c:telnet_parse(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12988 |
2,615 | openjpeg | baf0c1ad4572daa89caa3b12985bdd93530f0dd7 | https://github.com/uclouvain/openjpeg | https://github.com/uclouvain/openjpeg/commit/baf0c1ad4572daa89caa3b12985bdd93530f0dd7 | bmp_read_info_header(): reject bmp files with biBitCount == 0 (#983) | 1 | static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header)
{
memset(header, 0, sizeof(*header));
/* INFO HEADER */
/* ------------- */
header->biSize = (OPJ_UINT32)getc(IN);
header->biSize |= (OPJ_UINT32)getc(IN) << 8;
header->biSize |= (OPJ_UINT32)getc(IN) << 16;
header->biSize |= (OPJ_UINT32)getc(IN) << 24;
switch (header->biSize) {
case 12U: /* BITMAPCOREHEADER */
case 40U: /* BITMAPINFOHEADER */
case 52U: /* BITMAPV2INFOHEADER */
case 56U: /* BITMAPV3INFOHEADER */
case 108U: /* BITMAPV4HEADER */
case 124U: /* BITMAPV5HEADER */
break;
default:
fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize);
return OPJ_FALSE;
}
header->biWidth = (OPJ_UINT32)getc(IN);
header->biWidth |= (OPJ_UINT32)getc(IN) << 8;
header->biWidth |= (OPJ_UINT32)getc(IN) << 16;
header->biWidth |= (OPJ_UINT32)getc(IN) << 24;
header->biHeight = (OPJ_UINT32)getc(IN);
header->biHeight |= (OPJ_UINT32)getc(IN) << 8;
header->biHeight |= (OPJ_UINT32)getc(IN) << 16;
header->biHeight |= (OPJ_UINT32)getc(IN) << 24;
header->biPlanes = (OPJ_UINT16)getc(IN);
header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
header->biBitCount = (OPJ_UINT16)getc(IN);
header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
if (header->biSize >= 40U) {
header->biCompression = (OPJ_UINT32)getc(IN);
header->biCompression |= (OPJ_UINT32)getc(IN) << 8;
header->biCompression |= (OPJ_UINT32)getc(IN) << 16;
header->biCompression |= (OPJ_UINT32)getc(IN) << 24;
header->biSizeImage = (OPJ_UINT32)getc(IN);
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24;
header->biXpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biYpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biClrUsed = (OPJ_UINT32)getc(IN);
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24;
header->biClrImportant = (OPJ_UINT32)getc(IN);
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 56U) {
header->biRedMask = (OPJ_UINT32)getc(IN);
header->biRedMask |= (OPJ_UINT32)getc(IN) << 8;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 16;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 24;
header->biGreenMask = (OPJ_UINT32)getc(IN);
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24;
header->biBlueMask = (OPJ_UINT32)getc(IN);
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24;
header->biAlphaMask = (OPJ_UINT32)getc(IN);
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 108U) {
header->biColorSpaceType = (OPJ_UINT32)getc(IN);
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24;
if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP),
IN) != sizeof(header->biColorSpaceEP)) {
fprintf(stderr, "Error, can't read BMP header\n");
return OPJ_FALSE;
}
header->biRedGamma = (OPJ_UINT32)getc(IN);
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biGreenGamma = (OPJ_UINT32)getc(IN);
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biBlueGamma = (OPJ_UINT32)getc(IN);
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 124U) {
header->biIntent = (OPJ_UINT32)getc(IN);
header->biIntent |= (OPJ_UINT32)getc(IN) << 8;
header->biIntent |= (OPJ_UINT32)getc(IN) << 16;
header->biIntent |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileData = (OPJ_UINT32)getc(IN);
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileSize = (OPJ_UINT32)getc(IN);
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24;
header->biReserved = (OPJ_UINT32)getc(IN);
header->biReserved |= (OPJ_UINT32)getc(IN) << 8;
header->biReserved |= (OPJ_UINT32)getc(IN) << 16;
header->biReserved |= (OPJ_UINT32)getc(IN) << 24;
}
return OPJ_TRUE;
}
| 165,457,040,852,911,900,000,000,000,000,000,000,000 | convertbmp.c | 197,193,176,428,127,820,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-12982 | The bmp_read_info_header function in bin/jp2/convertbmp.c in OpenJPEG 2.2.0 does not reject headers with a zero biBitCount, which allows remote attackers to cause a denial of service (memory allocation failure) in the opj_image_create function in lib/openjp2/image.c, related to the opj_aligned_alloc_n function in opj_malloc.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12982 |
2,619 | tcpdump | de981e6070d168b58ec1bb0713ded77ed4ad87f4 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/de981e6070d168b58ec1bb0713ded77ed4ad87f4 | CVE-2017-12901/EIGRP: Do more length checks.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct eigrp_common_header *eigrp_com_header;
const struct eigrp_tlv_header *eigrp_tlv_header;
const u_char *tptr,*tlv_tptr;
u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length;
uint8_t prefix[4];
union {
const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm;
const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version;
const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int;
const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext;
const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup;
const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int;
const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext;
} tlv_ptr;
tptr=pptr;
eigrp_com_header = (const struct eigrp_common_header *)pptr;
ND_TCHECK(*eigrp_com_header);
/*
* Sanity checking of the header.
*/
if (eigrp_com_header->version != EIGRP_VERSION) {
ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "EIGRP %s, length: %u",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=len-sizeof(struct eigrp_common_header);
/* FIXME print other header info */
ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u",
eigrp_com_header->version,
tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode),
eigrp_com_header->opcode,
EXTRACT_16BITS(&eigrp_com_header->checksum),
tok2str(eigrp_common_header_flag_values,
"none",
EXTRACT_32BITS(&eigrp_com_header->flags)),
EXTRACT_32BITS(&eigrp_com_header->seq),
EXTRACT_32BITS(&eigrp_com_header->ack),
EXTRACT_32BITS(&eigrp_com_header->asn),
tlen));
tptr+=sizeof(const struct eigrp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header));
eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr;
eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length);
eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type);
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) ||
eigrp_tlv_len > tlen) {
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen);
return;
}
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u",
tok2str(eigrp_tlv_values,
"Unknown",
eigrp_tlv_type),
eigrp_tlv_type,
eigrp_tlv_len));
tlv_tptr=tptr+sizeof(struct eigrp_tlv_header);
tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, eigrp_tlv_len);
switch(eigrp_tlv_type) {
case EIGRP_TLV_GENERAL_PARM:
tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u",
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime),
tlv_ptr.eigrp_tlv_general_parm->k1,
tlv_ptr.eigrp_tlv_general_parm->k2,
tlv_ptr.eigrp_tlv_general_parm->k3,
tlv_ptr.eigrp_tlv_general_parm->k4,
tlv_ptr.eigrp_tlv_general_parm->k5));
break;
case EIGRP_TLV_SW_VERSION:
tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u",
tlv_ptr.eigrp_tlv_sw_version->ios_major,
tlv_ptr.eigrp_tlv_sw_version->ios_minor,
tlv_ptr.eigrp_tlv_sw_version->eigrp_major,
tlv_ptr.eigrp_tlv_sw_version->eigrp_minor));
break;
case EIGRP_TLV_IP_INT:
tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_int->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu),
tlv_ptr.eigrp_tlv_ip_int->hopcount,
tlv_ptr.eigrp_tlv_ip_int->reliability,
tlv_ptr.eigrp_tlv_ip_int->load));
break;
case EIGRP_TLV_IP_EXT:
tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop)));
ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id),
tlv_ptr.eigrp_tlv_ip_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu),
tlv_ptr.eigrp_tlv_ip_ext->hopcount,
tlv_ptr.eigrp_tlv_ip_ext->reliability,
tlv_ptr.eigrp_tlv_ip_ext->load));
break;
case EIGRP_TLV_AT_CABLE_SETUP:
tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id)));
break;
case EIGRP_TLV_AT_INT:
tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2])));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu),
tlv_ptr.eigrp_tlv_at_int->hopcount,
tlv_ptr.eigrp_tlv_at_int->reliability,
tlv_ptr.eigrp_tlv_at_int->load));
break;
case EIGRP_TLV_AT_EXT:
tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2])));
ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id),
tlv_ptr.eigrp_tlv_at_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag),
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu),
tlv_ptr.eigrp_tlv_at_ext->hopcount,
tlv_ptr.eigrp_tlv_at_ext->reliability,
tlv_ptr.eigrp_tlv_at_ext->load));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case EIGRP_TLV_AUTH:
case EIGRP_TLV_SEQ:
case EIGRP_TLV_MCAST_SEQ:
case EIGRP_TLV_IPX_INT:
case EIGRP_TLV_IPX_EXT:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",
eigrp_tlv_len-sizeof(struct eigrp_tlv_header));
tptr+=eigrp_tlv_len;
tlen-=eigrp_tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
| 34,544,532,256,323,543,000,000,000,000,000,000,000 | print-eigrp.c | 168,041,154,571,529,710,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12901 | The EIGRP parser in tcpdump before 4.9.2 has a buffer over-read in print-eigrp.c:eigrp_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12901 |
2,620 | tcpdump | 19d25dd8781620cd41bf178a5e2e27fc1cf242d0 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/19d25dd8781620cd41bf178a5e2e27fc1cf242d0 | CVE-2017-12898/NFS: Fix bounds checking.
Fix the bounds checking for the NFSv3 WRITE procedure to check whether the
length of the opaque data being written is present in the captured data,
not just whether the byte count is present in the captured data.
furthest forward in the packet, not the item before it. (This also lets
us eliminate the check for the "stable" argument being present in the
captured data; rewrite the code to print that to make it a bit clearer.)
Check that the entire ar_stat field is present in the capture.
Note that parse_wcc_attr() is called after we've already checked whether
the wcc_data is present.
Check before fetching the "access" part of the NFSv3 ACCESS results.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Include a test for the "check before fetching the "access" part..." fix,
using the capture supplied by the reporter(s). | 1 | interp_reply(netdissect_options *ndo,
const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length)
{
register const uint32_t *dp;
register int v3;
int er;
v3 = (vers == NFS_VER3);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
dp = parserep(ndo, rp, length);
if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0)
return;
break;
case NFSPROC_SETATTR:
if (!(dp = parserep(ndo, rp, length)))
return;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0)
return;
}
break;
case NFSPROC_LOOKUP:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (er) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
} else {
if (!(dp = parsefh(ndo, dp, v3)))
break;
if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) &&
ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
}
if (dp)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_ACCESS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag)
ND_PRINT((ndo, " attr:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (!er)
ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0])));
return;
case NFSPROC_READLINK:
dp = parserep(ndo, rp, length);
if (dp != NULL && parselinkres(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_READ:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (EXTRACT_32BITS(&dp[1]))
ND_PRINT((ndo, " EOF"));
}
return;
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0)
return;
}
break;
case NFSPROC_WRITE:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (ndo->ndo_vflag > 1) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[1]))));
}
return;
}
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0)
return;
}
break;
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_SYMLINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_MKNOD:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
break;
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_RENAME:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " from:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " to:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
}
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_LINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " file POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " dir:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
return;
}
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parserddires(ndo, dp) != 0)
return;
}
break;
case NFSPROC_READDIRPLUS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
break;
case NFSPROC_FSSTAT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsestatfs(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_FSINFO:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsefsinfo(ndo, dp) != 0)
return;
break;
case NFSPROC_PATHCONF:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsepathconf(ndo, dp) != 0)
return;
break;
case NFSPROC_COMMIT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0)
return;
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
| 51,599,841,573,578,110,000,000,000,000,000,000,000 | print-nfs.c | 16,060,131,602,798,477,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12898 | The NFS parser in tcpdump before 4.9.2 has a buffer over-read in print-nfs.c:interp_reply(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12898 |
2,629 | tcpdump | 1dcd10aceabbc03bf571ea32b892c522cbe923de | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/1dcd10aceabbc03bf571ea32b892c522cbe923de | CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s). | 1 | isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
}
| 100,921,063,137,195,820,000,000,000,000,000,000,000 | print-isoclns.c | 145,104,362,232,404,600,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12897 | The ISO CLNS parser in tcpdump before 4.9.2 has a buffer over-read in print-isoclns.c:isoclns_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12897 |
2,639 | tcpdump | 2b62d1dda41590db29368ec7ba5f4faf3464765a | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/2b62d1dda41590db29368ec7ba5f4faf3464765a | CVE-2017-12895/ICMP: Check the availability of data before checksumming it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s). | 1 | icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
| 177,467,826,620,986,760,000,000,000,000,000,000,000 | print-icmp.c | 162,892,417,934,913,890,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12895 | The ICMP parser in tcpdump before 4.9.2 has a buffer over-read in print-icmp.c:icmp_print(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12895 |
2,642 | tcpdump | 730fc35968c5433b9e2a829779057f4f9495dc51 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/730fc35968c5433b9e2a829779057f4f9495dc51 | CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account.
Otherwise, if, in our search of the hash table, we come across a byte
string that's shorter than the string we're looking for, we'll search
past the end of the string in the hash table.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | lookup_bytestring(netdissect_options *ndo, register const u_char *bs,
const unsigned int nlen)
{
struct enamemem *tp;
register u_int i, j, k;
if (nlen >= 6) {
k = (bs[0] << 8) | bs[1];
j = (bs[2] << 8) | bs[3];
i = (bs[4] << 8) | bs[5];
} else if (nlen >= 4) {
k = (bs[0] << 8) | bs[1];
j = (bs[2] << 8) | bs[3];
i = 0;
} else
i = j = k = 0;
tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)];
while (tp->e_nxt)
if (tp->e_addr0 == i &&
tp->e_addr1 == j &&
tp->e_addr2 == k &&
memcmp((const char *)bs, (const char *)(tp->e_bs), nlen) == 0)
return tp;
else
tp = tp->e_nxt;
tp->e_addr0 = i;
tp->e_addr1 = j;
tp->e_addr2 = k;
tp->e_bs = (u_char *) calloc(1, nlen + 1);
if (tp->e_bs == NULL)
(*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");
memcpy(tp->e_bs, bs, nlen);
tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
if (tp->e_nxt == NULL)
(*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");
return tp;
}
| 266,681,780,576,494,960,000,000,000,000,000,000,000 | addrtoname.c | 317,193,900,967,712,260,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12894 | Several protocol parsers in tcpdump before 4.9.2 could cause a buffer over-read in addrtoname.c:lookup_bytestring(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12894 |
2,643 | tcpdump | 6f5ba2b651cd9d4b7fa8ee5c4f94460645877c45 | https://github.com/the-tcpdump-group/tcpdump | https://github.com/the-tcpdump-group/tcpdump/commit/6f5ba2b651cd9d4b7fa8ee5c4f94460645877c45 | CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len().
After we advance the pointer by the length value in the buffer, make
sure it points to something in the captured data.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s). | 1 | name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
}
| 215,949,633,633,690,600,000,000,000,000,000,000,000 | smbutil.c | 199,318,378,380,938,750,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-12893 | The SMB/CIFS parser in tcpdump before 4.9.2 has a buffer over-read in smbutil.c:name_len(). | https://nvd.nist.gov/vuln/detail/CVE-2017-12893 |
2,644 | ImageMagick | 04178de2247e353fc095846784b9a10fefdbf890 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890 | https://github.com/ImageMagick/ImageMagick/issues/662 | 1 | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
quantum_info=(QuantumInfo *) NULL;
clone_info=(ImageInfo *) NULL;
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
{
MATLAB_KO:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if (MATLAB_HDR.DataType!=miMATRIX)
{
clone_info=DestroyImageInfo(clone_info);
continue; /* skip another objects. */
}
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default:
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if (image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
else
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
return (image);
}
| 8,018,273,083,591,260,000,000,000,000,000,000,000 | None | null | [
"CWE-416"
] | CVE-2017-12877 | Use-after-free vulnerability in the DestroyImage function in image.c in ImageMagick before 7.0.6-6 allows remote attackers to cause a denial of service via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-12877 |
2,646 | ImageMagick | 3d5ac8c20846871f1eb3068b65f93da7cd33bfd0 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/3d5ac8c20846871f1eb3068b65f93da7cd33bfd0 | None | 1 | static MagickBooleanType WriteCALSImage(const ImageInfo *image_info,
Image *image)
{
char
header[MaxTextExtent];
Image
*group4_image;
ImageInfo
*write_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
density,
length,
orient_x,
orient_y;
ssize_t
count;
unsigned char
*group4;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Create standard CALS header.
*/
count=WriteCALSRecord(image,"srcdocid: NONE");
(void) count;
count=WriteCALSRecord(image,"dstdocid: NONE");
count=WriteCALSRecord(image,"txtfilid: NONE");
count=WriteCALSRecord(image,"figid: NONE");
count=WriteCALSRecord(image,"srcgph: NONE");
count=WriteCALSRecord(image,"doccls: NONE");
count=WriteCALSRecord(image,"rtype: 1");
orient_x=0;
orient_y=0;
switch (image->orientation)
{
case TopRightOrientation:
{
orient_x=180;
orient_y=270;
break;
}
case BottomRightOrientation:
{
orient_x=180;
orient_y=90;
break;
}
case BottomLeftOrientation:
{
orient_y=90;
break;
}
case LeftTopOrientation:
{
orient_x=270;
break;
}
case RightTopOrientation:
{
orient_x=270;
orient_y=180;
break;
}
case RightBottomOrientation:
{
orient_x=90;
orient_y=180;
break;
}
case LeftBottomOrientation:
{
orient_x=90;
break;
}
default:
{
orient_y=270;
break;
}
}
(void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld",
(long) orient_x,(long) orient_y);
count=WriteCALSRecord(image,header);
(void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu",
(unsigned long) image->columns,(unsigned long) image->rows);
count=WriteCALSRecord(image,header);
density=200;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
(void) ParseGeometry(image_info->density,&geometry_info);
density=(size_t) floor(geometry_info.rho+0.5);
}
(void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu",
(unsigned long) density);
count=WriteCALSRecord(image,header);
count=WriteCALSRecord(image,"notes: NONE");
(void) ResetMagickMemory(header,' ',128);
for (i=0; i < 5; i++)
(void) WriteBlob(image,128,(unsigned char *) header);
/*
Write CALS pixels.
*/
write_info=CloneImageInfo(image_info);
(void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent);
(void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent);
group4_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (group4_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,
&image->exception);
group4_image=DestroyImage(group4_image);
if (group4 == (unsigned char *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
write_info=DestroyImageInfo(write_info);
if (WriteBlob(image,length,group4) != (ssize_t) length)
status=MagickFalse;
group4=(unsigned char *) RelinquishMagickMemory(group4);
(void) CloseBlob(image);
return(status);
}
| 223,208,806,303,774,400,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12669 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WriteCALSImage in coders/cals.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12669 |
2,648 | ImageMagick | 560e6e512961008938aa1d1b9aab06347b1c8f9b | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/560e6e512961008938aa1d1b9aab06347b1c8f9b | None | 1 | static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
offset,
*page_table,
scene;
MemoryInfo
*pixel_info;
PCXInfo
pcx_info;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
length;
ssize_t
y;
unsigned char
*pcx_colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
page_table=(MagickOffsetType *) NULL;
if ((LocaleCompare(image_info->magick,"DCX") == 0) ||
((GetNextImageInList(image) != (Image *) NULL) &&
(image_info->adjoin != MagickFalse)))
{
/*
Write the DCX page table.
*/
(void) WriteBlobLSBLong(image,0x3ADE68B1L);
page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
sizeof(*page_table));
if (page_table == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (scene=0; scene < 1024; scene++)
(void) WriteBlobLSBLong(image,0x00000000L);
}
scene=0;
do
{
if (page_table != (MagickOffsetType *) NULL)
page_table[scene]=TellBlob(image);
/*
Initialize PCX raster file header.
*/
pcx_info.identifier=0x0a;
pcx_info.version=5;
pcx_info.encoding=image_info->compression == NoCompression ? 0 : 1;
pcx_info.bits_per_pixel=8;
if ((image->storage_class == PseudoClass) &&
(SetImageMonochrome(image,&image->exception) != MagickFalse))
pcx_info.bits_per_pixel=1;
pcx_info.left=0;
pcx_info.top=0;
pcx_info.right=(unsigned short) (image->columns-1);
pcx_info.bottom=(unsigned short) (image->rows-1);
switch (image->units)
{
case UndefinedResolution:
case PixelsPerInchResolution:
default:
{
pcx_info.horizontal_resolution=(unsigned short) image->x_resolution;
pcx_info.vertical_resolution=(unsigned short) image->y_resolution;
break;
}
case PixelsPerCentimeterResolution:
{
pcx_info.horizontal_resolution=(unsigned short)
(2.54*image->x_resolution+0.5);
pcx_info.vertical_resolution=(unsigned short)
(2.54*image->y_resolution+0.5);
break;
}
}
pcx_info.reserved=0;
pcx_info.planes=1;
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
pcx_info.planes=3;
if (image->matte != MagickFalse)
pcx_info.planes++;
}
pcx_info.bytes_per_line=(unsigned short) (((size_t) image->columns*
pcx_info.bits_per_pixel+7)/8);
pcx_info.palette_info=1;
pcx_info.colormap_signature=0x0c;
/*
Write PCX header.
*/
(void) WriteBlobByte(image,pcx_info.identifier);
(void) WriteBlobByte(image,pcx_info.version);
(void) WriteBlobByte(image,pcx_info.encoding);
(void) WriteBlobByte(image,pcx_info.bits_per_pixel);
(void) WriteBlobLSBShort(image,pcx_info.left);
(void) WriteBlobLSBShort(image,pcx_info.top);
(void) WriteBlobLSBShort(image,pcx_info.right);
(void) WriteBlobLSBShort(image,pcx_info.bottom);
(void) WriteBlobLSBShort(image,pcx_info.horizontal_resolution);
(void) WriteBlobLSBShort(image,pcx_info.vertical_resolution);
/*
Dump colormap to file.
*/
pcx_colormap=(unsigned char *) AcquireQuantumMemory(256UL,
3*sizeof(*pcx_colormap));
if (pcx_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(pcx_colormap,0,3*256*sizeof(*pcx_colormap));
q=pcx_colormap;
if ((image->storage_class == PseudoClass) && (image->colors <= 256))
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=ScaleQuantumToChar(image->colormap[i].red);
*q++=ScaleQuantumToChar(image->colormap[i].green);
*q++=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,3*16,(const unsigned char *) pcx_colormap);
(void) WriteBlobByte(image,pcx_info.reserved);
(void) WriteBlobByte(image,pcx_info.planes);
(void) WriteBlobLSBShort(image,pcx_info.bytes_per_line);
(void) WriteBlobLSBShort(image,pcx_info.palette_info);
for (i=0; i < 58; i++)
(void) WriteBlobByte(image,'\0');
length=(size_t) pcx_info.bytes_per_line;
pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
q=pixels;
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
/*
Convert DirectClass image to PCX raster pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels;
for (i=0; i < pcx_info.planes; i++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
switch ((int) i)
{
case 0:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
p++;
}
break;
}
case 1:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelGreen(p));
p++;
}
break;
}
case 2:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
p++;
}
break;
}
case 3:
default:
{
for (x=(ssize_t) pcx_info.bytes_per_line; x != 0; x--)
{
*q++=ScaleQuantumToChar((Quantum)
(GetPixelAlpha(p)));
p++;
}
break;
}
}
}
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
if (pcx_info.bits_per_pixel > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a PCX monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
bit=0;
byte=0;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (GetPixelLuma(image,p) >= (QuantumRange/2.0))
byte|=0x01;
bit++;
if (bit == 8)
{
*q++=byte;
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
*q++=byte << (8-bit);
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
(void) WriteBlobByte(image,pcx_info.colormap_signature);
(void) WriteBlob(image,3*256,pcx_colormap);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);
if (page_table == (MagickOffsetType *) NULL)
break;
if (scene >= 1023)
break;
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
if (page_table != (MagickOffsetType *) NULL)
{
/*
Write the DCX page table.
*/
page_table[scene+1]=0;
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowWriterException(CorruptImageError,"ImproperImageHeader");
(void) WriteBlobLSBLong(image,0x3ADE68B1L);
for (i=0; i <= (ssize_t) scene; i++)
(void) WriteBlobLSBLong(image,(unsigned int) page_table[i]);
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
}
if (status == MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(&image->exception,GetMagickModule(),
FileOpenError,"UnableToWriteFile","`%s': %s",image->filename,message);
message=DestroyString(message);
}
(void) CloseBlob(image);
return(MagickTrue);
}
| 185,312,616,346,228,350,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12668 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WritePCXImage in coders/pcx.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12668 |
2,649 | ImageMagick | 8985ed08f01d465ee65ab5a106186b3868b6f601 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/8985ed08f01d465ee65ab5a106186b3868b6f601 | None | 1 | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
| 208,847,878,789,259,360,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12667 | ImageMagick 7.0.6-1 has a memory leak vulnerability in ReadMATImage in coders\mat.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12667 |
2,650 | ImageMagick | 859084b4fd966ac007965c3d85caabccd8aee9b4 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/859084b4fd966ac007965c3d85caabccd8aee9b4 | None | 1 | static MagickBooleanType WritePICTImage(const ImageInfo *image_info,
Image *image)
{
#define MaxCount 128
#define PictCropRegionOp 0x01
#define PictEndOfPictureOp 0xff
#define PictJPEGOp 0x8200
#define PictInfoOp 0x0C00
#define PictInfoSize 512
#define PictPixmapOp 0x9A
#define PictPICTOp 0x98
#define PictVersion 0x11
const StringInfo
*profile;
double
x_resolution,
y_resolution;
MagickBooleanType
status;
MagickOffsetType
offset;
PICTPixmap
pixmap;
PICTRectangle
bounds,
crop_rectangle,
destination_rectangle,
frame_rectangle,
size_rectangle,
source_rectangle;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
bytes_per_line,
count,
row_bytes,
storage_class;
ssize_t
y;
unsigned char
*buffer,
*packed_scanline,
*scanline;
unsigned short
base_address,
transfer_mode;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Initialize image info.
*/
size_rectangle.top=0;
size_rectangle.left=0;
size_rectangle.bottom=(short) image->rows;
size_rectangle.right=(short) image->columns;
frame_rectangle=size_rectangle;
crop_rectangle=size_rectangle;
source_rectangle=size_rectangle;
destination_rectangle=size_rectangle;
base_address=0xff;
row_bytes=image->columns;
bounds.top=0;
bounds.left=0;
bounds.bottom=(short) image->rows;
bounds.right=(short) image->columns;
pixmap.version=0;
pixmap.pack_type=0;
pixmap.pack_size=0;
pixmap.pixel_type=0;
pixmap.bits_per_pixel=8;
pixmap.component_count=1;
pixmap.component_size=8;
pixmap.plane_bytes=0;
pixmap.table=0;
pixmap.reserved=0;
transfer_mode=0;
x_resolution=image->x_resolution != 0.0 ? image->x_resolution :
DefaultResolution;
y_resolution=image->y_resolution != 0.0 ? image->y_resolution :
DefaultResolution;
storage_class=image->storage_class;
if (image_info->compression == JPEGCompression)
storage_class=DirectClass;
if (storage_class == DirectClass)
{
pixmap.component_count=image->matte != MagickFalse ? 4 : 3;
pixmap.pixel_type=16;
pixmap.bits_per_pixel=32;
pixmap.pack_type=0x04;
transfer_mode=0x40;
row_bytes=4*image->columns;
}
/*
Allocate memory.
*/
bytes_per_line=image->columns;
if (storage_class == DirectClass)
bytes_per_line*=image->matte != MagickFalse ? 4 : 3;
buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer));
packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t)
(row_bytes+MaxCount),sizeof(*packed_scanline));
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline));
if ((buffer == (unsigned char *) NULL) ||
(packed_scanline == (unsigned char *) NULL) ||
(scanline == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(scanline,0,row_bytes);
(void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount));
/*
Write header, header size, size bounding box, version, and reserved.
*/
(void) ResetMagickMemory(buffer,0,PictInfoSize);
(void) WriteBlob(image,PictInfoSize,buffer);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right);
(void) WriteBlobMSBShort(image,PictVersion);
(void) WriteBlobMSBShort(image,0x02ff); /* version #2 */
(void) WriteBlobMSBShort(image,PictInfoOp);
(void) WriteBlobMSBLong(image,0xFFFE0000UL);
/*
Write full size of the file, resolution, frame bounding box, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right);
(void) WriteBlobMSBLong(image,0x00000000L);
profile=GetImageProfile(image,"iptc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0x1f2);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobString(image,"8BIM");
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
}
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,4);
(void) WriteBlobMSBLong(image,0x00000002UL);
}
/*
Write crop region opcode and crop bounding box.
*/
(void) WriteBlobMSBShort(image,PictCropRegionOp);
(void) WriteBlobMSBShort(image,0xa);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right);
if (image_info->compression == JPEGCompression)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
size_t
length;
unsigned char
*blob;
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
jpeg_info=CloneImageInfo(image_info);
(void) CopyMagickString(jpeg_info->magick,"JPEG",MaxTextExtent);
length=0;
blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length,
&image->exception);
jpeg_info=DestroyImageInfo(jpeg_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
jpeg_image=DestroyImage(jpeg_image);
(void) WriteBlobMSBShort(image,PictJPEGOp);
(void) WriteBlobMSBLong(image,(unsigned int) length+154);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x40000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00400000UL);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00566A70UL);
(void) WriteBlobMSBLong(image,0x65670000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000001UL);
(void) WriteBlobMSBLong(image,0x00016170UL);
(void) WriteBlobMSBLong(image,0x706C0000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x87AC0001UL);
(void) WriteBlobMSBLong(image,0x0B466F74UL);
(void) WriteBlobMSBLong(image,0x6F202D20UL);
(void) WriteBlobMSBLong(image,0x4A504547UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x0018FFFFUL);
(void) WriteBlob(image,length,blob);
if ((length & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/*
Write picture opcode, row bytes, and picture bounding box, and version.
*/
if (storage_class == PseudoClass)
(void) WriteBlobMSBShort(image,PictPICTOp);
else
{
(void) WriteBlobMSBShort(image,PictPixmapOp);
(void) WriteBlobMSBLong(image,(size_t) base_address);
}
(void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000));
(void) WriteBlobMSBShort(image,(unsigned short) bounds.top);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.left);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.right);
/*
Write pack type, pack size, resolution, pixel type, and pixel size.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.version);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size);
(void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel);
/*
Write component count, size, plane bytes, table size, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.table);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved);
if (storage_class == PseudoClass)
{
/*
Write image colormap.
*/
(void) WriteBlobMSBLong(image,0x00000000L); /* color seed */
(void) WriteBlobMSBShort(image,0L); /* color flags */
(void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1));
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) WriteBlobMSBShort(image,(unsigned short) i);
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].red));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].green));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].blue));
}
}
/*
Write source and destination rectangle.
*/
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) transfer_mode);
/*
Write picture data.
*/
count=0;
if (storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
scanline[x]=(unsigned char) GetPixelIndex(indexes+x);
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image_info->compression == JPEGCompression)
{
(void) ResetMagickMemory(scanline,0,row_bytes);
for (y=0; y < (ssize_t) image->rows; y++)
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
}
else
{
register unsigned char
*blue,
*green,
*opacity,
*red;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
opacity=scanline+3*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
if (image->matte != MagickFalse)
{
opacity=scanline;
red=scanline+image->columns;
green=scanline+2*image->columns;
blue=scanline+3*image->columns;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
*red++=ScaleQuantumToChar(GetPixelRed(p));
*green++=ScaleQuantumToChar(GetPixelGreen(p));
*blue++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->matte != MagickFalse)
*opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if ((count & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
(void) WriteBlobMSBShort(image,PictEndOfPictureOp);
offset=TellBlob(image);
offset=SeekBlob(image,512,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) offset);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(MagickTrue);
}
| 16,589,949,673,789,804,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12665 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WritePICTImage in coders/pict.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12665 |
2,652 | ImageMagick | db1ffb6cf44bcfe5c4d5fcf9d9109ded5617387f | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/db1ffb6cf44bcfe5c4d5fcf9d9109ded5617387f | None | 1 | static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
currentOffset,
offset,
scene;
MagickSizeType
cc;
PixelPacket
transpix;
QuantizeInfo
*quantize_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*p;
ssize_t
y;
size_t
count,
bits_per_pixel,
bytes_per_row,
nextDepthOffset,
one;
unsigned char
bit,
byte,
color,
*lastrow,
*one_row,
*ptr,
version;
unsigned int
transparentIndex;
unsigned short
color16,
flags;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=AcquireExceptionInfo();
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
quantize_info=AcquireQuantizeInfo(image_info);
flags=0;
currentOffset=0;
transparentIndex=0;
transpix.red=0;
transpix.green=0;
transpix.blue=0;
transpix.opacity=0;
one=1;
version=0;
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
count=GetNumberColors(image,NULL,exception);
for (bits_per_pixel=1; (one << bits_per_pixel) < count; bits_per_pixel*=2) ;
if (bits_per_pixel > 16)
bits_per_pixel=16;
else
if (bits_per_pixel < 16)
(void) TransformImageColorspace(image,image->colorspace);
if (bits_per_pixel < 8)
{
(void) TransformImageColorspace(image,GRAYColorspace);
(void) SetImageType(image,PaletteType);
(void) SortColormapByIntensity(image);
}
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass);
if (image->storage_class == PseudoClass)
flags|=PALM_HAS_COLORMAP_FLAG;
else
flags|=PALM_IS_DIRECT_COLOR;
(void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
(void) WriteBlobMSBShort(image,(unsigned short) image->rows); /* height */
bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
bits_per_pixel))*2;
(void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
flags|=PALM_IS_COMPRESSED_FLAG;
(void) WriteBlobMSBShort(image, flags);
(void) WriteBlobByte(image,(unsigned char) bits_per_pixel);
if (bits_per_pixel > 1)
version=1;
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
version=2;
(void) WriteBlobByte(image,version);
(void) WriteBlobMSBShort(image,0); /* nextDepthOffset */
(void) WriteBlobByte(image,(unsigned char) transparentIndex);
if (image_info->compression == RLECompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_RLE);
else
if (image_info->compression == FaxCompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE);
else
(void) WriteBlobByte(image,PALM_COMPRESSION_NONE);
(void) WriteBlobMSBShort(image,0); /* reserved */
offset=16;
if (bits_per_pixel == 16)
{
(void) WriteBlobByte(image,5); /* # of bits of red */
(void) WriteBlobByte(image,6); /* # of bits of green */
(void) WriteBlobByte(image,5); /* # of bits of blue */
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobMSBLong(image,0); /* no transparent color, YET */
offset+=8;
}
if (bits_per_pixel == 8)
{
if (flags & PALM_HAS_COLORMAP_FLAG) /* Write out colormap */
{
quantize_info->dither=IsPaletteImage(image,&image->exception);
quantize_info->number_colors=image->colors;
(void) QuantizeImage(quantize_info,image);
(void) WriteBlobMSBShort(image,(unsigned short) image->colors);
for (count = 0; count < image->colors; count++)
{
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[count].red));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[count].green));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[count].blue));
}
offset+=2+count*4;
}
else /* Map colors to Palm standard colormap */
{
Image
*affinity_image;
affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
exception);
(void) TransformImageColorspace(affinity_image,
affinity_image->colorspace);
(void) RemapImage(quantize_info,image,affinity_image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,FindColor(&image->colormap[
(ssize_t) GetPixelIndex(indexes+x)]));
}
affinity_image=DestroyImage(affinity_image);
}
}
if (flags & PALM_IS_COMPRESSED_FLAG)
(void) WriteBlobMSBShort(image,0); /* fill in size later */
lastrow=(unsigned char *) NULL;
if (image_info->compression == FaxCompression)
lastrow=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*lastrow));
/* TODO check whether memory really was acquired? */
one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*one_row));
if (one_row == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
ptr=one_row;
(void) ResetMagickMemory(ptr,0,bytes_per_row);
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (bits_per_pixel == 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
color16=(unsigned short) ((((31*(size_t) GetPixelRed(p))/
(size_t) QuantumRange) << 11) |
(((63*(size_t) GetPixelGreen(p))/(size_t) QuantumRange) << 5) |
((31*(size_t) GetPixelBlue(p))/(size_t) QuantumRange));
if (GetPixelOpacity(p) == (Quantum) TransparentOpacity)
{
transpix.red=GetPixelRed(p);
transpix.green=GetPixelGreen(p);
transpix.blue=GetPixelBlue(p);
transpix.opacity=GetPixelOpacity(p);
flags|=PALM_HAS_TRANSPARENCY_FLAG;
}
*ptr++=(unsigned char) ((color16 >> 8) & 0xff);
*ptr++=(unsigned char) (color16 & 0xff);
p++;
}
}
else
{
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bits_per_pixel >= 8)
color=(unsigned char) GetPixelIndex(indexes+x);
else
color=(unsigned char) (GetPixelIndex(indexes+x)*
((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1));
byte|=color << bit;
if (bit != 0)
bit-=(unsigned char) bits_per_pixel;
else
{
*ptr++=byte;
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
}
}
if ((image->columns % (8/bits_per_pixel)) != 0)
*ptr++=byte;
}
if (image_info->compression == RLECompression)
{
x=0;
while (x < (ssize_t) bytes_per_row)
{
byte=one_row[x];
count=1;
while ((one_row[++x] == byte) && (count < 255) &&
(x < (ssize_t) bytes_per_row))
count++;
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
else
if (image_info->compression == FaxCompression)
{
char
tmpbuf[8],
*tptr;
for (x = 0; x < (ssize_t) bytes_per_row; x += 8)
{
tptr = tmpbuf;
for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++)
{
if ((y == 0) || (lastrow[x + bit] != one_row[x + bit]))
{
byte |= (1 << (7 - bit));
*tptr++ = (char) one_row[x + bit];
}
}
(void) WriteBlobByte(image, byte);
(void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf);
}
(void) CopyMagickMemory(lastrow,one_row,bytes_per_row);
}
else
(void) WriteBlob(image,bytes_per_row,one_row);
}
if (flags & PALM_HAS_TRANSPARENCY_FLAG)
{
offset=SeekBlob(image,currentOffset+6,SEEK_SET);
(void) WriteBlobMSBShort(image,flags);
offset=SeekBlob(image,currentOffset+12,SEEK_SET);
(void) WriteBlobByte(image,(unsigned char) transparentIndex); /* trans index */
}
if (bits_per_pixel == 16)
{
offset=SeekBlob(image,currentOffset+20,SEEK_SET);
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/QuantumRange));
}
if (flags & PALM_IS_COMPRESSED_FLAG) /* fill in size now */
{
offset=SeekBlob(image,currentOffset+offset,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)-
currentOffset-offset));
}
if (one_row != (unsigned char *) NULL)
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (lastrow != (unsigned char *) NULL)
lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
if (GetNextImageInList(image) == (Image *) NULL)
break;
/* padding to 4 byte word */
for (cc=(GetBlobSize(image)) % 4; cc > 0; cc--)
(void) WriteBlobByte(image,0);
/* write nextDepthOffset and return to end of image */
(void) SeekBlob(image,currentOffset+10,SEEK_SET);
nextDepthOffset=(size_t) ((GetBlobSize(image)-currentOffset)/4);
(void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset);
currentOffset=(MagickOffsetType) GetBlobSize(image);
(void) SeekBlob(image,currentOffset,SEEK_SET);
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
quantize_info=DestroyQuantizeInfo(quantize_info);
(void) CloseBlob(image);
(void) DestroyExceptionInfo(exception);
return(MagickTrue);
}
| 326,733,059,304,932,100,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12664 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WritePALMImage in coders/palm.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12664 |
2,654 | ImageMagick | 6233ef75bb973745ab1092b59aea8fe316f09074 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/6233ef75bb973745ab1092b59aea8fe316f09074 | None | 1 | static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| 48,387,372,742,263,020,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12663 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WriteMAPImage in coders/map.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12663 |
2,655 | ImageMagick | 73a2bad43d157acfe360595feee739b4cc4406cb | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/73a2bad43d157acfe360595feee739b4cc4406cb | None | 1 | static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image)
{
#define CFormat "/Filter [ /%s ]\n"
#define ObjectsPerImage 14
DisableMSCWarning(4310)
static const char
XMPProfile[]=
{
"<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
" <xap:ModifyDate>%s</xap:ModifyDate>\n"
" <xap:CreateDate>%s</xap:CreateDate>\n"
" <xap:MetadataDate>%s</xap:MetadataDate>\n"
" <xap:CreatorTool>%s</xap:CreatorTool>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:format>application/pdf</dc:format>\n"
" <dc:title>\n"
" <rdf:Alt>\n"
" <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
" </rdf:Alt>\n"
" </dc:title>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
" <pdf:Producer>%s</pdf:Producer>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
" <pdfaid:part>3</pdfaid:part>\n"
" <pdfaid:conformance>B</pdfaid:conformance>\n"
" </rdf:Description>\n"
" </rdf:RDF>\n"
"</x:xmpmeta>\n"
"<?xpacket end=\"w\"?>\n"
},
XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
RestoreMSCWarning
char
basename[MaxTextExtent],
buffer[MaxTextExtent],
date[MaxTextExtent],
*escape,
**labels,
page_geometry[MaxTextExtent],
*url;
CompressionType
compression;
const char
*device,
*option,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
Image
*next,
*tile_image;
MagickBooleanType
status;
MagickOffsetType
offset,
scene,
*xref;
MagickSizeType
number_pixels;
MagickStatusType
flags;
PointInfo
delta,
resolution,
scale;
RectangleInfo
geometry,
media_info,
page_info;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register unsigned char
*q;
register ssize_t
i,
x;
size_t
channels,
info_id,
length,
object,
pages_id,
root_id,
text_size,
version;
ssize_t
count,
page_count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
wchar_t
*utf16;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Allocate X ref memory.
*/
xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref));
/*
Write Info object.
*/
object=0;
version=3;
if (image_info->compression == JPEG2000Compression)
version=(size_t) MagickMax(version,5);
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
if (next->matte != MagickFalse)
version=(size_t) MagickMax(version,4);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
version=(size_t) MagickMax(version,6);
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
version=(size_t) MagickMax(version,7);
(void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double)
version);
(void) WriteBlobString(image,buffer);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
(void) WriteBlobByte(image,'%');
(void) WriteBlobByte(image,0xe2);
(void) WriteBlobByte(image,0xe3);
(void) WriteBlobByte(image,0xcf);
(void) WriteBlobByte(image,0xd3);
(void) WriteBlobByte(image,'\n');
}
/*
Write Catalog object.
*/
xref[object++]=TellBlob(image);
root_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") != 0)
(void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double)
object+1);
else
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",
(double) object+2);
}
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Catalog");
option=GetImageOption(image_info,"pdf:page-direction");
if ((option != (const char *) NULL) &&
(LocaleCompare(option,"right-to-left") != MagickFalse))
(void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n");
(void) WriteBlobString(image,"\n");
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
GetPathComponent(image->filename,BasePath,basename);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
char
create_date[MaxTextExtent],
modify_date[MaxTextExtent],
timestamp[MaxTextExtent],
xmp_profile[MaxTextExtent],
*url;
/*
Write XMP object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Subtype /XML\n");
*modify_date='\0';
value=GetImageProperty(image,"date:modify");
if (value != (const char *) NULL)
(void) CopyMagickString(modify_date,value,MaxTextExtent);
*create_date='\0';
value=GetImageProperty(image,"date:create");
if (value != (const char *) NULL)
(void) CopyMagickString(create_date,value,MaxTextExtent);
(void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp);
url=GetMagickHomeURL();
escape=EscapeParenthesis(basename);
i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile,
XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);
escape=DestroyString(escape);
url=DestroyString(url);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double)
i);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Metadata\n");
(void) WriteBlobString(image,">>\nstream\n");
(void) WriteBlobString(image,xmp_profile);
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
}
/*
Write Pages object.
*/
xref[object++]=TellBlob(image);
pages_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Pages\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double)
object+1);
(void) WriteBlobString(image,buffer);
count=(ssize_t) (pages_id+ObjectsPerImage+1);
page_count=1;
if (image_info->adjoin != MagickFalse)
{
Image
*kid_image;
/*
Predict page object id's.
*/
kid_image=image;
for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
{
page_count++;
profile=GetImageProfile(kid_image,"icc");
if (profile != (StringInfo *) NULL)
count+=2;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double)
count);
(void) WriteBlobString(image,buffer);
kid_image=GetNextImageInList(kid_image);
}
xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobString(image,"]\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double)
page_count);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
scene=0;
do
{
MagickBooleanType
has_icc_profile;
profile=GetImageProfile(image,"icc");
has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if ((SetImageMonochrome(image,&image->exception) == MagickFalse) ||
(image->matte != MagickFalse))
compression=RLECompression;
break;
}
#if !defined(MAGICKCORE_JPEG_DELEGATE)
case JPEGCompression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
case JPEG2000Compression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_ZLIB_DELEGATE)
case ZipCompression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
image->filename);
break;
}
#endif
case LZWCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* LZW compression is forbidden */
break;
}
case NoCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* ASCII 85 compression is forbidden */
break;
}
default:
break;
}
if (compression == JPEG2000Compression)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Scale relative to dots-per-inch.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->x_resolution;
resolution.y=image->y_resolution;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double)
image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PDF") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
(void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,
&image->exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
(void) text_size;
/*
Write Page object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Page\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n",
(double) pages_id);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Resources <<\n");
labels=(char **) NULL;
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+4);
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MaxTextExtent,
"/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+5);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n",
(double) object+3);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 10 : 8));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Contents object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
(void) WriteBlobString(image,"q\n");
if (labels != (char **) NULL)
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) WriteBlobString(image,"BT\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n",
(double) image->scene,pointsize);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n",
(double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
12));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"ET\n");
labels[i]=DestroyString(labels[i]);
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n",
scale.x,scale.y,(double) geometry.x,(double) geometry.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"Q\n");
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Procset object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent);
else
if ((compression == FaxCompression) || (compression == Group4Compression))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent);
else
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ]\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Font object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (labels != (char **) NULL)
{
(void) WriteBlobString(image,"/Type /Font\n");
(void) WriteBlobString(image,"/Subtype /Type1\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/BaseFont /Helvetica\n");
(void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
labels=(char **) RelinquishMagickMemory(labels);
}
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write XObject object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) image->columns,(double) image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
(double) object+2);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
if (image->matte != MagickFalse)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 9 : 7));
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((compression == FaxCompression) || (compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,image);
break;
}
(void) Huffman2DEncodeImage(image_info,image,image);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p)));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelIndex(indexes+x));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelIndex(indexes+x)));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
Ascii85Encode(image,(unsigned char)
GetPixelIndex(indexes+x));
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Colorspace object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
device="DeviceRGB";
channels=0;
if (image->colorspace == CMYKColorspace)
{
device="DeviceCMYK";
channels=4;
}
else
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse)))
{
device="DeviceGray";
channels=1;
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
{
device="DeviceRGB";
channels=3;
}
profile=GetImageProfile(image,"icc");
if ((profile == (StringInfo *) NULL) || (channels == 0))
{
if (channels != 0)
(void) FormatLocaleString(buffer,MaxTextExtent,"/%s\n",device);
else
(void) FormatLocaleString(buffer,MaxTextExtent,
"[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors-
1,(double) object+3);
(void) WriteBlobString(image,buffer);
}
else
{
const unsigned char
*p;
/*
Write ICC profile.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"[/ICCBased %.20g 0 R]\n",(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"<<\n/N %.20g\n"
"/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n"
"stream\n",(double) channels,(double) object+1,device);
(void) WriteBlobString(image,buffer);
offset=TellBlob(image);
Ascii85Initialize(image);
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
Ascii85Encode(image,(unsigned char) *p++);
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"endstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Thumb object.
*/
SetGeometry(image,&geometry);
(void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
tile_image=ThumbnailImage(image,geometry.width,geometry.height,
&image->exception);
if (tile_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,image->exception.reason);
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) tile_image->columns,(double) tile_image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
tile_image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
tile_image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
(double) object-(has_icc_profile != MagickFalse ? 3 : 1));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(tile_image,&image->exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,tile_image);
break;
}
(void) Huffman2DEncodeImage(image_info,image,tile_image);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p)));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p))));
p++;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((tile_image->storage_class == DirectClass) ||
(tile_image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runoffset encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
if (tile_image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelIndex(indexes+x));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelIndex(indexes+x)));
p++;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
Ascii85Encode(image,(unsigned char)
GetPixelIndex(indexes+x));
}
Ascii85Flush(image);
break;
}
}
}
tile_image=DestroyImage(tile_image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == FaxCompression) || (compression == Group4Compression))
(void) WriteBlobString(image,">>\n");
else
{
/*
Write Colormap object.
*/
if (compression == NoCompression)
(void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
if (compression == NoCompression)
Ascii85Initialize(image);
for (i=0; i < (ssize_t) image->colors; i++)
{
if (compression == NoCompression)
{
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red));
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green));
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue));
continue;
}
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].red));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].green));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].blue));
}
if (compression == NoCompression)
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write softmask object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (image->matte == MagickFalse)
(void) WriteBlobString(image,">>\n");
else
{
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"ASCII85Decode");
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"FlateDecode");
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression)
? 1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
image=DestroyImage(image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelOpacity(p))));
p++;
}
}
Ascii85Flush(image);
break;
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
/*
Write Metadata object.
*/
xref[object++]=TellBlob(image);
info_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);
if (utf16 != (wchar_t *) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/Title (\xfe\xff");
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) length; i++)
(void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);
(void) FormatLocaleString(buffer,MaxTextExtent,")\n");
(void) WriteBlobString(image,buffer);
utf16=(wchar_t *) RelinquishMagickMemory(utf16);
}
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d",
local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
(void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
url=GetMagickHomeURL();
escape=EscapeParenthesis(url);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape);
escape=DestroyString(escape);
url=DestroyString(url);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Xref object.
*/
offset=TellBlob(image)-xref[0]+
(LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
(void) WriteBlobString(image,"xref\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"0000000000 65535 f \n");
for (i=0; i < (ssize_t) object; i++)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n",
(unsigned long) xref[i]);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"trailer\n");
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double)
info_id);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double)
root_id);
(void) WriteBlobString(image,buffer);
(void) SignatureImage(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n",
GetImageProperty(image,"signature"),GetImageProperty(image,"signature"));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"startxref\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%EOF\n");
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
(void) CloseBlob(image);
return(MagickTrue);
}
| 295,540,819,852,515,800,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12662 | ImageMagick 7.0.6-2 has a memory leak vulnerability in WritePDFImage in coders/pdf.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12662 |
2,656 | ImageMagick | 9eedb5660f1704cde8e8cd784c5c2a09dd2fd60f | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/9eedb5660f1704cde8e8cd784c5c2a09dd2fd60f | None | 1 | static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
| 300,007,481,126,911,370,000,000,000,000,000,000,000 | None | null | [
"CWE-770"
] | CVE-2017-12643 | ImageMagick 7.0.6-1 has a memory exhaustion vulnerability in ReadOneJNGImage in coders\png.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12643 |
2,658 | ImageMagick | 3320955045e5a2a22c13a04fa9422bb809e75eda | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/3320955045e5a2a22c13a04fa9422bb809e75eda | None | 1 | static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
| 230,970,568,755,587,880,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-12641 | ImageMagick 7.0.6-1 has a memory leak vulnerability in ReadOneJNGImage in coders\png.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12641 |
2,659 | ImageMagick | 78d4c5db50fbab0b4beb69c46c6167f2c6513dec | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/78d4c5db50fbab0b4beb69c46c6167f2c6513dec | None | 1 | static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
}
| 22,632,770,722,273,930,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-12640 | ImageMagick 7.0.6-1 has an out-of-bounds read vulnerability in ReadOneMNGImage in coders/png.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-12640 |
2,662 | ImageMagick | e793eb203e5e0f91f5037aed6585e81b1e27395b | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/e793eb203e5e0f91f5037aed6585e81b1e27395b | https://github.com/ImageMagick/ImageMagick/issues/636 | 1 | static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info,
Image **image,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
Image
*msl_image;
int
status;
ssize_t
n;
MSLInfo
msl_info;
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(image != (Image **) NULL);
msl_image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
msl_image->filename);
msl_image=DestroyImageList(msl_image);
return(MagickFalse);
}
msl_image->columns=1;
msl_image->rows=1;
/*
Parse MSL file.
*/
(void) ResetMagickMemory(&msl_info,0,sizeof(msl_info));
msl_info.exception=exception;
msl_info.image_info=(ImageInfo **) AcquireMagickMemory(
sizeof(*msl_info.image_info));
msl_info.draw_info=(DrawInfo **) AcquireMagickMemory(
sizeof(*msl_info.draw_info));
/* top of the stack is the MSL file itself */
msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image));
msl_info.attributes=(Image **) AcquireMagickMemory(
sizeof(*msl_info.attributes));
msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory(
sizeof(*msl_info.group_info));
if ((msl_info.image_info == (ImageInfo **) NULL) ||
(msl_info.image == (Image **) NULL) ||
(msl_info.attributes == (Image **) NULL) ||
(msl_info.group_info == (MSLGroupInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"UnableToInterpretMSLImage");
*msl_info.image_info=CloneImageInfo(image_info);
*msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
*msl_info.attributes=AcquireImage(image_info,exception);
msl_info.group_info[0].numImages=0;
/* the first slot is used to point to the MSL file image */
*msl_info.image=msl_image;
if (*image != (Image *) NULL)
MSLPushImage(&msl_info,*image);
(void) xmlSubstituteEntitiesDefault(1);
(void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=MSLInternalSubset;
sax_modules.isStandalone=MSLIsStandalone;
sax_modules.hasInternalSubset=MSLHasInternalSubset;
sax_modules.hasExternalSubset=MSLHasExternalSubset;
sax_modules.resolveEntity=MSLResolveEntity;
sax_modules.getEntity=MSLGetEntity;
sax_modules.entityDecl=MSLEntityDeclaration;
sax_modules.notationDecl=MSLNotationDeclaration;
sax_modules.attributeDecl=MSLAttributeDeclaration;
sax_modules.elementDecl=MSLElementDeclaration;
sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=MSLSetDocumentLocator;
sax_modules.startDocument=MSLStartDocument;
sax_modules.endDocument=MSLEndDocument;
sax_modules.startElement=MSLStartElement;
sax_modules.endElement=MSLEndElement;
sax_modules.reference=MSLReference;
sax_modules.characters=MSLCharacters;
sax_modules.ignorableWhitespace=MSLIgnorableWhitespace;
sax_modules.processingInstruction=MSLProcessingInstructions;
sax_modules.comment=MSLComment;
sax_modules.warning=MSLWarning;
sax_modules.error=MSLError;
sax_modules.fatalError=MSLError;
sax_modules.getParameterEntity=MSLGetParameterEntity;
sax_modules.cdataBlock=MSLCDataBlock;
sax_modules.externalSubset=MSLExternalSubset;
sax_handler=(&sax_modules);
msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0,
msl_image->filename);
while (ReadBlobString(msl_image,message) != (char *) NULL)
{
n=(ssize_t) strlen(message);
if (n == 0)
continue;
status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse);
if (status != 0)
break;
(void) xmlParseChunk(msl_info.parser," ",1,MagickFalse);
if (msl_info.exception->severity >= ErrorException)
break;
}
if (msl_info.exception->severity == UndefinedException)
(void) xmlParseChunk(msl_info.parser," ",1,MagickTrue);
xmlFreeParserCtxt(msl_info.parser);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory(
msl_info.group_info);
if (*image == (Image *) NULL)
*image=(*msl_info.image);
if (msl_info.exception->severity != UndefinedException)
return(MagickFalse);
return(MagickTrue);
}
| 112,895,750,210,052,900,000,000,000,000,000,000,000 | msl.c | 158,414,803,465,023,320,000,000,000,000,000,000,000 | [
"CWE-772"
] | CVE-2017-12427 | The ProcessMSLScript function in coders/msl.c in ImageMagick before 6.9.9-5 and 7.x before 7.0.6-5 allows remote attackers to cause a denial of service (memory leak) via a crafted file, related to the WriteMSLImage function. | https://nvd.nist.gov/vuln/detail/CVE-2017-12427 |
2,663 | linux | ea6789980fdaa610d7eb63602c746bf6ec70cd2b | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/ea6789980fdaa610d7eb63602c746bf6ec70cd2b | assoc_array: Fix a buggy node-splitting case
This fixes CVE-2017-12193.
Fix a case in the assoc_array implementation in which a new leaf is
added that needs to go into a node that happens to be full, where the
existing leaves in that node cluster together at that level to the
exclusion of new leaf.
What needs to happen is that the existing leaves get moved out to a new
node, N1, at level + 1 and the existing node needs replacing with one,
N0, that has pointers to the new leaf and to N1.
The code that tries to do this gets this wrong in two ways:
(1) The pointer that should've pointed from N0 to N1 is set to point
recursively to N0 instead.
(2) The backpointer from N0 needs to be set correctly in the case N0 is
either the root node or reached through a shortcut.
Fix this by removing this path and using the split_node path instead,
which achieves the same end, but in a more general way (thanks to Eric
Biggers for spotting the redundancy).
The problem manifests itself as:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
IP: assoc_array_apply_edit+0x59/0xe5
Fixes: 3cb989501c26 ("Add a generic associative array implementation.")
Reported-and-tested-by: WU Fan <u3536072@connect.hku.hk>
Signed-off-by: David Howells <dhowells@redhat.com>
Cc: stable@vger.kernel.org [v3.13-rc1+]
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> | 1 | static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0;
struct assoc_array_node *node, *new_n0, *new_n1, *side;
struct assoc_array_ptr *ptr;
unsigned long dissimilarity, base_seg, blank;
size_t keylen;
bool have_meta;
int level, diff;
int slot, next_slot, free_slot, i, j;
node = result->terminal_node.node;
level = result->terminal_node.level;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
pr_devel("-->%s()\n", __func__);
/* We arrived at a node which doesn't have an onward node or shortcut
* pointer that we have to follow. This means that (a) the leaf we
* want must go here (either by insertion or replacement) or (b) we
* need to split this node and insert in one of the fragments.
*/
free_slot = -1;
/* Firstly, we have to check the leaves in this node to see if there's
* a matching one we should replace in place.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (!ptr) {
free_slot = i;
continue;
}
if (assoc_array_ptr_is_leaf(ptr) &&
ops->compare_object(assoc_array_ptr_to_leaf(ptr),
index_key)) {
pr_devel("replace in slot %d\n", i);
edit->leaf_p = &node->slots[i];
edit->dead_leaf = node->slots[i];
pr_devel("<--%s() = ok [replace]\n", __func__);
return true;
}
}
/* If there is a free slot in this node then we can just insert the
* leaf here.
*/
if (free_slot >= 0) {
pr_devel("insert in free slot %d\n", free_slot);
edit->leaf_p = &node->slots[free_slot];
edit->adjust_count_on = node;
pr_devel("<--%s() = ok [insert]\n", __func__);
return true;
}
/* The node has no spare slots - so we're either going to have to split
* it or insert another node before it.
*
* Whatever, we're going to need at least two new nodes - so allocate
* those now. We may also need a new shortcut, but we deal with that
* when we need it.
*/
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n1)
return false;
edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
/* We need to find out how similar the leaves are. */
pr_devel("no spare slots\n");
have_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
edit->segment_cache[i] = 0xff;
have_meta = true;
continue;
}
base_seg = ops->get_object_key_chunk(
assoc_array_ptr_to_leaf(ptr), level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
if (have_meta) {
pr_devel("have meta\n");
goto split_node;
}
/* The node contains only leaves */
dissimilarity = 0;
base_seg = edit->segment_cache[0];
for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
dissimilarity |= edit->segment_cache[i] ^ base_seg;
pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
/* The old leaves all cluster in the same slot. We will need
* to insert a shortcut if the new node wants to cluster with them.
*/
if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
goto all_leaves_cluster_together;
/* Otherwise we can just insert a new node ahead of the old
* one.
*/
goto present_leaves_cluster_but_not_new_leaf;
}
split_node:
pr_devel("split node\n");
/* We need to split the current node; we know that the node doesn't
* simply contain a full set of leaves that cluster together (it
* contains meta pointers and/or non-clustering leaves).
*
* We need to expel at least two leaves out of a set consisting of the
* leaves in the node and the new leaf.
*
* We need a new node (n0) to replace the current one and a new node to
* take the expelled nodes (n1).
*/
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
do_split_node:
pr_devel("do_split_node\n");
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->nr_leaves_on_branch = 0;
/* Begin by finding two matching leaves. There have to be at least two
* that match - even if there are meta pointers - because any leaf that
* would match a slot with a meta pointer in it must be somewhere
* behind that meta pointer and cannot be here. Further, given N
* remaining leaf slots, we now have N+1 leaves to go in them.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
slot = edit->segment_cache[i];
if (slot != 0xff)
for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
if (edit->segment_cache[j] == slot)
goto found_slot_for_multiple_occupancy;
}
found_slot_for_multiple_occupancy:
pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
new_n1->parent_slot = slot;
/* Metadata pointers cannot change slot */
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
if (assoc_array_ptr_is_meta(node->slots[i]))
new_n0->slots[i] = node->slots[i];
else
new_n0->slots[i] = NULL;
BUG_ON(new_n0->slots[slot] != NULL);
new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
/* Filter the leaf pointers between the new nodes */
free_slot = -1;
next_slot = 0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (assoc_array_ptr_is_meta(node->slots[i]))
continue;
if (edit->segment_cache[i] == slot) {
new_n1->slots[next_slot++] = node->slots[i];
new_n1->nr_leaves_on_branch++;
} else {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
new_n0->slots[free_slot] = node->slots[i];
}
}
pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
edit->leaf_p = &new_n0->slots[free_slot];
edit->adjust_count_on = new_n0;
} else {
edit->leaf_p = &new_n1->slots[next_slot++];
edit->adjust_count_on = new_n1;
}
BUG_ON(next_slot <= 1);
edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (edit->segment_cache[i] == 0xff) {
ptr = node->slots[i];
BUG_ON(assoc_array_ptr_is_leaf(ptr));
if (assoc_array_ptr_is_node(ptr)) {
side = assoc_array_ptr_to_node(ptr);
edit->set_backpointers[i] = &side->back_pointer;
} else {
shortcut = assoc_array_ptr_to_shortcut(ptr);
edit->set_backpointers[i] = &shortcut->back_pointer;
}
}
}
ptr = node->back_pointer;
if (!ptr)
edit->set[0].ptr = &edit->array->root;
else if (assoc_array_ptr_is_node(ptr))
edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
else
edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [split node]\n", __func__);
return true;
present_leaves_cluster_but_not_new_leaf:
/* All the old leaves cluster in the same slot, but the new leaf wants
* to go into a different slot, so we create a new node to hold the new
* leaf and a pointer to a new node holding all the old leaves.
*/
pr_devel("present leaves cluster but not new leaf\n");
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = edit->segment_cache[0];
new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
new_n1->slots[i] = node->slots[i];
new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]];
edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot];
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [insert node before]\n", __func__);
return true;
all_leaves_cluster_together:
/* All the leaves, new and old, want to cluster together in this node
* in the same slot, so we have to replace this node with a shortcut to
* skip over the identical parts of the key and then place a pair of
* nodes, one inside the other, at the end of the shortcut and
* distribute the keys between them.
*
* Firstly we need to work out where the leaves start diverging as a
* bit position into their keys so that we know how big the shortcut
* needs to be.
*
* We only need to make a single pass of N of the N+1 leaves because if
* any keys differ between themselves at bit X then at least one of
* them must also differ with the base key at bit X or before.
*/
pr_devel("all leaves cluster together\n");
diff = INT_MAX;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
index_key);
if (x < diff) {
BUG_ON(x < 0);
diff = x;
}
}
BUG_ON(diff == INT_MAX);
BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = node->back_pointer;
new_s0->parent_slot = node->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
BUG_ON(level <= 0);
for (i = 0; i < keylen; i++)
new_s0->index_key[i] =
ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
new_s0->index_key[keylen - 1] &= ~blank;
/* This now reduces to a node splitting exercise for which we'll need
* to regenerate the disparity table.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
base_seg = ops->get_key_chunk(index_key, level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
goto do_split_node;
}
| 253,577,312,062,185,030,000,000,000,000,000,000,000 | assoc_array.c | 298,293,148,560,020,940,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-12193 | The assoc_array_insert_into_terminal_node function in lib/assoc_array.c in the Linux kernel before 4.13.11 mishandles node splitting, which allows local users to cause a denial of service (NULL pointer dereference and panic) via a crafted application, as demonstrated by the keyring key type, and key addition and link creation operations. | https://nvd.nist.gov/vuln/detail/CVE-2017-12193 |
2,664 | linux | 37863c43b2c6464f252862bf2e9768264e961678 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/37863c43b2c6464f252862bf2e9768264e961678 | KEYS: prevent KEYCTL_READ on negative key
Because keyctl_read_key() looks up the key with no permissions
requested, it may find a negatively instantiated key. If the key is
also possessed, we went ahead and called ->read() on the key. But the
key payload will actually contain the ->reject_error rather than the
normal payload. Thus, the kernel oopses trying to read the
user_key_payload from memory address (int)-ENOKEY = 0x00000000ffffff82.
Fortunately the payload data is stored inline, so it shouldn't be
possible to abuse this as an arbitrary memory read primitive...
Reproducer:
keyctl new_session
keyctl request2 user desc '' @s
keyctl read $(keyctl show | awk '/user: desc/ {print $1}')
It causes a crash like the following:
BUG: unable to handle kernel paging request at 00000000ffffff92
IP: user_read+0x33/0xa0
PGD 36a54067 P4D 36a54067 PUD 0
Oops: 0000 [#1] SMP
CPU: 0 PID: 211 Comm: keyctl Not tainted 4.14.0-rc1 #337
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014
task: ffff90aa3b74c3c0 task.stack: ffff9878c0478000
RIP: 0010:user_read+0x33/0xa0
RSP: 0018:ffff9878c047bee8 EFLAGS: 00010246
RAX: 0000000000000001 RBX: ffff90aa3d7da340 RCX: 0000000000000017
RDX: 0000000000000000 RSI: 00000000ffffff82 RDI: ffff90aa3d7da340
RBP: ffff9878c047bf00 R08: 00000024f95da94f R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
FS: 00007f58ece69740(0000) GS:ffff90aa3e200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000ffffff92 CR3: 0000000036adc001 CR4: 00000000003606f0
Call Trace:
keyctl_read_key+0xac/0xe0
SyS_keyctl+0x99/0x120
entry_SYSCALL_64_fastpath+0x1f/0xbe
RIP: 0033:0x7f58ec787bb9
RSP: 002b:00007ffc8d401678 EFLAGS: 00000206 ORIG_RAX: 00000000000000fa
RAX: ffffffffffffffda RBX: 00007ffc8d402800 RCX: 00007f58ec787bb9
RDX: 0000000000000000 RSI: 00000000174a63ac RDI: 000000000000000b
RBP: 0000000000000004 R08: 00007ffc8d402809 R09: 0000000000000020
R10: 0000000000000000 R11: 0000000000000206 R12: 00007ffc8d402800
R13: 00007ffc8d4016e0 R14: 0000000000000000 R15: 0000000000000000
Code: e5 41 55 49 89 f5 41 54 49 89 d4 53 48 89 fb e8 a4 b4 ad ff 85 c0 74 09 80 3d b9 4c 96 00 00 74 43 48 8b b3 20 01 00 00 4d 85 ed <0f> b7 5e 10 74 29 4d 85 e4 74 24 4c 39 e3 4c 89 e2 4c 89 ef 48
RIP: user_read+0x33/0xa0 RSP: ffff9878c047bee8
CR2: 00000000ffffff92
Fixes: 61ea0c0ba904 ("KEYS: Skip key state checks when checking for possession")
Cc: <stable@vger.kernel.org> [v3.13+]
Signed-off-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: David Howells <dhowells@redhat.com> | 1 | long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
| 217,498,043,437,743,400,000,000,000,000,000,000,000 | keyctl.c | 204,715,776,427,842,440,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-12192 | The keyctl_read_key function in security/keys/keyctl.c in the Key Management subcomponent in the Linux kernel before 4.13.5 does not properly consider that a key may be possessed but negatively instantiated, which allows local users to cause a denial of service (OOPS and system crash) via a crafted KEYCTL_READ operation. | https://nvd.nist.gov/vuln/detail/CVE-2017-12192 |
2,665 | linux | 95d78c28b5a85bacbc29b8dba7c04babb9b0d467 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/95d78c28b5a85bacbc29b8dba7c04babb9b0d467 | fix unbalanced page refcounting in bio_map_user_iov
bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if
IO vector has small consecutive buffers belonging to the same page.
bio_add_pc_page merges them into one, but the page reference is never
dropped.
Cc: stable@vger.kernel.org
Signed-off-by: Vitaly Mayatskikh <v.mayatskih@gmail.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> | 1 | struct bio *bio_map_user_iov(struct request_queue *q,
const struct iov_iter *iter,
gfp_t gfp_mask)
{
int j;
int nr_pages = 0;
struct page **pages;
struct bio *bio;
int cur_page = 0;
int ret, offset;
struct iov_iter i;
struct iovec iov;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
/*
* Overflow, abort
*/
if (end < start)
return ERR_PTR(-EINVAL);
nr_pages += end - start;
/*
* buffer must be aligned to at least logical block size for now
*/
if (uaddr & queue_dma_alignment(q))
return ERR_PTR(-EINVAL);
}
if (!nr_pages)
return ERR_PTR(-EINVAL);
bio = bio_kmalloc(gfp_mask, nr_pages);
if (!bio)
return ERR_PTR(-ENOMEM);
ret = -ENOMEM;
pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask);
if (!pages)
goto out;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
const int local_nr_pages = end - start;
const int page_limit = cur_page + local_nr_pages;
ret = get_user_pages_fast(uaddr, local_nr_pages,
(iter->type & WRITE) != WRITE,
&pages[cur_page]);
if (ret < local_nr_pages) {
ret = -EFAULT;
goto out_unmap;
}
offset = offset_in_page(uaddr);
for (j = cur_page; j < page_limit; j++) {
unsigned int bytes = PAGE_SIZE - offset;
if (len <= 0)
break;
if (bytes > len)
bytes = len;
/*
* sorry...
*/
if (bio_add_pc_page(q, bio, pages[j], bytes, offset) <
bytes)
break;
len -= bytes;
offset = 0;
}
cur_page = j;
/*
* release the pages we didn't map into the bio, if any
*/
while (j < page_limit)
put_page(pages[j++]);
}
kfree(pages);
bio_set_flag(bio, BIO_USER_MAPPED);
/*
* subtle -- if bio_map_user_iov() ended up bouncing a bio,
* it would normally disappear when its bi_end_io is run.
* however, we need it for the unmap, so grab an extra
* reference to it
*/
bio_get(bio);
return bio;
out_unmap:
for (j = 0; j < nr_pages; j++) {
if (!pages[j])
break;
put_page(pages[j]);
}
out:
kfree(pages);
bio_put(bio);
return ERR_PTR(ret);
}
| 55,680,421,256,663,070,000,000,000,000,000,000,000 | bio.c | 206,551,357,025,644,700,000,000,000,000,000,000,000 | [
"CWE-772"
] | CVE-2017-12190 | The bio_map_user_iov and bio_unmap_user functions in block/bio.c in the Linux kernel before 4.13.8 do unbalanced refcounting when a SCSI I/O vector has small consecutive buffers belonging to the same page. The bio_add_pc_page function merges them into one, but the page reference is never dropped. This causes a memory leak and possible system lockup (exploitable against the host OS by a guest OS user, if a SCSI disk is passed through to a virtual machine) due to an out-of-memory condition. | https://nvd.nist.gov/vuln/detail/CVE-2017-12190 |
2,666 | linux | 51aa68e7d57e3217192d88ce90fd5b8ef29ec94f | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/51aa68e7d57e3217192d88ce90fd5b8ef29ec94f | kvm: nVMX: Don't allow L2 to access the hardware CR8
If L1 does not specify the "use TPR shadow" VM-execution control in
vmcs12, then L0 must specify the "CR8-load exiting" and "CR8-store
exiting" VM-execution controls in vmcs02. Failure to do so will give
the L2 VM unrestricted read/write access to the hardware CR8.
This fixes CVE-2017-12154.
Signed-off-by: Jim Mattson <jmattson@google.com>
Reviewed-by: David Hildenbrand <david@redhat.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> | 1 | static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
bool from_vmentry, u32 *entry_failure_code)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exec_control, vmcs12_exec_ctrl;
vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
if (from_vmentry &&
(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
} else {
kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
}
if (from_vmentry) {
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
vmcs12->vm_entry_intr_info_field);
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
vmcs12->vm_entry_exception_error_code);
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmcs12->vm_entry_instruction_len);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
vmcs12->guest_interruptibility_info);
vmx->loaded_vmcs->nmi_known_unmasked =
!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
} else {
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
}
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
vmx_set_rflags(vcpu, vmcs12->guest_rflags);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
vmcs12->guest_pending_dbg_exceptions);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
if (nested_cpu_has_xsaves(vmcs12))
vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
exec_control = vmcs12->pin_based_vm_exec_control;
/* Preemption timer setting is only taken from vmcs01. */
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
exec_control |= vmcs_config.pin_based_exec_ctrl;
if (vmx->hv_deadline_tsc == -1)
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
/* Posted interrupts setting is only taken from vmcs12. */
if (nested_cpu_has_posted_intr(vmcs12)) {
vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
vmx->nested.pi_pending = false;
vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
} else {
exec_control &= ~PIN_BASED_POSTED_INTR;
}
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
vmx->nested.preemption_timer_expired = false;
if (nested_cpu_has_preemption_timer(vmcs12))
vmx_start_preemption_timer(vcpu);
/*
* Whether page-faults are trapped is determined by a combination of
* 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
* If enable_ept, L0 doesn't care about page faults and we should
* set all of these to L1's desires. However, if !enable_ept, L0 does
* care about (at least some) page faults, and because it is not easy
* (if at all possible?) to merge L0 and L1's desires, we simply ask
* to exit on each and every L2 page fault. This is done by setting
* MASK=MATCH=0 and (see below) EB.PF=1.
* Note that below we don't need special code to set EB.PF beyond the
* "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
* vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
* !enable_ept, EB.PF is 1, so the "or" will always be 1.
*/
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
enable_ept ? vmcs12->page_fault_error_code_mask : 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
enable_ept ? vmcs12->page_fault_error_code_match : 0);
if (cpu_has_secondary_exec_ctrls()) {
exec_control = vmx->secondary_exec_control;
/* Take the following fields only from vmcs12 */
exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_ENABLE_INVPCID |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_XSAVES |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_ENABLE_VMFUNC);
if (nested_cpu_has(vmcs12,
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
~SECONDARY_EXEC_ENABLE_PML;
exec_control |= vmcs12_exec_ctrl;
}
/* All VMFUNCs are currently emulated through L0 vmexits. */
if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
vmcs_write64(VM_FUNCTION_CONTROL, 0);
if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
vmcs_write64(EOI_EXIT_BITMAP0,
vmcs12->eoi_exit_bitmap0);
vmcs_write64(EOI_EXIT_BITMAP1,
vmcs12->eoi_exit_bitmap1);
vmcs_write64(EOI_EXIT_BITMAP2,
vmcs12->eoi_exit_bitmap2);
vmcs_write64(EOI_EXIT_BITMAP3,
vmcs12->eoi_exit_bitmap3);
vmcs_write16(GUEST_INTR_STATUS,
vmcs12->guest_intr_status);
}
/*
* Write an illegal value to APIC_ACCESS_ADDR. Later,
* nested_get_vmcs12_pages will either fix it up or
* remove the VM execution control.
*/
if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
vmcs_write64(APIC_ACCESS_ADDR, -1ull);
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
}
/*
* Set host-state according to L0's settings (vmcs12 is irrelevant here)
* Some constant fields are set here by vmx_set_constant_host_state().
* Other fields are different per CPU, and will be set later when
* vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
*/
vmx_set_constant_host_state(vmx);
/*
* Set the MSR load/store lists to match L0's settings.
*/
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
/*
* HOST_RSP is normally set correctly in vmx_vcpu_run() just before
* entry, but only if the current (host) sp changed from the value
* we wrote last (vmx->host_rsp). This cache is no longer relevant
* if we switch vmcs, and rather than hold a separate cache per vmcs,
* here we just force the write to happen on entry.
*/
vmx->host_rsp = 0;
exec_control = vmx_exec_control(vmx); /* L0's desires */
exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
exec_control &= ~CPU_BASED_TPR_SHADOW;
exec_control |= vmcs12->cpu_based_vm_exec_control;
/*
* Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
* nested_get_vmcs12_pages can't fix it up, the illegal value
* will result in a VM entry failure.
*/
if (exec_control & CPU_BASED_TPR_SHADOW) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
}
/*
* Merging of IO bitmap not currently supported.
* Rather, exit every time.
*/
exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
exec_control |= CPU_BASED_UNCOND_IO_EXITING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
* bitwise-or of what L1 wants to trap for L2, and what we want to
* trap. Note that CR0.TS also needs updating - we do this later.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
* we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
* bits are further modified by vmx_set_efer() below.
*/
vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
* emulated by vmx_set_efer(), below.
*/
vm_entry_controls_init(vmx,
(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
~VM_ENTRY_IA32E_MODE) |
(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
if (from_vmentry &&
(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
vcpu->arch.pat = vmcs12->guest_ia32_pat;
} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
}
set_cr4_guest_host_mask(vmx);
if (from_vmentry &&
vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
vmcs_write64(TSC_OFFSET,
vcpu->arch.tsc_offset + vmcs12->tsc_offset);
else
vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
if (kvm_has_tsc_control)
decache_tsc_multiplier(vmx);
if (enable_vpid) {
/*
* There is no direct mapping between vpid02 and vpid12, the
* vpid02 is per-vCPU for L0 and reused while the value of
* vpid12 is changed w/ one invvpid during nested vmentry.
* The vpid12 is allocated by L1 for L2, so it will not
* influence global bitmap(for vpid01 and vpid02 allocation)
* even if spawn a lot of nested vCPUs.
*/
if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
vmx->nested.last_vpid = vmcs12->virtual_processor_id;
__vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
}
} else {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
vmx_flush_tlb(vcpu);
}
}
if (enable_pml) {
/*
* Conceptually we want to copy the PML address and index from
* vmcs01 here, and then back to vmcs01 on nested vmexit. But,
* since we always flush the log on each vmexit, this happens
* to be equivalent to simply resetting the fields in vmcs02.
*/
ASSERT(vmx->pml_pg);
vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
}
if (nested_cpu_has_ept(vmcs12)) {
if (nested_ept_init_mmu_context(vcpu)) {
*entry_failure_code = ENTRY_FAIL_DEFAULT;
return 1;
}
} else if (nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
vmx_flush_tlb_ept_only(vcpu);
}
/*
* This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
* bits which we consider mandatory enabled.
* The CR0_READ_SHADOW is what L2 should have expected to read given
* the specifications by L1; It's not enough to take
* vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
* have more bits than L1 expected.
*/
vmx_set_cr0(vcpu, vmcs12->guest_cr0);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
vmx_set_cr4(vcpu, vmcs12->guest_cr4);
vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
if (from_vmentry &&
(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
vcpu->arch.efer = vmcs12->guest_ia32_efer;
else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
vmx_set_efer(vcpu, vcpu->arch.efer);
/* Shadow page tables on either EPT or shadow page tables. */
if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
entry_failure_code))
return 1;
if (!enable_ept)
vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
/*
* L1 may access the L2's PDPTR, so save them to construct vmcs12
*/
if (enable_ept) {
vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
}
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
return 0;
}
| 315,707,918,919,549,060,000,000,000,000,000,000,000 | vmx.c | 128,365,054,033,147,450,000,000,000,000,000,000,000 | [
"CWE-284"
] | CVE-2017-12154 | The prepare_vmcs02 function in arch/x86/kvm/vmx.c in the Linux kernel through 4.13.3 does not ensure that the "CR8-load exiting" and "CR8-store exiting" L0 vmcs02 controls exist in cases where L1 omits the "use TPR shadow" vmcs12 control, which allows KVM L2 guest OS users to obtain read and write access to the hardware CR8 register. | https://nvd.nist.gov/vuln/detail/CVE-2017-12154 |
2,676 | FFmpeg | ffcc82219cef0928bed2d558b19ef6ea35634130 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/ffcc82219cef0928bed2d558b19ef6ea35634130 | avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2
Fixes: out of array accesses
Found-by: JunDong Xie of Ant-financial Light-Year Security Lab
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {
len = ff_amf_tag_size(data, data_end);
if (len < 0)
len = data_end - data;
data += len;
}
if (data_end - data < 3)
return -1;
data++;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (size < 0 || size >= data_end - data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || len >= data_end - data)
return -1;
data += len;
}
return -1;
}
| 65,922,353,615,166,360,000,000,000,000,000,000,000 | rtmppkt.c | 39,451,849,705,085,110,000,000,000,000,000,000,000 | [
"CWE-20"
] | CVE-2017-11665 | The ff_amf_get_field_value function in libavformat/rtmppkt.c in FFmpeg 3.3.2 allows remote RTMP servers to cause a denial of service (Segmentation Violation and application crash) via a crafted stream. | https://nvd.nist.gov/vuln/detail/CVE-2017-11665 |
2,682 | wildmidi | 660b513d99bced8783a4a5984ac2f742c74ebbdd | https://github.com/Mindwerks/wildmidi | https://github.com/Mindwerks/wildmidi/commit/660b513d99bced8783a4a5984ac2f742c74ebbdd | None | 1 | uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint8_t running_event) {
/*
Only add standard MIDI and Sysex events in here.
Non-standard events need to be handled by calling function
to avoid compatibility issues.
TODO:
Add value limit checks
*/
uint32_t ret_cnt = 0;
uint8_t command = 0;
uint8_t channel = 0;
uint8_t data_1 = 0;
uint8_t data_2 = 0;
char *text = NULL;
if (event_data[0] >= 0x80) {
command = *event_data & 0xf0;
channel = *event_data++ & 0x0f;
ret_cnt++;
} else {
command = running_event & 0xf0;
channel = running_event & 0x0f;
}
switch(command) {
case 0x80:
_SETUP_NOTEOFF:
data_1 = *event_data++;
data_2 = *event_data++;
_WM_midi_setup_noteoff(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0x90:
if (event_data[1] == 0) goto _SETUP_NOTEOFF; /* A velocity of 0 in a note on is actually a note off */
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_noteon(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xa0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_aftertouch(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xb0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_control(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xc0:
data_1 = *event_data++;
midi_setup_patch(mdi, channel, data_1);
ret_cnt++;
break;
case 0xd0:
data_1 = *event_data++;
midi_setup_channel_pressure(mdi, channel, data_1);
ret_cnt++;
break;
case 0xe0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_pitch(mdi, channel, ((data_2 << 7) | (data_1 & 0x7f)));
ret_cnt += 2;
break;
case 0xf0:
if (channel == 0x0f) {
/*
MIDI Meta Events
*/
uint32_t tmp_length = 0;
if ((event_data[0] == 0x00) && (event_data[1] == 0x02)) {
/*
Sequence Number
We only setting this up here for WM_Event2Midi function
*/
midi_setup_sequenceno(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else if (event_data[0] == 0x01) {
/* Text Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_text(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x02) {
/* Copyright Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
/* Copy copyright info in the getinfo struct */
if (mdi->extra_info.copyright) {
mdi->extra_info.copyright = realloc(mdi->extra_info.copyright,(strlen(mdi->extra_info.copyright) + 1 + tmp_length + 1));
memcpy(&mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1], event_data, tmp_length);
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1 + tmp_length] = '\0';
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright)] = '\n';
} else {
mdi->extra_info.copyright = malloc(tmp_length + 1);
memcpy(mdi->extra_info.copyright, event_data, tmp_length);
mdi->extra_info.copyright[tmp_length] = '\0';
}
/* NOTE: free'd when events are cleared during closure of mdi */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_copyright(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x03) {
/* Track Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_trackname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x04) {
/* Instrument Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_instrumentname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x05) {
/* Lyric Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_lyric(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x06) {
/* Marker Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_marker(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x07) {
/* Cue Point Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_cuepoint(mdi, text);
ret_cnt += tmp_length;
} else if ((event_data[0] == 0x20) && (event_data[1] == 0x01)) {
/*
Channel Prefix
We only setting this up here for WM_Event2Midi function
*/
midi_setup_channelprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x21) && (event_data[1] == 0x01)) {
/*
Port Prefix
We only setting this up here for WM_Event2Midi function
*/
midi_setup_portprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x2F) && (event_data[1] == 0x00)) {
/*
End of Track
Deal with this inside calling function
We only setting this up here for _WM_Event2Midi function
*/
_WM_midi_setup_endoftrack(mdi);
ret_cnt += 2;
} else if ((event_data[0] == 0x51) && (event_data[1] == 0x03)) {
/*
Tempo
Deal with this inside calling function.
We only setting this up here for _WM_Event2Midi function
*/
_WM_midi_setup_tempo(mdi, ((event_data[2] << 16) + (event_data[3] << 8) + event_data[4]));
ret_cnt += 5;
} else if ((event_data[0] == 0x54) && (event_data[1] == 0x05)) {
/*
SMPTE Offset
We only setting this up here for WM_Event2Midi function
*/
midi_setup_smpteoffset(mdi, ((event_data[3] << 24) + (event_data[4] << 16) + (event_data[5] << 8) + event_data[6]));
/*
Because this has 5 bytes of data we gonna "hack" it a little
*/
mdi->events[mdi->events_size - 1].event_data.channel = event_data[2];
ret_cnt += 7;
} else if ((event_data[0] == 0x58) && (event_data[1] == 0x04)) {
/*
Time Signature
We only setting this up here for WM_Event2Midi function
*/
midi_setup_timesignature(mdi, ((event_data[2] << 24) + (event_data[3] << 16) + (event_data[4] << 8) + event_data[5]));
ret_cnt += 6;
} else if ((event_data[0] == 0x59) && (event_data[1] == 0x02)) {
/*
Key Signature
We only setting this up here for WM_Event2Midi function
*/
midi_setup_keysignature(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else {
/*
Unsupported Meta Event
*/
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
ret_cnt++;
ret_cnt += tmp_length;
}
} else if ((channel == 0) || (channel == 7)) {
/*
Sysex Events
*/
uint32_t sysex_len = 0;
uint8_t *sysex_store = NULL;
if (*event_data > 0x7f) {
do {
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
if (!sysex_len) break;
ret_cnt++;
sysex_store = malloc(sizeof(uint8_t) * sysex_len);
memcpy(sysex_store, event_data, sysex_len);
if (sysex_store[sysex_len - 1] == 0xF7) {
uint8_t rolandsysexid[] = { 0x41, 0x10, 0x42, 0x12 };
if (memcmp(rolandsysexid, sysex_store, 4) == 0) {
/* For Roland Sysex Messages */
/* checksum */
uint8_t sysex_cs = 0;
uint32_t sysex_ofs = 4;
do {
sysex_cs += sysex_store[sysex_ofs];
if (sysex_cs > 0x7F) {
sysex_cs -= 0x80;
}
sysex_ofs++;
} while (sysex_store[sysex_ofs + 1] != 0xf7);
sysex_cs = 128 - sysex_cs;
/* is roland sysex message valid */
if (sysex_cs == sysex_store[sysex_ofs]) {
/* process roland sysex event */
if (sysex_store[4] == 0x40) {
if (((sysex_store[5] & 0xf0) == 0x10) && (sysex_store[6] == 0x15)) {
/* Roland Drum Track Setting */
uint8_t sysex_ch = 0x0f & sysex_store[5];
if (sysex_ch == 0x00) {
sysex_ch = 0x09;
} else if (sysex_ch <= 0x09) {
sysex_ch -= 1;
}
midi_setup_sysex_roland_drum_track(mdi, sysex_ch, sysex_store[7]);
} else if ((sysex_store[5] == 0x00) && (sysex_store[6] == 0x7F) && (sysex_store[7] == 0x00)) {
/* Roland GS Reset */
midi_setup_sysex_roland_reset(mdi);
}
}
}
} else {
/* For non-Roland Sysex Messages */
uint8_t gm_reset[] = {0x7e, 0x7f, 0x09, 0x01, 0xf7};
uint8_t yamaha_reset[] = {0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7};
if (memcmp(gm_reset, sysex_store, 5) == 0) {
/* GM Reset */
midi_setup_sysex_gm_reset(mdi);
} else if (memcmp(yamaha_reset,sysex_store,8) == 0) {
/* Yamaha Reset */
midi_setup_sysex_yamaha_reset(mdi);
}
}
}
free(sysex_store);
sysex_store = NULL;
/*
event_data += sysex_len;
*/
ret_cnt += sysex_len;
} else {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(unrecognized meta type event)", 0);
return 0;
}
break;
default: /* Should NEVER get here */
ret_cnt = 0;
break;
}
if (ret_cnt == 0)
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing event)", 0);
return ret_cnt;
}
| 312,895,510,042,769,500,000,000,000,000,000,000,000 | internal_midi.c | 50,268,150,752,711,670,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-11661 | The _WM_SetupMidiEvent function in internal_midi.c:2318 in WildMIDI 0.4.2 can cause a denial of service (invalid memory read and application crash) via a crafted mid file. | https://nvd.nist.gov/vuln/detail/CVE-2017-11661 |
2,683 | ImageMagick | a8f9c2aabed37cd6a728532d1aed13ae0f3dfd78 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/a8f9c2aabed37cd6a728532d1aed13ae0f3dfd78 | None | 1 | static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 255,352,715,063,295,070,000,000,000,000,000,000,000 | None | null | [
"CWE-835"
] | CVE-2017-11523 | The ReadTXTImage function in coders/txt.c in ImageMagick through 6.9.9-0 and 7.x through 7.0.6-1 allows remote attackers to cause a denial of service (infinite loop) via a crafted file, because the end-of-file condition is not considered. | https://nvd.nist.gov/vuln/detail/CVE-2017-11523 |
2,684 | ImageMagick | 816ecab6c532ae086ff4186b3eaf4aa7092d536f | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/816ecab6c532ae086ff4186b3eaf4aa7092d536f | https://github.com/ImageMagick/ImageMagick/issues/58 | 1 | static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
s[2];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
if (image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*s;
register Quantum
*q,
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,q) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image, q, opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (Magick_png_color_equal(image,q,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image, q, opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,q) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image, q, transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,q);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,q);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,q);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (Magick_png_color_equal(image,q,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,q,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,q,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (Magick_png_color_equal(image,q,semitransparent+i)
&& GetPixelAlpha(image,q) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image, q, semitransparent+i);
}
}
}
q+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||
GetPixelRed(image,s) != GetPixelBlue(image,s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != 0 &&
GetPixelRed(image,s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,r);
SetPixelAlpha(image,TransparentAlpha,r);
}
else
SetPixelAlpha(image,OpaqueAlpha,r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR04PixelRGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR03RGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR02PixelBlue(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&
GetPixelAlpha(image,r) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),r);
}
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const Quantum
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
}
| 46,130,426,879,440,080,000,000,000,000,000,000,000 | png.c | 85,174,790,945,754,270,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-11522 | The WriteOnePNGImage function in coders/png.c in ImageMagick through 6.9.9-0 and 7.x through 7.0.6-1 allows remote attackers to cause a denial of service (NULL pointer dereference) via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-11522 |
2,685 | linux | 3b2d69114fefa474fca542e51119036dceb4aa6f | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/3b2d69114fefa474fca542e51119036dceb4aa6f | ACPICA: Namespace: fix operand cache leak
ACPICA commit a23325b2e583556eae88ed3f764e457786bf4df6
I found some ACPI operand cache leaks in ACPI early abort cases.
Boot log of ACPI operand cache leak is as follows:
>[ 0.174332] ACPI: Added _OSI(Module Device)
>[ 0.175504] ACPI: Added _OSI(Processor Device)
>[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.178284] ACPI: SCI (IRQ16705) allocation failed
>[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install
System Control Interrupt handler (20160930/evevent-131)
>[ 0.180008] ACPI: Unable to start the ACPI Interpreter
>[ 0.181125] ACPI Error: Could not remove SCI handler
(20160930/evmisc-281)
>[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has
objects
>[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2
>[ 0.186820] Hardware name: innotek gmb_h virtual_box/virtual_box, BIOS
virtual_box 12/01/2006
>[ 0.188000] Call Trace:
>[ 0.188000] ? dump_stack+0x5c/0x7d
>[ 0.188000] ? kmem_cache_destroy+0x224/0x230
>[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22
>[ 0.188000] ? acpi_os_delete_cache+0xa/0xd
>[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.188000] ? acpi_terminate+0x5/0xf
>[ 0.188000] ? acpi_init+0x288/0x32e
>[ 0.188000] ? __class_create+0x4c/0x80
>[ 0.188000] ? video_setup+0x7a/0x7a
>[ 0.188000] ? do_one_initcall+0x4e/0x1b0
>[ 0.188000] ? kernel_init_freeable+0x194/0x21a
>[ 0.188000] ? rest_init+0x80/0x80
>[ 0.188000] ? kernel_init+0xa/0x100
>[ 0.188000] ? ret_from_fork+0x25/0x30
When early abort is occurred due to invalid ACPI information, Linux kernel
terminates ACPI by calling acpi_terminate() function. The function calls
acpi_ns_terminate() function to delete namespace data and ACPI operand cache
(acpi_gbl_module_code_list).
But the deletion code in acpi_ns_terminate() function is wrapped in
ACPI_EXEC_APP definition, therefore the code is only executed when the
definition exists. If the define doesn't exist, ACPI operand cache
(acpi_gbl_module_code_list) is leaked, and stack dump is shown in kernel log.
This causes a security threat because the old kernel (<= 4.9) shows memory
locations of kernel functions in stack dump, therefore kernel ASLR can be
neutralized.
To fix ACPI operand leak for enhancing security, I made a patch which
removes the ACPI_EXEC_APP define in acpi_ns_terminate() function for
executing the deletion code unconditionally.
Link: https://github.com/acpica/acpica/commit/a23325b2
Signed-off-by: Seunghun Han <kkamagui@gmail.com>
Signed-off-by: Lv Zheng <lv.zheng@intel.com>
Signed-off-by: Bob Moore <robert.moore@intel.com>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com> | 1 | void acpi_ns_terminate(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ns_terminate);
#ifdef ACPI_EXEC_APP
{
union acpi_operand_object *prev;
union acpi_operand_object *next;
/* Delete any module-level code blocks */
next = acpi_gbl_module_code_list;
while (next) {
prev = next;
next = next->method.mutex;
prev->method.mutex = NULL; /* Clear the Mutex (cheated) field */
acpi_ut_remove_reference(prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
acpi_ns_delete_namespace_subtree(acpi_gbl_root_node);
/* Delete any objects attached to the root node */
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_VOID;
}
acpi_ns_delete_node(acpi_gbl_root_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
| 280,039,072,811,556,760,000,000,000,000,000,000,000 | nsutils.c | 109,243,291,210,227,210,000,000,000,000,000,000,000 | [
"CWE-755"
] | CVE-2017-11472 | The acpi_ns_terminate() function in drivers/acpi/acpica/nsutils.c in the Linux kernel before 4.12 does not flush the operand cache and causes a kernel stack dump, which allows local users to obtain sensitive information from kernel memory and bypass the KASLR protection mechanism (in the kernel through 4.9) via a crafted ACPI table. | https://nvd.nist.gov/vuln/detail/CVE-2017-11472 |
2,708 | ImageMagick | b007dd3a048097d8f58949297f5b434612e1e1a3 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/b007dd3a048097d8f58949297f5b434612e1e1a3 | None | 1 | ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 214,653,499,182,550,400,000,000,000,000,000,000,000 | None | null | [
"CWE-20"
] | CVE-2017-11449 | coders/mpc.c in ImageMagick before 7.0.6-1 does not enable seekable streams and thus cannot validate blob sizes, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via an image received from stdin. | https://nvd.nist.gov/vuln/detail/CVE-2017-11449 |
2,709 | ImageMagick | 1737ac82b335e53376382c07b9a500d73dd2aa11 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/1737ac82b335e53376382c07b9a500d73dd2aa11 | None | 1 | static Image *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*option;
ErrorManager
error_manager;
Image
*image;
IndexPacket
index;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
debug,
status;
MagickSizeType
number_pixels;
MemoryInfo
*memory_info;
register ssize_t
i;
struct jpeg_decompress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
register JSAMPLE
*p;
size_t
units;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
debug=IsEventLogging();
(void) debug;
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Verify that file size large enough to contain a JPEG datastream.
*/
if (GetBlobSize(image) < 107)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
memory_info=(MemoryInfo *) NULL;
error_manager.image=image;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_decompress(&jpeg_info);
if (error_manager.profile != (StringInfo *) NULL)
error_manager.profile=DestroyStringInfo(error_manager.profile);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
InheritException(exception,&image->exception);
return(DestroyImage(image));
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_decompress(&jpeg_info);
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
option=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
if (IsOptionMember("IPTC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
if (IsOptionMember("APP",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile);
i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE);
if ((image_info->colorspace == YCbCrColorspace) ||
(image_info->colorspace == Rec601YCbCrColorspace) ||
(image_info->colorspace == Rec709YCbCrColorspace))
jpeg_info.out_color_space=JCS_YCbCr;
/*
Set image resolution.
*/
units=0;
if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) &&
(jpeg_info.Y_density != 1))
{
image->x_resolution=(double) jpeg_info.X_density;
image->y_resolution=(double) jpeg_info.Y_density;
units=(size_t) jpeg_info.density_unit;
}
if (units == 1)
image->units=PixelsPerInchResolution;
if (units == 2)
image->units=PixelsPerCentimeterResolution;
number_pixels=(MagickSizeType) image->columns*image->rows;
option=GetImageOption(image_info,"jpeg:size");
if ((option != (const char *) NULL) &&
(jpeg_info.out_color_space != JCS_YCbCr))
{
double
scale_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Scale the image.
*/
flags=ParseGeometry(option,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
scale_factor=1.0;
if (geometry_info.rho != 0.0)
scale_factor=jpeg_info.output_width/geometry_info.rho;
if ((geometry_info.sigma != 0.0) &&
(scale_factor > (jpeg_info.output_height/geometry_info.sigma)))
scale_factor=jpeg_info.output_height/geometry_info.sigma;
jpeg_info.scale_num=1U;
jpeg_info.scale_denom=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Scale factor: %.20g",(double) scale_factor);
}
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if defined(D_LOSSLESS_SUPPORTED)
image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ?
JPEGInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'",
image->filename);
if (jpeg_info.data_precision == 16)
jpeg_info.data_precision=12;
#else
image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace :
NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=JPEGInterlace;
#endif
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
{
/*
Let the JPEG library quantize for us.
*/
jpeg_info.quantize_colors=TRUE;
jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option);
}
option=GetImageOption(image_info,"jpeg:block-smoothing");
if (option != (const char *) NULL)
jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:fancy-upsampling");
if (option != (const char *) NULL)
jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=(size_t) jpeg_info.data_precision;
switch (jpeg_info.out_color_space)
{
case JCS_RGB:
default:
{
(void) SetImageColorspace(image,sRGBColorspace);
break;
}
case JCS_GRAYSCALE:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
case JCS_YCbCr:
{
(void) SetImageColorspace(image,YCbCrColorspace);
break;
}
case JCS_CMYK:
{
(void) SetImageColorspace(image,CMYKColorspace);
break;
}
}
if (IsITUFaxImage(image) != MagickFalse)
{
(void) SetImageColorspace(image,LabColorspace);
jpeg_info.out_color_space=JCS_YCbCr;
}
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0))
{
size_t
colors;
colors=(size_t) GetQuantumRange(image->depth)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
}
if (image->debug != MagickFalse)
{
if (image->interlace != NoInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,(int) jpeg_info.output_height);
}
JPEGSetImageQuality(&jpeg_info,image);
JPEGSetImageSamplingFactor(&jpeg_info,image);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
jpeg_info.out_color_space);
(void) SetImageProperty(image,"jpeg:colorspace",value);
if (image_info->ping != MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) && (jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.output_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
/*
Convert JPEG pixels to pixel packets.
*/
if (setjmp(error_manager.error_recovery) != 0)
{
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
return(DestroyImage(image));
}
if (jpeg_info.quantize_colors != 0)
{
image->colors=(size_t) jpeg_info.actual_number_of_colors;
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=image->colormap[i].red;
image->colormap[i].blue=image->colormap[i].red;
image->colormap[i].opacity=OpaqueOpacity;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]);
image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]);
image->colormap[i].opacity=OpaqueOpacity;
}
}
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
continue;
}
p=jpeg_pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (jpeg_info.data_precision > 8)
{
unsigned short
scale;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
size_t
pixel;
pixel=(size_t) (scale*GETJSAMPLE(*p));
index=ConstrainColormapIndex(image,pixel);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum(
(unsigned char) GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
{
jpeg_abort_decompress(&jpeg_info);
break;
}
}
if (status != MagickFalse)
{
error_manager.finished=MagickTrue;
if (setjmp(error_manager.error_recovery) == 0)
(void) jpeg_finish_decompress(&jpeg_info);
}
/*
Free jpeg resources.
*/
jpeg_destroy_decompress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 139,760,603,405,269,560,000,000,000,000,000,000,000 | None | null | [
"CWE-200"
] | CVE-2017-11448 | The ReadJPEGImage function in coders/jpeg.c in ImageMagick before 7.0.6-1 allows remote attackers to obtain sensitive information from uninitialized memory locations via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-11448 |
2,710 | ImageMagick | 8c10b9247509c0484b55330458846115131ec2ae | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/8c10b9247509c0484b55330458846115131ec2ae | None | 1 | static Image *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
status=SetImageExtent(screen,screen->columns,screen->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
| 220,742,260,935,559,080,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-11447 | The ReadSCREENSHOTImage function in coders/screenshot.c in ImageMagick before 7.0.6-1 has memory leaks, causing denial of service. | https://nvd.nist.gov/vuln/detail/CVE-2017-11447 |
2,716 | yara | 4a342f01e5439b9bb901aff1c6c23c536baeeb3f | https://github.com/VirusTotal/yara | https://github.com/VirusTotal/yara/commit/4a342f01e5439b9bb901aff1c6c23c536baeeb3f | Fix heap overflow (reported by Jurriaan Bremer)
When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. | 1 | int yr_object_array_set_item(
YR_OBJECT* object,
YR_OBJECT* item,
int index)
{
YR_OBJECT_ARRAY* array;
int i;
int count;
assert(index >= 0);
assert(object->type == OBJECT_TYPE_ARRAY);
array = object_as_array(object);
if (array->items == NULL)
{
count = yr_max(64, (index + 1) * 2);
array->items = (YR_ARRAY_ITEMS*) yr_malloc(
sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*));
if (array->items == NULL)
return ERROR_INSUFFICIENT_MEMORY;
memset(array->items->objects, 0, count * sizeof(YR_OBJECT*));
array->items->count = count;
}
else if (index >= array->items->count)
{
count = array->items->count * 2;
array->items = (YR_ARRAY_ITEMS*) yr_realloc(
array->items,
sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*));
if (array->items == NULL)
return ERROR_INSUFFICIENT_MEMORY;
for (i = array->items->count; i < count; i++)
array->items->objects[i] = NULL;
array->items->count = count;
}
item->parent = object;
array->items->objects[index] = item;
return ERROR_SUCCESS;
}
| 226,909,454,874,264,900,000,000,000,000,000,000,000 | object.c | 256,017,910,395,129,500,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-11328 | Heap buffer overflow in the yr_object_array_set_item() function in object.c in YARA 3.x allows a denial-of-service attack by scanning a crafted .NET file. | https://nvd.nist.gov/vuln/detail/CVE-2017-11328 |
2,717 | ImageMagick | 8ca35831e91c3db8c6d281d09b605001003bec08 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/8ca35831e91c3db8c6d281d09b605001003bec08 | coders/png.c: Stop a memory leak in read_user_chunk_callback() (reference
https://github.com/ImageMagick/ImageMagick/issues/517). | 1 | static Image *ReadOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
/* Read one PNG image */
/* To do: Read the tEXt/Creation Time chunk into the date:create property */
Image
*image;
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
int
intent, /* "PNG Rendering intent", which is ICC intent + 1 */
num_raw_profiles,
num_text,
num_text_total,
num_passes,
number_colors,
pass,
ping_bit_depth,
ping_color_type,
ping_file_depth,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans,
unit_type;
double
file_gamma;
MagickBooleanType
logging,
ping_found_cHRM,
ping_found_gAMA,
ping_found_iCCP,
ping_found_sRGB,
ping_found_sRGB_cHRM,
ping_preserve_iCCP,
status;
MemoryInfo
*volatile pixel_info;
PixelInfo
transparent_color;
PNGErrorInfo
error_info;
png_bytep
ping_trans_alpha;
png_color_16p
ping_background,
ping_trans_color;
png_info
*end_info,
*ping_info;
png_struct
*ping;
png_textp
text;
png_uint_32
ping_height,
ping_width,
x_resolution,
y_resolution;
QuantumInfo
*quantum_info;
ssize_t
ping_rowbytes,
y;
register unsigned char
*p;
register ssize_t
i,
x;
register Quantum
*q;
size_t
length,
row_offset;
ssize_t
j;
unsigned char
*ping_pixels;
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_byte unused_chunks[]=
{
104, 73, 83, 84, (png_byte) '\0', /* hIST */
105, 84, 88, 116, (png_byte) '\0', /* iTXt */
112, 67, 65, 76, (png_byte) '\0', /* pCAL */
115, 67, 65, 76, (png_byte) '\0', /* sCAL */
115, 80, 76, 84, (png_byte) '\0', /* sPLT */
#if !defined(PNG_tIME_SUPPORTED)
116, 73, 77, 69, (png_byte) '\0', /* tIME */
#endif
#ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */
/* ignore the APNG chunks */
97, 99, 84, 76, (png_byte) '\0', /* acTL */
102, 99, 84, 76, (png_byte) '\0', /* fcTL */
102, 100, 65, 84, (png_byte) '\0', /* fdAT */
#endif
};
#endif
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,32);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,32);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOnePNGImage()\n"
" IM version = %s\n"
" Libpng version = %s",
im_vers, libpng_vers);
if (logging != MagickFalse)
{
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
#if (PNG_LIBPNG_VER >= 10400)
# ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */
if (image_info->verbose)
{
printf("Your PNG library (libpng-%s) is an old beta version.\n",
PNG_LIBPNG_VER_STRING);
printf("Please update it.\n");
}
# endif
#endif
quantum_info = (QuantumInfo *) NULL;
image=mng_info->image;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before reading:\n"
" image->alpha_trait=%d"
" image->rendering_intent=%d\n"
" image->colorspace=%d\n"
" image->gamma=%f",
(int) image->alpha_trait, (int) image->rendering_intent,
(int) image->colorspace, image->gamma);
}
intent=
Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent);
/* Set to an out-of-range color unless tRNS chunk is present */
transparent_color.red=65537;
transparent_color.green=65537;
transparent_color.blue=65537;
transparent_color.alpha=65537;
number_colors=0;
num_text = 0;
num_text_total = 0;
num_raw_profiles = 0;
ping_found_cHRM = MagickFalse;
ping_found_gAMA = MagickFalse;
ping_found_iCCP = MagickFalse;
ping_found_sRGB = MagickFalse;
ping_found_sRGB_cHRM = MagickFalse;
ping_preserve_iCCP = MagickFalse;
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler, NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
end_info=png_create_info_struct(ping);
if (end_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG image is corrupt.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() with error.");
return(GetFirstImageInList(image));
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for reading.
*/
mng_info->image_found++;
png_set_sig_bytes(ping,8);
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED)
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
png_set_read_fn(ping,image,png_get_data);
#else
#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED)
png_permit_empty_plte(ping,MagickTrue);
png_set_read_fn(ping,image,png_get_data);
#else
mng_info->image=image;
mng_info->bytes_in_read_buffer=0;
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
png_set_read_fn(ping,mng_info,mng_get_data);
#endif
#endif
}
else
png_set_read_fn(ping,image,png_get_data);
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",value) == MagickFalse)
{
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
ping_preserve_iCCP=MagickTrue;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
/* Don't let libpng check for ICC/sRGB profile because we're going
* to do that anyway. This feature was added at libpng-1.6.12.
* If logging, go ahead and check and issue a warning as appropriate.
*/
if (logging == MagickFalse)
png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
else
{
png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1);
}
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
/* Ignore unused chunks and all unknown chunks except for eXIf,
caNv, and vpAg */
# if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */
png_set_keep_unknown_chunks(ping, 2, NULL, 0);
# else
png_set_keep_unknown_chunks(ping, 1, NULL, 0);
# endif
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_eXIf, 1);
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1);
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1);
png_set_keep_unknown_chunks(ping, 1, unused_chunks,
(int)sizeof(unused_chunks)/5);
/* Callback for other unknown chunks */
png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
# if (PNG_LIBPNG_VER >= 10400)
/* Limit the size of the chunk storage cache used for sPLT, text,
* and unknown chunks.
*/
png_set_chunk_cache_max(ping, 32767);
# endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature */
png_set_check_for_invalid_index (ping, 0);
#endif
#if (PNG_LIBPNG_VER < 10400)
# if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
(PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__)
/* Disable thread-unsafe features of pnggccrd */
if (png_access_version_number() >= 10200)
{
png_uint_32 mmx_disable_mask=0;
png_uint_32 asm_flags;
mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
| PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
| PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
| PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
asm_flags=png_get_asm_flags(ping);
png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask);
}
# endif
#endif
png_read_info(ping,ping_info);
png_get_IHDR(ping,ping_info,&ping_width,&ping_height,
&ping_bit_depth,&ping_color_type,
&ping_interlace_method,&ping_compression_method,
&ping_filter_method);
ping_file_depth = ping_bit_depth;
/* Swap bytes if requested */
if (ping_file_depth == 16)
{
const char
*value;
value=GetImageOption(image_info,"png:swap-bytes");
if (value == NULL)
value=GetImageArtifact(image,"png:swap-bytes");
if (value != NULL)
png_set_swap(ping);
}
/* Save bit-depth and color-type in case we later want to write a PNG00 */
{
char
msg[MagickPathExtent];
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_color_type);
(void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_bit_depth);
(void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception);
}
(void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans,
&ping_trans_color);
(void) png_get_bKGD(ping, ping_info, &ping_background);
if (ping_bit_depth < 8)
{
png_set_packing(ping);
ping_bit_depth = 8;
}
image->depth=ping_bit_depth;
image->depth=GetImageQuantumDepth(image,MagickFalse);
image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
image->rendering_intent=UndefinedIntent;
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent);
(void) ResetMagickMemory(&image->chromaticity,0,
sizeof(image->chromaticity));
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG width: %.20g, height: %.20g\n"
" PNG color_type: %d, bit_depth: %d\n"
" PNG compression_method: %d\n"
" PNG interlace_method: %d, filter_method: %d",
(double) ping_width, (double) ping_height,
ping_color_type, ping_bit_depth,
ping_compression_method,
ping_interlace_method,ping_filter_method);
}
if (png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_gAMA))
{
ping_found_gAMA=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG gAMA chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
ping_found_cHRM=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG cHRM chunk.");
}
if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
ping_found_sRGB=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG sRGB chunk.");
}
#ifdef PNG_READ_iCCP_SUPPORTED
if (ping_found_iCCP !=MagickTrue &&
ping_found_sRGB != MagickTrue &&
png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_iCCP))
{
int
compression;
#if (PNG_LIBPNG_VER < 10500)
png_charp
info;
#else
png_bytep
info;
#endif
png_charp
name;
png_uint_32
profile_length;
(void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info,
&profile_length);
if (profile_length != 0)
{
StringInfo
*profile;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG iCCP chunk.");
profile=BlobToStringInfo(info,profile_length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "ICC profile is NULL");
profile=DestroyStringInfo(profile);
}
else
{
if (ping_preserve_iCCP == MagickFalse)
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
break;
}
}
}
if (sRGB_info[icheck].len == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
(void) SetImageProfile(image,"icc",profile,exception);
}
}
else /* Preserve-iCCP */
{
(void) SetImageProfile(image,"icc",profile,exception);
}
profile=DestroyStringInfo(profile);
}
}
}
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
{
if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
if (png_get_sRGB(ping,ping_info,&intent))
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent (intent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG sRGB chunk: rendering_intent: %d",intent);
}
}
else if (mng_info->have_global_srgb)
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent
(mng_info->global_srgb_intent);
}
}
#endif
{
if (!png_get_gAMA(ping,ping_info,&file_gamma))
if (mng_info->have_global_gama)
png_set_gAMA(ping,ping_info,mng_info->global_gamma);
if (png_get_gAMA(ping,ping_info,&file_gamma))
{
image->gamma=(float) file_gamma;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG gAMA chunk: gamma: %f",file_gamma);
}
}
if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
if (mng_info->have_global_chrm != MagickFalse)
{
(void) png_set_cHRM(ping,ping_info,
mng_info->global_chrm.white_point.x,
mng_info->global_chrm.white_point.y,
mng_info->global_chrm.red_primary.x,
mng_info->global_chrm.red_primary.y,
mng_info->global_chrm.green_primary.x,
mng_info->global_chrm.green_primary.y,
mng_info->global_chrm.blue_primary.x,
mng_info->global_chrm.blue_primary.y);
}
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
(void) png_get_cHRM(ping,ping_info,
&image->chromaticity.white_point.x,
&image->chromaticity.white_point.y,
&image->chromaticity.red_primary.x,
&image->chromaticity.red_primary.y,
&image->chromaticity.green_primary.x,
&image->chromaticity.green_primary.y,
&image->chromaticity.blue_primary.x,
&image->chromaticity.blue_primary.y);
ping_found_cHRM=MagickTrue;
if (image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f)
ping_found_sRGB_cHRM=MagickTrue;
}
if (image->rendering_intent != UndefinedIntent)
{
if (ping_found_sRGB != MagickTrue &&
(ping_found_gAMA != MagickTrue ||
(image->gamma > .45 && image->gamma < .46)) &&
(ping_found_cHRM != MagickTrue ||
ping_found_sRGB_cHRM != MagickFalse) &&
ping_found_iCCP != MagickTrue)
{
png_set_sRGB(ping,ping_info,
Magick_RenderingIntent_to_PNG_RenderingIntent
(image->rendering_intent));
file_gamma=1.000f/2.200f;
ping_found_sRGB=MagickTrue;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting sRGB as if in input");
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info);
image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info);
if (logging != MagickFalse)
if (image->page.x || image->page.y)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double)
image->page.x,(double) image->page.y);
}
#endif
#if defined(PNG_pHYs_SUPPORTED)
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
if (mng_info->have_global_phys)
{
png_set_pHYs(ping,ping_info,
mng_info->global_x_pixels_per_unit,
mng_info->global_y_pixels_per_unit,
mng_info->global_phys_unit_type);
}
}
x_resolution=0;
y_resolution=0;
unit_type=0;
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
/*
Set image resolution.
*/
(void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution,
&unit_type);
image->resolution.x=(double) x_resolution;
image->resolution.y=(double) y_resolution;
if (unit_type == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=(double) x_resolution/100.0;
image->resolution.y=(double) y_resolution/100.0;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) x_resolution,(double) y_resolution,unit_type);
}
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
if ((number_colors == 0) &&
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE))
{
if (mng_info->global_plte_length)
{
png_set_PLTE(ping,ping_info,mng_info->global_plte,
(int) mng_info->global_plte_length);
if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
if (mng_info->global_trns_length)
{
png_warning(ping,
"global tRNS has more entries than global PLTE");
}
else
{
png_set_tRNS(ping,ping_info,mng_info->global_trns,
(int) mng_info->global_trns_length,NULL);
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
mng_info->have_saved_bkgd_index ||
#endif
png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
png_color_16
background;
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
if (mng_info->have_saved_bkgd_index)
background.index=mng_info->saved_bkgd_index;
#endif
if (png_get_valid(ping, ping_info, PNG_INFO_bKGD))
background.index=ping_background->index;
background.red=(png_uint_16)
mng_info->global_plte[background.index].red;
background.green=(png_uint_16)
mng_info->global_plte[background.index].green;
background.blue=(png_uint_16)
mng_info->global_plte[background.index].blue;
background.gray=(png_uint_16)
mng_info->global_plte[background.index].green;
png_set_bKGD(ping,ping_info,&background);
}
#endif
}
else
png_error(ping,"No global PLTE in file");
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (mng_info->have_global_bkgd &&
(!png_get_valid(ping,ping_info,PNG_INFO_bKGD)))
image->background_color=mng_info->mng_global_bkgd;
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
unsigned int
bkgd_scale;
/* Set image background color.
* Scale background components to 16-bit, then scale
* to quantum depth
*/
bkgd_scale = 1;
if (ping_file_depth == 1)
bkgd_scale = 255;
else if (ping_file_depth == 2)
bkgd_scale = 85;
else if (ping_file_depth == 4)
bkgd_scale = 17;
if (ping_file_depth <= 8)
bkgd_scale *= 257;
ping_background->red *= bkgd_scale;
ping_background->green *= bkgd_scale;
ping_background->blue *= bkgd_scale;
if (logging != MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n"
" bkgd_scale=%d. ping_background=(%d,%d,%d)",
ping_background->red,ping_background->green,
ping_background->blue,
bkgd_scale,ping_background->red,
ping_background->green,ping_background->blue);
}
image->background_color.red=
ScaleShortToQuantum(ping_background->red);
image->background_color.green=
ScaleShortToQuantum(ping_background->green);
image->background_color.blue=
ScaleShortToQuantum(ping_background->blue);
image->background_color.alpha=OpaqueAlpha;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->background_color=(%.20g,%.20g,%.20g).",
(double) image->background_color.red,
(double) image->background_color.green,
(double) image->background_color.blue);
}
#endif /* PNG_READ_bKGD_SUPPORTED */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
/*
Image has a tRNS chunk.
*/
int
max_sample;
size_t
one=1;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG tRNS chunk.");
max_sample = (int) ((one << ping_file_depth) - 1);
if ((ping_color_type == PNG_COLOR_TYPE_GRAY &&
(int)ping_trans_color->gray > max_sample) ||
(ping_color_type == PNG_COLOR_TYPE_RGB &&
((int)ping_trans_color->red > max_sample ||
(int)ping_trans_color->green > max_sample ||
(int)ping_trans_color->blue > max_sample)))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Ignoring PNG tRNS chunk with out-of-range sample.");
png_free_data(ping, ping_info, PNG_FREE_TRNS, 0);
png_set_invalid(ping,ping_info,PNG_INFO_tRNS);
image->alpha_trait=UndefinedPixelTrait;
}
else
{
int
scale_to_short;
scale_to_short = 65535L/((1UL << ping_file_depth)-1);
/* Scale transparent_color to short */
transparent_color.red= scale_to_short*ping_trans_color->red;
transparent_color.green= scale_to_short*ping_trans_color->green;
transparent_color.blue= scale_to_short*ping_trans_color->blue;
transparent_color.alpha= scale_to_short*ping_trans_color->gray;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Raw tRNS graylevel = %d, scaled graylevel = %d.",
(int) ping_trans_color->gray,(int) transparent_color.alpha);
}
transparent_color.red=transparent_color.alpha;
transparent_color.green=transparent_color.alpha;
transparent_color.blue=transparent_color.alpha;
}
}
}
#if defined(PNG_READ_sBIT_SUPPORTED)
if (mng_info->have_global_sbit)
{
if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT))
png_set_sBIT(ping,ping_info,&mng_info->global_sbit);
}
#endif
num_passes=png_set_interlace_handling(ping);
png_read_update_info(ping,ping_info);
ping_rowbytes=png_get_rowbytes(ping,ping_info);
/*
Initialize image structure.
*/
mng_info->image_box.left=0;
mng_info->image_box.right=(ssize_t) ping_width;
mng_info->image_box.top=0;
mng_info->image_box.bottom=(ssize_t) ping_height;
if (mng_info->mng_type == 0)
{
mng_info->mng_width=ping_width;
mng_info->mng_height=ping_height;
mng_info->frame=mng_info->image_box;
mng_info->clip=mng_info->image_box;
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
image->compression=ZipCompression;
image->columns=ping_width;
image->rows=ping_height;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
double
image_gamma = image->gamma;
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%f",(float) image_gamma);
if (image_gamma > 0.75)
{
/* Set image->rendering_intent to Undefined,
* image->colorspace to GRAY, and reset image->chromaticity.
*/
image->intensity = Rec709LuminancePixelIntensityMethod;
SetImageColorspace(image,GRAYColorspace,exception);
}
else
{
RenderingIntent
save_rendering_intent = image->rendering_intent;
ChromaticityInfo
save_chromaticity = image->chromaticity;
SetImageColorspace(image,GRAYColorspace,exception);
image->rendering_intent = save_rendering_intent;
image->chromaticity = save_chromaticity;
}
image->gamma = image_gamma;
}
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace=%d",(int) image->colorspace);
if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
((int) ping_bit_depth < 16 &&
(int) ping_color_type == PNG_COLOR_TYPE_GRAY))
{
size_t
one;
image->storage_class=PseudoClass;
one=1;
image->colors=one << ping_file_depth;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->colors > 256)
image->colors=256;
#else
if (image->colors > 65536L)
image->colors=65536L;
#endif
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
image->colors=(size_t) number_colors;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG PLTE chunk: number_colors: %d.",number_colors);
}
}
if (image->storage_class == PseudoClass)
{
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
png_error(ping,"Memory allocation failed");
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(palette[i].red);
image->colormap[i].green=ScaleCharToQuantum(palette[i].green);
image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue);
}
for ( ; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=0;
image->colormap[i].green=0;
image->colormap[i].blue=0;
}
}
else
{
Quantum
scale;
scale = (Quantum) (65535.0/((1UL << ping_file_depth)-1.0));
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
scale = ScaleShortToQuantum(scale);
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(Quantum) (i*scale);
image->colormap[i].green=(Quantum) (i*scale);
image->colormap[i].blue=(Quantum) (i*scale);
}
}
}
/* Set some properties for reporting by "identify" */
{
char
msg[MagickPathExtent];
/* encode ping_width, ping_height, ping_file_depth, ping_color_type,
ping_interlace_method in value */
(void) FormatLocaleString(msg,MagickPathExtent,
"%d, %d",(int) ping_width, (int) ping_height);
(void) SetImageProperty(image,"png:IHDR.width,height",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_file_depth);
(void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)",
(int) ping_color_type,
Magick_ColorType_from_PNG_ColorType((int)ping_color_type));
(void) SetImageProperty(image,"png:IHDR.color_type",msg,exception);
if (ping_interlace_method == 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)",
(int) ping_interlace_method);
}
else if (ping_interlace_method == 1)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)",
(int) ping_interlace_method);
}
else
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)",
(int) ping_interlace_method);
}
(void) SetImageProperty(image,"png:IHDR.interlace_method",
msg,exception);
if (number_colors != 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) number_colors);
(void) SetImageProperty(image,"png:PLTE.number_colors",msg,
exception);
}
}
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,ping_info,exception);
#endif
/*
Read image scanlines.
*/
if (image->delay != 0)
mng_info->scenes_found++;
if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || (
(image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t)
(image_info->first_scene+image_info->number_scenes))))
{
/* This happens later in non-ping decodes */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
image->storage_class=DirectClass;
image->alpha_trait=
(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping PNG image data for scene %.20g",(double)
mng_info->scenes_found-1);
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage().");
return(image);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG IDAT chunk(s)");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (num_passes > 1)
pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes*
sizeof(*ping_pixels));
else
pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Memory allocation failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting PNG pixels to pixel packets");
/*
Convert PNG pixels to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Failed to allocate quantum_info");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
{
MagickBooleanType
found_transparent_pixel;
found_transparent_pixel=MagickFalse;
if (image->storage_class == DirectClass)
{
for (pass=0; pass < num_passes; pass++)
{
/*
Convert image to DirectClass pixel packets.
*/
image->alpha_trait=
(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
for (y=0; y < (ssize_t) image->rows; y++)
{
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayAlphaQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBAQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
IndexQuantum,ping_pixels+row_offset,exception);
else /* ping_color_type == PNG_COLOR_TYPE_RGB */
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBQuantum,ping_pixels+row_offset,exception);
if (found_transparent_pixel == MagickFalse)
{
/* Is there a transparent pixel in the row? */
if (y== 0 && logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Looking for cheap transparent pixel");
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if ((ping_color_type == PNG_COLOR_TYPE_RGBA ||
ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(GetPixelAlpha(image,q) != OpaqueAlpha))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
if ((ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_GRAY) &&
(ScaleQuantumToShort(GetPixelRed(image,q)) ==
transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(image,q)) ==
transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(image,q)) ==
transparent_color.blue))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
q+=GetPixelChannels(image);
}
}
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,
(MagickOffsetType) y, image->rows);
if (status == MagickFalse)
break;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
}
}
else /* image->storage_class != DirectClass */
for (pass=0; pass < num_passes; pass++)
{
Quantum
*quantum_scanline;
register Quantum
*r;
/*
Convert grayscale image to PseudoClass pixel packets.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting grayscale pixels to pixel packets");
image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ?
BlendPixelTrait : UndefinedPixelTrait;
quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns,
(image->alpha_trait == BlendPixelTrait? 2 : 1)*
sizeof(*quantum_scanline));
if (quantum_scanline == (Quantum *) NULL)
png_error(ping,"Memory allocation failed");
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
alpha;
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=ping_pixels+row_offset;
r=quantum_scanline;
switch (ping_bit_depth)
{
case 8:
{
if (ping_color_type == 4)
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
*r++=*p++;
alpha=ScaleCharToQuantum((unsigned char)*p++);
SetPixelAlpha(image,alpha,q);
if (alpha != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
q+=GetPixelChannels(image);
}
else
for (x=(ssize_t) image->columns-1; x >= 0; x--)
*r++=*p++;
break;
}
case 16:
{
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
unsigned short
quantum;
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
*r=ScaleShortToQuantum(quantum);
r++;
if (ping_color_type == 4)
{
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
alpha=ScaleShortToQuantum(quantum);
SetPixelAlpha(image,alpha,q);
if (alpha != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
q+=GetPixelChannels(image);
}
#else /* MAGICKCORE_QUANTUM_DEPTH == 8 */
*r++=(*p++);
p++; /* strip low byte */
if (ping_color_type == 4)
{
SetPixelAlpha(image,*p++,q);
if (GetPixelAlpha(image,q) != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
p++;
q+=GetPixelChannels(image);
}
#endif
}
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=quantum_scanline;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*r++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline);
}
image->alpha_trait=found_transparent_pixel ? BlendPixelTrait :
UndefinedPixelTrait;
if (logging != MagickFalse)
{
if (found_transparent_pixel != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found transparent pixel");
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No transparent pixel was found");
ping_color_type&=0x03;
}
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->storage_class == PseudoClass)
{
PixelTrait
alpha_trait;
alpha_trait=image->alpha_trait;
image->alpha_trait=UndefinedPixelTrait;
(void) SyncImage(image,exception);
image->alpha_trait=alpha_trait;
}
png_read_end(ping,end_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=%d\n",(int) image->storage_class);
}
if (image_info->number_scenes != 0 && mng_info->scenes_found-1 <
(ssize_t) image_info->first_scene && image->delay != 0)
{
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
image->colors=2;
(void) SetImageBackgroundColor(image,exception);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() early.");
return(image);
}
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
ClassType
storage_class;
/*
Image has a transparent background.
*/
storage_class=image->storage_class;
image->alpha_trait=BlendPixelTrait;
/* Balfour fix from imagemagick discourse server, 5 Feb 2010 */
if (storage_class == PseudoClass)
{
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
for (x=0; x < ping_num_trans; x++)
{
image->colormap[x].alpha_trait=BlendPixelTrait;
image->colormap[x].alpha =
ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]);
}
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
for (x=0; x < (int) image->colors; x++)
{
if (ScaleQuantumToShort(image->colormap[x].red) ==
transparent_color.alpha)
{
image->colormap[x].alpha_trait=BlendPixelTrait;
image->colormap[x].alpha = (Quantum) TransparentAlpha;
}
}
}
(void) SyncImage(image,exception);
}
#if 1 /* Should have already been done above, but glennrp problem P10
* needs this.
*/
else
{
for (y=0; y < (ssize_t) image->rows; y++)
{
image->storage_class=storage_class;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
/* Caution: on a Q8 build, this does not distinguish between
* 16-bit colors that differ only in the low byte
*/
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if (ScaleQuantumToShort(GetPixelRed(image,q)) ==
transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(image,q)) ==
transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(image,q)) ==
transparent_color.blue)
{
SetPixelAlpha(image,TransparentAlpha,q);
}
#if 0 /* I have not found a case where this is needed. */
else
{
SetPixelAlpha(image,q)=(Quantum) OpaqueAlpha;
}
#endif
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
image->storage_class=DirectClass;
}
for (j = 0; j < 2; j++)
{
if (j == 0)
status = png_get_text(ping,ping_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
else
status = png_get_text(ping,end_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
if (status != MagickFalse)
for (i=0; i < (ssize_t) num_text; i++)
{
/* Check for a profile */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG text chunk");
if (strlen(text[i].key) > 16 &&
memcmp(text[i].key, "Raw profile type ",17) == 0)
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember(text[i].key+17,value) == MagickFalse)
{
(void) Magick_png_read_raw_profile(ping,image,image_info,text,
(int) i,exception);
num_raw_profiles++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Read raw profile %s",text[i].key+17);
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping raw profile %s",text[i].key+17);
}
}
else
{
char
*value;
length=text[i].text_length;
value=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*value));
if (value == (char *) NULL)
{
png_error(ping,"Memory allocation failed");
break;
}
*value='\0';
(void) ConcatenateMagickString(value,text[i].text,length+2);
/* Don't save "density" or "units" property if we have a pHYs
* chunk
*/
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) ||
(LocaleCompare(text[i].key,"density") != 0 &&
LocaleCompare(text[i].key,"units") != 0))
(void) SetImageProperty(image,text[i].key,value,exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu\n"
" Keyword: %s",
(unsigned long) length,
text[i].key);
}
value=DestroyString(value);
}
}
num_text_total += num_text;
}
#ifdef MNG_OBJECT_BUFFERS
/*
Store the object if necessary.
*/
if (object_id && !mng_info->frozen[object_id])
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
{
/*
create a new object buffer.
*/
mng_info->ob[object_id]=(MngBuffer *)
AcquireMagickMemory(sizeof(MngBuffer));
if (mng_info->ob[object_id] != (MngBuffer *) NULL)
{
mng_info->ob[object_id]->image=(Image *) NULL;
mng_info->ob[object_id]->reference_count=1;
}
}
if ((mng_info->ob[object_id] == (MngBuffer *) NULL) ||
mng_info->ob[object_id]->frozen)
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
png_error(ping,"Memory allocation failed");
if (mng_info->ob[object_id]->frozen)
png_error(ping,"Cannot overwrite frozen MNG object buffer");
}
else
{
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image=DestroyImage
(mng_info->ob[object_id]->image);
mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue,
exception);
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image->file=(FILE *) NULL;
else
png_error(ping, "Cloning image for object buffer failed");
if (ping_width > 250000L || ping_height > 250000L)
png_error(ping,"PNG Image dimensions are too large.");
mng_info->ob[object_id]->width=ping_width;
mng_info->ob[object_id]->height=ping_height;
mng_info->ob[object_id]->color_type=ping_color_type;
mng_info->ob[object_id]->sample_depth=ping_bit_depth;
mng_info->ob[object_id]->interlace_method=ping_interlace_method;
mng_info->ob[object_id]->compression_method=
ping_compression_method;
mng_info->ob[object_id]->filter_method=ping_filter_method;
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
plte;
/*
Copy the PLTE to the object buffer.
*/
png_get_PLTE(ping,ping_info,&plte,&number_colors);
mng_info->ob[object_id]->plte_length=number_colors;
for (i=0; i < number_colors; i++)
{
mng_info->ob[object_id]->plte[i]=plte[i];
}
}
else
mng_info->ob[object_id]->plte_length=0;
}
}
#endif
/* Set image->alpha_trait to MagickTrue if the input colortype supports
* alpha or if a valid tRNS chunk is present, no matter whether there
* is actual transparency present.
*/
image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
#if 0 /* I'm not sure what's wrong here but it does not work. */
if (image->alpha_trait != UndefinedPixelTrait)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) SetImageType(image,GrayscaleAlphaType,exception);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteAlphaType,exception);
else
(void) SetImageType(image,TrueColorAlphaType,exception);
}
else
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) SetImageType(image,GrayscaleType,exception);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteType,exception);
else
(void) SetImageType(image,TrueColorType,exception);
}
#endif
/* Set more properties for identify to retrieve */
{
char
msg[MagickPathExtent];
if (num_text_total != 0)
{
/* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */
(void) FormatLocaleString(msg,MagickPathExtent,
"%d tEXt/zTXt/iTXt chunks were found", num_text_total);
(void) SetImageProperty(image,"png:text",msg,
exception);
}
if (num_raw_profiles != 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"%d were found", num_raw_profiles);
(void) SetImageProperty(image,"png:text-encoded profiles",msg,
exception);
}
/* cHRM chunk: */
if (ping_found_cHRM != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found (see Chromaticity, above)");
(void) SetImageProperty(image,"png:cHRM",msg,
exception);
}
/* bKGD chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found (see Background color, above)");
(void) SetImageProperty(image,"png:bKGD",msg,
exception);
}
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found");
#if defined(PNG_iCCP_SUPPORTED)
/* iCCP chunk: */
if (ping_found_iCCP != MagickFalse)
(void) SetImageProperty(image,"png:iCCP",msg,
exception);
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
(void) SetImageProperty(image,"png:tRNS",msg,
exception);
#if defined(PNG_sRGB_SUPPORTED)
/* sRGB chunk: */
if (ping_found_sRGB != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"intent=%d (%s)",
(int) intent,
Magick_RenderingIntentString_from_PNG_RenderingIntent(intent));
(void) SetImageProperty(image,"png:sRGB",msg,
exception);
}
#endif
/* gAMA chunk: */
if (ping_found_gAMA != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"gamma=%.8g (See Gamma, above)",
file_gamma);
(void) SetImageProperty(image,"png:gAMA",msg,
exception);
}
#if defined(PNG_pHYs_SUPPORTED)
/* pHYs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"x_res=%.10g, y_res=%.10g, units=%d",
(double) x_resolution,(double) y_resolution, unit_type);
(void) SetImageProperty(image,"png:pHYs",msg,
exception);
}
#endif
#if defined(PNG_oFFs_SUPPORTED)
/* oFFs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"x_off=%.20g, y_off=%.20g",
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:oFFs",msg,
exception);
}
#endif
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,end_info,exception);
#endif
/* caNv chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
(image->page.x != 0 || image->page.y != 0))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:caNv",msg,
exception);
}
/* vpAg chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"width=%.20g, height=%.20g",
(double) image->page.width,(double) image->page.height);
(void) SetImageProperty(image,"png:vpAg",msg,
exception);
}
}
/*
Relinquish resources.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block, revert to
* Throwing an Exception when an error occurs.
*/
return(image);
/* end of reading one PNG image */
}
| 6,716,675,637,673,233,000,000,000,000,000,000,000 | png.c | 228,033,773,830,255,870,000,000,000,000,000,000,000 | [
"CWE-772"
] | CVE-2017-11310 | The read_user_chunk_callback function in coders\png.c in ImageMagick 7.0.6-1 Q16 2017-06-21 (beta) has memory leak vulnerabilities via crafted PNG files. | https://nvd.nist.gov/vuln/detail/CVE-2017-11310 |
2,718 | linux | f991af3daabaecff34684fd51fac80319d1baad1 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/f991af3daabaecff34684fd51fac80319d1baad1 | mqueue: fix a use-after-free in sys_mq_notify()
The retry logic for netlink_attachskb() inside sys_mq_notify()
is nasty and vulnerable:
1) The sock refcnt is already released when retry is needed
2) The fd is controllable by user-space because we already
release the file refcnt
so we when retry but the fd has been just closed by user-space
during this small window, we end up calling netlink_detachskb()
on the error path which releases the sock again, later when
the user-space closes this socket a use-after-free could be
triggered.
Setting 'sock' to NULL here should be sufficient to fix it.
Reported-by: GeneBlue <geneblue.mail@gmail.com>
Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Manfred Spraul <manfred@colorfullife.com>
Cc: stable@kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> | 1 | static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification)
{
int ret;
struct fd f;
struct sock *sock;
struct inode *inode;
struct mqueue_inode_info *info;
struct sk_buff *nc;
audit_mq_notify(mqdes, notification);
nc = NULL;
sock = NULL;
if (notification != NULL) {
if (unlikely(notification->sigev_notify != SIGEV_NONE &&
notification->sigev_notify != SIGEV_SIGNAL &&
notification->sigev_notify != SIGEV_THREAD))
return -EINVAL;
if (notification->sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification->sigev_signo)) {
return -EINVAL;
}
if (notification->sigev_notify == SIGEV_THREAD) {
long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
if (!nc) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(nc->data,
notification->sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
ret = -EFAULT;
goto out;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN);
/* and attach it to the socket */
retry:
f = fdget(notification->sigev_signo);
if (!f.file) {
ret = -EBADF;
goto out;
}
sock = netlink_getsockbyfilp(f.file);
fdput(f);
if (IS_ERR(sock)) {
ret = PTR_ERR(sock);
sock = NULL;
goto out;
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL);
if (ret == 1)
goto retry;
if (ret) {
sock = NULL;
nc = NULL;
goto out;
}
}
}
f = fdget(mqdes);
if (!f.file) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
ret = 0;
spin_lock(&info->lock);
if (notification == NULL) {
if (info->notify_owner == task_tgid(current)) {
remove_notification(info);
inode->i_atime = inode->i_ctime = current_time(inode);
}
} else if (info->notify_owner != NULL) {
ret = -EBUSY;
} else {
switch (notification->sigev_notify) {
case SIGEV_NONE:
info->notify.sigev_notify = SIGEV_NONE;
break;
case SIGEV_THREAD:
info->notify_sock = sock;
info->notify_cookie = nc;
sock = NULL;
nc = NULL;
info->notify.sigev_notify = SIGEV_THREAD;
break;
case SIGEV_SIGNAL:
info->notify.sigev_signo = notification->sigev_signo;
info->notify.sigev_value = notification->sigev_value;
info->notify.sigev_notify = SIGEV_SIGNAL;
break;
}
info->notify_owner = get_pid(task_tgid(current));
info->notify_user_ns = get_user_ns(current_user_ns());
inode->i_atime = inode->i_ctime = current_time(inode);
}
spin_unlock(&info->lock);
out_fput:
fdput(f);
out:
if (sock)
netlink_detachskb(sock, nc);
else if (nc)
dev_kfree_skb(nc);
return ret;
}
| 64,115,780,527,379,680,000,000,000,000,000,000,000 | mqueue.c | 183,724,114,749,802,100,000,000,000,000,000,000,000 | [
"CWE-416"
] | CVE-2017-11176 | The mq_notify function in the Linux kernel through 4.11.9 does not set the sock pointer to NULL upon entry into the retry logic. During a user-space close of a Netlink socket, it allows attackers to cause a denial of service (use-after-free) or possibly have unspecified other impact. | https://nvd.nist.gov/vuln/detail/CVE-2017-11176 |
2,721 | gnome-session | b0dc999e0b45355314616321dbb6cb71e729fc9d | https://github.com/GNOME/gnome-session | https://github.com/GNOME/gnome-session/commit/b0dc999e0b45355314616321dbb6cb71e729fc9d | [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211 | 1 | accept_ice_connection (GIOChannel *source,
GIOCondition condition,
GsmIceConnectionData *data)
{
IceListenObj listener;
IceConn ice_conn;
IceAcceptStatus status;
GsmClient *client;
GsmXsmpServer *server;
listener = data->listener;
server = data->server;
g_debug ("GsmXsmpServer: accept_ice_connection()");
ice_conn = IceAcceptConnection (listener, &status);
if (status != IceAcceptSuccess) {
g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status);
return TRUE;
}
client = gsm_xsmp_client_new (ice_conn);
ice_conn->context = client;
gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client));
/* the store will own the ref */
g_object_unref (client);
return TRUE;
}
| 115,853,477,812,783,840,000,000,000,000,000,000,000 | gsm-xsmp-server.c | 139,028,771,084,308,010,000,000,000,000,000,000,000 | [
"CWE-835"
] | CVE-2017-11171 | Bad reference counting in the context of accept_ice_connection() in gsm-xsmp-server.c in old versions of gnome-session up until version 2.29.92 allows a local attacker to establish ICE connections to gnome-session with invalid authentication data (an invalid magic cookie). Each failed authentication attempt will leak a file descriptor in gnome-session. When the maximum number of file descriptors is exhausted in the gnome-session process, it will enter an infinite loop trying to communicate without success, consuming 100% of the CPU. The graphical session associated with the gnome-session process will stop working correctly, because communication with gnome-session is no longer possible. | https://nvd.nist.gov/vuln/detail/CVE-2017-11171 |
2,725 | radare2 | c57997e76ec70862174a1b3b3aeb62a6f8570e85 | https://github.com/radare/radare2 | https://github.com/radare/radare2/commit/c57997e76ec70862174a1b3b3aeb62a6f8570e85 | Fix r2_hbo_grub_memmove ext2 crash | 1 | grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf)
{
char *tmp_buf;
unsigned real_offset;
/* First of all, check if the region is within the disk. */
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n",
(unsigned long long) sector, grub_errmsg);
grub_error_pop ();
return grub_errno;
}
real_offset = offset;
/* Allocate a temporary buffer. */
tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! tmp_buf)
return grub_errno;
/* Until SIZE is zero... */
while (size)
{
char *data;
grub_disk_addr_t start_sector;
grub_size_t len;
grub_size_t pos;
/* For reading bulk data. */
start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1);
pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS;
len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS)
- pos - real_offset);
if (len > size)
len = size;
/* Fetch the cache. */
data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector);
if (data)
{
/* Just copy it! */
if (buf)
grub_memcpy (buf, data + pos + real_offset, len);
grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector);
}
else
{
/* Otherwise read data from the disk actually. */
if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors
|| (disk->dev->read) (disk, start_sector,
GRUB_DISK_CACHE_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
/* Uggh... Failed. Instead, just read necessary data. */
unsigned num;
char *p;
grub_errno = GRUB_ERR_NONE;
num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS);
p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS);
if (!p)
goto finish;
tmp_buf = p;
if ((disk->dev->read) (disk, sector, num, tmp_buf))
{
grub_error_push ();
grub_dprintf ("disk", "%s read failed\n", disk->name);
grub_error_pop ();
goto finish;
}
if (buf)
grub_memcpy (buf, tmp_buf + real_offset, size);
/* Call the read hook, if any. */
if (disk->read_hook)
while (size)
{
grub_size_t to_read;
to_read = size;
if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE)
to_read = GRUB_DISK_SECTOR_SIZE - real_offset;
(disk->read_hook) (sector, real_offset,
to_read, disk->closure);
if (grub_errno != GRUB_ERR_NONE)
goto finish;
sector++;
size -= to_read;
real_offset = 0;
}
/* This must be the end. */
goto finish;
}
/* Copy it and store it in the disk cache. */
if (buf)
grub_memcpy (buf, tmp_buf + pos + real_offset, len);
grub_disk_cache_store (disk->dev->id, disk->id,
start_sector, tmp_buf);
}
/* Call the read hook, if any. */
if (disk->read_hook)
{
grub_disk_addr_t s = sector;
grub_size_t l = len;
while (l)
{
(disk->read_hook) (s, real_offset,
((l > GRUB_DISK_SECTOR_SIZE)
? GRUB_DISK_SECTOR_SIZE
: l), disk->closure);
if (l < GRUB_DISK_SECTOR_SIZE - real_offset)
break;
s++;
l -= GRUB_DISK_SECTOR_SIZE - real_offset;
real_offset = 0;
}
}
sector = start_sector + GRUB_DISK_CACHE_SIZE;
if (buf)
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
finish:
grub_free (tmp_buf);
return grub_errno;
}
| 303,262,332,284,339,200,000,000,000,000,000,000,000 | disk.c | 311,683,975,526,626,800,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-10929 | The grub_memmove function in shlr/grub/kern/misc.c in radare2 1.5.0 allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted binary file, possibly related to a read overflow in the grub_disk_read_small_real function in kern/disk.c in GNU GRUB 2.02. | https://nvd.nist.gov/vuln/detail/CVE-2017-10929 |
2,726 | linux | 089bc0143f489bd3a4578bdff5f4ca68fb26f341 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/089bc0143f489bd3a4578bdff5f4ca68fb26f341 | xen-blkback: don't leak stack data via response ring
Rather than constructing a local structure instance on the stack, fill
the fields directly on the shared ring, just like other backends do.
Build on the fact that all response structure flavors are actually
identical (the old code did make this assumption too).
This is XSA-216.
Cc: stable@vger.kernel.org
Signed-off-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> | 1 | static void make_response(struct xen_blkif_ring *ring, u64 id,
unsigned short op, int st)
{
struct blkif_response resp;
unsigned long flags;
union blkif_back_rings *blk_rings;
int notify;
resp.id = id;
resp.operation = op;
resp.status = st;
spin_lock_irqsave(&ring->blk_ring_lock, flags);
blk_rings = &ring->blk_rings;
/* Place on the response ring for the relevant domain. */
switch (ring->blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(RING_GET_RESPONSE(&blk_rings->native, blk_rings->native.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_32:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_32, blk_rings->x86_32.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_64:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_64, blk_rings->x86_64.rsp_prod_pvt),
&resp, sizeof(resp));
break;
default:
BUG();
}
blk_rings->common.rsp_prod_pvt++;
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blk_rings->common, notify);
spin_unlock_irqrestore(&ring->blk_ring_lock, flags);
if (notify)
notify_remote_via_irq(ring->irq);
}
| 3,010,677,516,050,940,000,000,000,000,000,000,000 | blkback.c | 154,573,801,860,346,860,000,000,000,000,000,000,000 | [
"CWE-200"
] | CVE-2017-10911 | The make_response function in drivers/block/xen-blkback/blkback.c in the Linux kernel before 4.11.8 allows guest OS users to obtain sensitive information from host OS (or other guest OS) kernel memory by leveraging the copying of uninitialized padding fields in Xen block-interface response structures, aka XSA-216. | https://nvd.nist.gov/vuln/detail/CVE-2017-10911 |
2,727 | linux | 385aee965b4e4c36551c362a334378d2985b722a | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/385aee965b4e4c36551c362a334378d2985b722a | drm/virtio: don't leak bo on drm_gem_object_init failure
Reported-by: 李强 <liqiang6-s@360.cn>
Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
Link: http://patchwork.freedesktop.org/patch/msgid/20170406155941.458-1-kraxel@redhat.com | 1 | int virtio_gpu_object_create(struct virtio_gpu_device *vgdev,
unsigned long size, bool kernel, bool pinned,
struct virtio_gpu_object **bo_ptr)
{
struct virtio_gpu_object *bo;
enum ttm_bo_type type;
size_t acc_size;
int ret;
if (kernel)
type = ttm_bo_type_kernel;
else
type = ttm_bo_type_device;
*bo_ptr = NULL;
acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size,
sizeof(struct virtio_gpu_object));
bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
size = roundup(size, PAGE_SIZE);
ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size);
if (ret != 0)
return ret;
bo->dumb = false;
virtio_gpu_init_ttm_placement(bo, pinned);
ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type,
&bo->placement, 0, !kernel, NULL, acc_size,
NULL, NULL, &virtio_gpu_ttm_bo_destroy);
/* ttm_bo_init failure will call the destroy */
if (ret != 0)
return ret;
*bo_ptr = bo;
return 0;
}
| 94,677,181,086,707,980,000,000,000,000,000,000,000 | virtgpu_object.c | 7,738,869,874,472,682,000,000,000,000,000,000,000 | [
"CWE-772"
] | CVE-2017-10810 | Memory leak in the virtio_gpu_object_create function in drivers/gpu/drm/virtio/virtgpu_object.c in the Linux kernel through 4.11.8 allows attackers to cause a denial of service (memory consumption) by triggering object-initialization failures. | https://nvd.nist.gov/vuln/detail/CVE-2017-10810 |
2,730 | sthttpd | c0dc63a49d8605649f1d8e4a96c9b468b0bff660 | https://github.com/blueness/sthttpd | https://github.com/blueness/sthttpd/commit/c0dc63a49d8605649f1d8e4a96c9b468b0bff660 | Fix heap buffer overflow in de_dotdot | 1 | de_dotdot( char* file )
{
char* cp;
char* cp2;
int l;
/* Collapse any multiple / sequences. */
while ( ( cp = strstr( file, "//") ) != (char*) 0 )
{
for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
continue;
(void) strcpy( cp + 1, cp2 );
}
/* Remove leading ./ and any /./ sequences. */
while ( strncmp( file, "./", 2 ) == 0 )
(void) memmove( file, file + 2, strlen( file ) - 1 );
while ( ( cp = strstr( file, "/./") ) != (char*) 0 )
(void) memmove( cp, cp + 2, strlen( file ) - 1 );
/* Alternate between removing leading ../ and removing xxx/../ */
for (;;)
{
while ( strncmp( file, "../", 3 ) == 0 )
(void) memmove( file, file + 3, strlen( file ) - 2 );
cp = strstr( file, "/../" );
if ( cp == (char*) 0 )
break;
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
(void) strcpy( cp2 + 1, cp + 4 );
}
/* Also elide any xxx/.. at the end. */
while ( ( l = strlen( file ) ) > 3 &&
strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
{
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
if ( cp2 < file )
break;
*cp2 = '\0';
}
}
| 45,843,749,197,328,700,000,000,000,000,000,000,000 | None | null | [
"CWE-119"
] | CVE-2017-10671 | Heap-based Buffer Overflow in the de_dotdot function in libhttpd.c in sthttpd before 2.27.1 allows remote attackers to cause a denial of service (daemon crash) or possibly have unspecified other impact via a crafted filename. | https://nvd.nist.gov/vuln/detail/CVE-2017-10671 |
2,731 | linux | 15d3042a937c13f5d9244241c7a9c8416ff6e82a | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/15d3042a937c13f5d9244241c7a9c8416ff6e82a | f2fs: sanity check checkpoint segno and blkoff
Make sure segno and blkoff read from raw image are valid.
Cc: stable@vger.kernel.org
Signed-off-by: Jin Qian <jinqian@google.com>
[Jaegeuk Kim: adjust minor coding style]
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> | 1 | int sanity_check_ckpt(struct f2fs_sb_info *sbi)
{
unsigned int total, fsmeta;
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned int ovp_segments, reserved_segments;
total = le32_to_cpu(raw_super->segment_count);
fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
fsmeta += le32_to_cpu(raw_super->segment_count_sit);
fsmeta += le32_to_cpu(raw_super->segment_count_nat);
fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
if (unlikely(fsmeta >= total))
return 1;
ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
ovp_segments == 0 || reserved_segments == 0)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Wrong layout: check mkfs.f2fs version");
return 1;
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
return 1;
}
return 0;
}
| 300,134,534,374,965,750,000,000,000,000,000,000,000 | super.c | 152,243,762,551,827,040,000,000,000,000,000,000,000 | [
"CWE-129"
] | CVE-2017-10663 | The sanity_check_ckpt function in fs/f2fs/super.c in the Linux kernel before 4.12.4 does not validate the blkoff and segno arrays, which allows local users to gain privileges via unspecified vectors. | https://nvd.nist.gov/vuln/detail/CVE-2017-10663 |
2,732 | linux | b9dd46188edc2f0d1f37328637860bb65a771124 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/b9dd46188edc2f0d1f37328637860bb65a771124 | f2fs: sanity check segment count
F2FS uses 4 bytes to represent block address. As a result, supported
size of disk is 16 TB and it equals to 16 * 1024 * 1024 / 2 segments.
Signed-off-by: Jin Qian <jinqian@google.com>
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> | 1 | static int sanity_check_raw_super(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
unsigned int blocksize;
if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
f2fs_msg(sb, KERN_INFO,
"Magic Mismatch, valid(0x%x) - read(0x%x)",
F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
return 1;
}
/* Currently, support only 4KB page cache size */
if (F2FS_BLKSIZE != PAGE_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid page_cache_size (%lu), supports only 4KB\n",
PAGE_SIZE);
return 1;
}
/* Currently, support only 4KB block size */
blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
if (blocksize != F2FS_BLKSIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid blocksize (%u), supports only 4KB\n",
blocksize);
return 1;
}
/* check log blocks per segment */
if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
f2fs_msg(sb, KERN_INFO,
"Invalid log blocks per segment (%u)\n",
le32_to_cpu(raw_super->log_blocks_per_seg));
return 1;
}
/* Currently, support 512/1024/2048/4096 bytes sector size */
if (le32_to_cpu(raw_super->log_sectorsize) >
F2FS_MAX_LOG_SECTOR_SIZE ||
le32_to_cpu(raw_super->log_sectorsize) <
F2FS_MIN_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)",
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
if (le32_to_cpu(raw_super->log_sectors_per_block) +
le32_to_cpu(raw_super->log_sectorsize) !=
F2FS_MAX_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid log sectors per block(%u) log sectorsize(%u)",
le32_to_cpu(raw_super->log_sectors_per_block),
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
/* check reserved ino info */
if (le32_to_cpu(raw_super->node_ino) != 1 ||
le32_to_cpu(raw_super->meta_ino) != 2 ||
le32_to_cpu(raw_super->root_ino) != 3) {
f2fs_msg(sb, KERN_INFO,
"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
le32_to_cpu(raw_super->node_ino),
le32_to_cpu(raw_super->meta_ino),
le32_to_cpu(raw_super->root_ino));
return 1;
}
/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
if (sanity_check_area_boundary(sbi, bh))
return 1;
return 0;
}
| 308,343,461,471,708,700,000,000,000,000,000,000,000 | super.c | 300,133,004,536,822,700,000,000,000,000,000,000,000 | [
"CWE-284"
] | CVE-2017-10662 | The sanity_check_raw_super function in fs/f2fs/super.c in the Linux kernel before 4.11.1 does not validate the segment count, which allows local users to gain privileges via unspecified vectors. | https://nvd.nist.gov/vuln/detail/CVE-2017-10662 |
2,735 | FFmpeg | 1e42736b95065c69a7481d0cf55247024f54b660 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/1e42736b95065c69a7481d0cf55247024f54b660 | avcodec/cdxl: Check format for BGR24
Fixes: out of array access
Fixes: 1427/clusterfuzz-testcase-minimized-5020737339392000
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int cdxl_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *pkt)
{
CDXLVideoContext *c = avctx->priv_data;
AVFrame * const p = data;
int ret, w, h, encoding, aligned_width, buf_size = pkt->size;
const uint8_t *buf = pkt->data;
if (buf_size < 32)
return AVERROR_INVALIDDATA;
encoding = buf[1] & 7;
c->format = buf[1] & 0xE0;
w = AV_RB16(&buf[14]);
h = AV_RB16(&buf[16]);
c->bpp = buf[19];
c->palette_size = AV_RB16(&buf[20]);
c->palette = buf + 32;
c->video = c->palette + c->palette_size;
c->video_size = buf_size - c->palette_size - 32;
if (c->palette_size > 512)
return AVERROR_INVALIDDATA;
if (buf_size < c->palette_size + 32)
return AVERROR_INVALIDDATA;
if (c->bpp < 1)
return AVERROR_INVALIDDATA;
if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) {
avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
return ret;
if (c->format == CHUNKY)
aligned_width = avctx->width;
else
aligned_width = FFALIGN(c->avctx->width, 16);
c->padded_bits = aligned_width - c->avctx->width;
if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8)
return AVERROR_INVALIDDATA;
if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) {
avctx->pix_fmt = AV_PIX_FMT_PAL8;
} else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) {
if (c->palette_size != (1 << (c->bpp - 1)))
return AVERROR_INVALIDDATA;
avctx->pix_fmt = AV_PIX_FMT_BGR24;
} else if (!encoding && c->bpp == 24 && c->format == CHUNKY &&
!c->palette_size) {
avctx->pix_fmt = AV_PIX_FMT_RGB24;
} else {
avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x",
encoding, c->bpp, c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
p->pict_type = AV_PICTURE_TYPE_I;
if (encoding) {
av_fast_padded_malloc(&c->new_video, &c->new_video_size,
h * w + AV_INPUT_BUFFER_PADDING_SIZE);
if (!c->new_video)
return AVERROR(ENOMEM);
if (c->bpp == 8)
cdxl_decode_ham8(c, p);
else
cdxl_decode_ham6(c, p);
} else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
cdxl_decode_rgb(c, p);
} else {
cdxl_decode_raw(c, p);
}
*got_frame = 1;
return buf_size;
}
| 272,076,656,890,640,220,000,000,000,000,000,000,000 | cdxl.c | 286,646,798,604,789,030,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9996 | The cdxl_decode_frame function in libavcodec/cdxl.c in FFmpeg 2.8.x before 2.8.12, 3.0.x before 3.0.8, 3.1.x before 3.1.8, 3.2.x before 3.2.5, and 3.3.x before 3.3.1 does not exclude the CHUNKY format, which allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9996 |
2,736 | FFmpeg | 7ac5067146613997bb38442cb022d7f41321a706 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/7ac5067146613997bb38442cb022d7f41321a706 | avcodec/scpr: Check y in first line loop in decompress_i()
Fixes: out of array access
Fixes: 1478/clusterfuzz-testcase-minimized-5285486908145664
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize)
{
SCPRContext *s = avctx->priv_data;
GetByteContext *gb = &s->gb;
int cx = 0, cx1 = 0, k = 0, clr = 0;
int run, r, g, b, off, y = 0, x = 0, z, ret;
unsigned backstep = linesize - avctx->width;
const int cxshift = s->cxshift;
unsigned lx, ly, ptype;
reinit_tables(s);
bytestream2_skip(gb, 2);
init_rangecoder(&s->rc, gb);
while (k < avctx->width + 1) {
ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = r >> cxshift;
ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = g >> cxshift;
ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = b >> cxshift;
ret = decode_value(s, s->run_model[0], 256, 400, &run);
if (ret < 0)
return ret;
clr = (b << 16) + (g << 8) + r;
k += run;
while (run-- > 0) {
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
}
off = -linesize - 1;
ptype = 0;
while (x < avctx->width && y < avctx->height) {
ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);
if (ret < 0)
return ret;
if (ptype == 0) {
ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = r >> cxshift;
ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = g >> cxshift;
ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);
if (ret < 0)
return ret;
clr = (b << 16) + (g << 8) + r;
}
if (ptype > 5)
return AVERROR_INVALIDDATA;
ret = decode_value(s, s->run_model[ptype], 256, 400, &run);
if (ret < 0)
return ret;
switch (ptype) {
case 0:
while (run-- > 0) {
if (y >= avctx->height)
return AVERROR_INVALIDDATA;
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 1:
while (run-- > 0) {
if (y >= avctx->height)
return AVERROR_INVALIDDATA;
dst[y * linesize + x] = dst[ly * linesize + lx];
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
clr = dst[ly * linesize + lx];
break;
case 2:
while (run-- > 0) {
if (y < 1 || y >= avctx->height)
return AVERROR_INVALIDDATA;
clr = dst[y * linesize + x + off + 1];
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 4:
while (run-- > 0) {
uint8_t *odst = (uint8_t *)dst;
if (y < 1 || y >= avctx->height ||
(y == 1 && x == 0))
return AVERROR_INVALIDDATA;
if (x == 0) {
z = backstep;
} else {
z = 0;
}
r = odst[(ly * linesize + lx) * 4] +
odst[((y * linesize + x) + off - z) * 4 + 4] -
odst[((y * linesize + x) + off - z) * 4];
g = odst[(ly * linesize + lx) * 4 + 1] +
odst[((y * linesize + x) + off - z) * 4 + 5] -
odst[((y * linesize + x) + off - z) * 4 + 1];
b = odst[(ly * linesize + lx) * 4 + 2] +
odst[((y * linesize + x) + off - z) * 4 + 6] -
odst[((y * linesize + x) + off - z) * 4 + 2];
clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 5:
while (run-- > 0) {
if (y < 1 || y >= avctx->height ||
(y == 1 && x == 0))
return AVERROR_INVALIDDATA;
if (x == 0) {
z = backstep;
} else {
z = 0;
}
clr = dst[y * linesize + x + off - z];
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
}
if (avctx->bits_per_coded_sample == 16) {
cx1 = (clr & 0x3F00) >> 2;
cx = (clr & 0xFFFFFF) >> 16;
} else {
cx1 = (clr & 0xFC00) >> 4;
cx = (clr & 0xFFFFFF) >> 18;
}
}
return 0;
}
| 183,761,881,120,239,970,000,000,000,000,000,000,000 | scpr.c | 289,050,571,695,209,180,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9995 | libavcodec/scpr.c in FFmpeg 3.3 before 3.3.1 does not properly validate height and width data, which allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9995 |
2,738 | FFmpeg | 6b5d3fb26fb4be48e4966e4b1d97c2165538d4ef | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/6b5d3fb26fb4be48e4966e4b1d97c2165538d4ef | avcodec/webp: Always set pix_fmt
Fixes: out of array access
Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632
Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Reviewed-by: "Ronald S. Bultje" <rsbultje@gmail.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,
int *got_frame, uint8_t *data_start,
unsigned int data_size)
{
WebPContext *s = avctx->priv_data;
AVPacket pkt;
int ret;
if (!s->initialized) {
ff_vp8_decode_init(avctx);
s->initialized = 1;
if (s->has_alpha)
avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
}
s->lossless = 0;
if (data_size > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");
return AVERROR_PATCHWELCOME;
}
av_init_packet(&pkt);
pkt.data = data_start;
pkt.size = data_size;
ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);
if (ret < 0)
return ret;
update_canvas_size(avctx, avctx->width, avctx->height);
if (s->has_alpha) {
ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,
s->alpha_data_size);
if (ret < 0)
return ret;
}
return ret;
}
| 92,038,738,073,539,860,000,000,000,000,000,000,000 | webp.c | 318,309,543,806,629,500,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9994 | libavcodec/webp.c in FFmpeg before 2.8.12, 3.0.x before 3.0.8, 3.1.x before 3.1.8, 3.2.x before 3.2.5, and 3.3.x before 3.3.1 does not ensure that pix_fmt is set, which allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted file, related to the vp8_decode_mb_row_no_filter and pred8x8_128_dc_8_c functions. | https://nvd.nist.gov/vuln/detail/CVE-2017-9994 |
2,739 | FFmpeg | a5d849b149ca67ced2d271dc84db0bc95a548abb | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/a5d849b149ca67ced2d271dc84db0bc95a548abb | avformat/avidec: Limit formats in gab2 to srt and ass/ssa
This prevents part of one exploit leading to an information leak
Found-by: Emil Lerner and Pavel Cheremushkin
Reported-by: Thierry Foucu <tfoucu@google.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
if (pkt->size >= 7 &&
pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
uint8_t desc[256];
int score = AVPROBE_SCORE_EXTENSION, ret;
AVIStream *ast = st->priv_data;
AVInputFormat *sub_demuxer;
AVRational time_base;
int size;
AVIOContext *pb = avio_alloc_context(pkt->data + 7,
pkt->size - 7,
0, NULL, NULL, NULL, NULL);
AVProbeData pd;
unsigned int desc_len = avio_rl32(pb);
if (desc_len > pb->buf_end - pb->buf_ptr)
goto error;
ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
avio_skip(pb, desc_len - ret);
if (*desc)
av_dict_set(&st->metadata, "title", desc, 0);
avio_rl16(pb); /* flags? */
avio_rl32(pb); /* data size */
size = pb->buf_end - pb->buf_ptr;
pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
.buf_size = size };
if (!pd.buf)
goto error;
memcpy(pd.buf, pb->buf_ptr, size);
sub_demuxer = av_probe_input_format2(&pd, 1, &score);
av_freep(&pd.buf);
if (!sub_demuxer)
goto error;
if (!(ast->sub_ctx = avformat_alloc_context()))
goto error;
ast->sub_ctx->pb = pb;
if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
goto error;
if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
if (ast->sub_ctx->nb_streams != 1)
goto error;
ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
time_base = ast->sub_ctx->streams[0]->time_base;
avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
}
ast->sub_buffer = pkt->data;
memset(pkt, 0, sizeof(*pkt));
return 1;
error:
av_freep(&ast->sub_ctx);
av_freep(&pb);
}
return 0;
}
| 57,648,922,262,249,090,000,000,000,000,000,000,000 | None | null | [
"CWE-200"
] | CVE-2017-9993 | FFmpeg before 2.8.12, 3.0.x and 3.1.x before 3.1.9, 3.2.x before 3.2.6, and 3.3.x before 3.3.2 does not properly restrict HTTP Live Streaming filename extensions and demuxer names, which allows attackers to read arbitrary files via crafted playlist data. | https://nvd.nist.gov/vuln/detail/CVE-2017-9993 |
2,740 | FFmpeg | f52fbf4f3ed02a7d872d8a102006f29b4421f360 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/f52fbf4f3ed02a7d872d8a102006f29b4421f360 | avcodec/dfa: Fix off by 1 error
Fixes out of array access
Fixes: 1345/clusterfuzz-testcase-minimized-6062963045695488
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int i, v, offset, count, segments;
segments = bytestream2_get_le16(gb);
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 2;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count*2 + width)
return AVERROR_INVALIDDATA;
for (i = 0; i < count; i++) {
frame[0] = frame[1] =
frame[width] = frame[width + 1] = frame[-offset];
frame += 2;
}
} else if (bitbuf & (mask << 1)) {
v = bytestream2_get_le16(gb)*2;
if (frame - frame_end < v)
return AVERROR_INVALIDDATA;
frame += v;
} else {
if (frame_end - frame < width + 3)
return AVERROR_INVALIDDATA;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
}
mask <<= 2;
}
return 0;
}
| 311,517,746,864,273,740,000,000,000,000,000,000,000 | dfa.c | 52,043,501,485,622,960,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9992 | Heap-based buffer overflow in the decode_dds1 function in libavcodec/dfa.c in FFmpeg before 2.8.12, 3.0.x before 3.0.8, 3.1.x before 3.1.8, 3.2.x before 3.2.5, and 3.3.x before 3.3.1 allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9992 |
2,741 | FFmpeg | 441026fcb13ac23aa10edc312bdacb6445a0ad06 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/441026fcb13ac23aa10edc312bdacb6445a0ad06 | avcodec/xwddec: Check bpp more completely
Fixes out of array access
Fixes: 1399/clusterfuzz-testcase-minimized-4866094172995584
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static int xwd_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
AVFrame *p = data;
const uint8_t *buf = avpkt->data;
int i, ret, buf_size = avpkt->size;
uint32_t version, header_size, vclass, ncolors;
uint32_t xoffset, be, bpp, lsize, rsize;
uint32_t pixformat, pixdepth, bunit, bitorder, bpad;
uint32_t rgb[3];
uint8_t *ptr;
GetByteContext gb;
if (buf_size < XWD_HEADER_SIZE)
return AVERROR_INVALIDDATA;
bytestream2_init(&gb, buf, buf_size);
header_size = bytestream2_get_be32u(&gb);
version = bytestream2_get_be32u(&gb);
if (version != XWD_VERSION) {
av_log(avctx, AV_LOG_ERROR, "unsupported version\n");
return AVERROR_INVALIDDATA;
}
if (buf_size < header_size || header_size < XWD_HEADER_SIZE) {
av_log(avctx, AV_LOG_ERROR, "invalid header size\n");
return AVERROR_INVALIDDATA;
}
pixformat = bytestream2_get_be32u(&gb);
pixdepth = bytestream2_get_be32u(&gb);
avctx->width = bytestream2_get_be32u(&gb);
avctx->height = bytestream2_get_be32u(&gb);
xoffset = bytestream2_get_be32u(&gb);
be = bytestream2_get_be32u(&gb);
bunit = bytestream2_get_be32u(&gb);
bitorder = bytestream2_get_be32u(&gb);
bpad = bytestream2_get_be32u(&gb);
bpp = bytestream2_get_be32u(&gb);
lsize = bytestream2_get_be32u(&gb);
vclass = bytestream2_get_be32u(&gb);
rgb[0] = bytestream2_get_be32u(&gb);
rgb[1] = bytestream2_get_be32u(&gb);
rgb[2] = bytestream2_get_be32u(&gb);
bytestream2_skipu(&gb, 8);
ncolors = bytestream2_get_be32u(&gb);
bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20));
av_log(avctx, AV_LOG_DEBUG,
"pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n",
pixformat, pixdepth, bunit, bitorder, bpad);
av_log(avctx, AV_LOG_DEBUG,
"vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n",
vclass, ncolors, bpp, be, lsize, xoffset);
av_log(avctx, AV_LOG_DEBUG,
"red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n",
rgb[0], rgb[1], rgb[2]);
if (pixformat > XWD_Z_PIXMAP) {
av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n");
return AVERROR_INVALIDDATA;
}
if (pixdepth == 0 || pixdepth > 32) {
av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n");
return AVERROR_INVALIDDATA;
}
if (xoffset) {
avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset);
return AVERROR_PATCHWELCOME;
}
if (be > 1) {
av_log(avctx, AV_LOG_ERROR, "invalid byte order\n");
return AVERROR_INVALIDDATA;
}
if (bitorder > 1) {
av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n");
return AVERROR_INVALIDDATA;
}
if (bunit != 8 && bunit != 16 && bunit != 32) {
av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n");
return AVERROR_INVALIDDATA;
}
if (bpad != 8 && bpad != 16 && bpad != 32) {
av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n");
return AVERROR_INVALIDDATA;
}
if (bpp == 0 || bpp > 32) {
av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n");
return AVERROR_INVALIDDATA;
}
if (ncolors > 256) {
av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n");
return AVERROR_INVALIDDATA;
}
if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0)
return ret;
rsize = FFALIGN(avctx->width * bpp, bpad) / 8;
if (lsize < rsize) {
av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n");
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) {
av_log(avctx, AV_LOG_ERROR, "input buffer too small\n");
return AVERROR_INVALIDDATA;
}
if (pixformat != XWD_Z_PIXMAP) {
avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat);
return AVERROR_PATCHWELCOME;
}
avctx->pix_fmt = AV_PIX_FMT_NONE;
switch (vclass) {
case XWD_STATIC_GRAY:
case XWD_GRAY_SCALE:
if (bpp != 1 && bpp != 8)
return AVERROR_INVALIDDATA;
if (pixdepth == 1) {
avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
} else if (pixdepth == 8) {
avctx->pix_fmt = AV_PIX_FMT_GRAY8;
}
break;
case XWD_STATIC_COLOR:
case XWD_PSEUDO_COLOR:
if (bpp == 8)
avctx->pix_fmt = AV_PIX_FMT_PAL8;
break;
case XWD_TRUE_COLOR:
case XWD_DIRECT_COLOR:
if (bpp != 16 && bpp != 24 && bpp != 32)
return AVERROR_INVALIDDATA;
if (bpp == 16 && pixdepth == 15) {
if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F)
avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE;
else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00)
avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE;
} else if (bpp == 16 && pixdepth == 16) {
if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F)
avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE;
else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800)
avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE;
} else if (bpp == 24) {
if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)
avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24;
else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)
avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24;
} else if (bpp == 32) {
if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)
avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA;
else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)
avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA;
}
bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE);
break;
default:
av_log(avctx, AV_LOG_ERROR, "invalid visual class\n");
return AVERROR_INVALIDDATA;
}
if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
avpriv_request_sample(avctx,
"Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"",
bpp, pixdepth, vclass);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
uint32_t *dst = (uint32_t *)p->data[1];
uint8_t red, green, blue;
for (i = 0; i < ncolors; i++) {
bytestream2_skipu(&gb, 4); // skip colormap entry number
red = bytestream2_get_byteu(&gb);
bytestream2_skipu(&gb, 1);
green = bytestream2_get_byteu(&gb);
bytestream2_skipu(&gb, 1);
blue = bytestream2_get_byteu(&gb);
bytestream2_skipu(&gb, 3); // skip bitmask flag and padding
dst[i] = red << 16 | green << 8 | blue;
}
}
ptr = p->data[0];
for (i = 0; i < avctx->height; i++) {
bytestream2_get_bufferu(&gb, ptr, rsize);
bytestream2_skipu(&gb, lsize - rsize);
ptr += p->linesize[0];
}
*got_frame = 1;
return buf_size;
}
| 154,378,037,284,752,480,000,000,000,000,000,000,000 | xwddec.c | 294,025,484,135,912,770,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9991 | Heap-based buffer overflow in the xwd_decode_frame function in libavcodec/xwddec.c in FFmpeg before 2.8.12, 3.0.x before 3.0.8, 3.1.x before 3.1.8, 3.2.x before 3.2.5, and 3.3.x before 3.3.1 allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9991 |
2,742 | FFmpeg | cb243972b121b1ae6b60a78ff55a0506c69f3879 | https://github.com/FFmpeg/FFmpeg | https://github.com/FFmpeg/FFmpeg/commit/cb243972b121b1ae6b60a78ff55a0506c69f3879 | avcodec/xpmdec: Fix multiple pointer/memory issues
Most of these were found through code review in response to
fixing 1466/clusterfuzz-testcase-minimized-5961584419536896
There is thus no testcase for most of this.
The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> | 1 | static uint32_t color_string_to_rgba(const char *p, int len)
{
uint32_t ret = 0xFF000000;
const ColorEntry *entry;
char color_name[100];
if (*p == '#') {
p++;
len--;
if (len == 3) {
ret |= (hex_char_to_number(p[2]) << 4) |
(hex_char_to_number(p[1]) << 12) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 4) {
ret = (hex_char_to_number(p[3]) << 4) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 20) |
(hex_char_to_number(p[0]) << 28);
} else if (len == 6) {
ret |= hex_char_to_number(p[5]) |
(hex_char_to_number(p[4]) << 4) |
(hex_char_to_number(p[3]) << 8) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 16) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 8) {
ret = hex_char_to_number(p[7]) |
(hex_char_to_number(p[6]) << 4) |
(hex_char_to_number(p[5]) << 8) |
(hex_char_to_number(p[4]) << 12) |
(hex_char_to_number(p[3]) << 16) |
(hex_char_to_number(p[2]) << 20) |
(hex_char_to_number(p[1]) << 24) |
(hex_char_to_number(p[0]) << 28);
}
} else {
strncpy(color_name, p, len);
color_name[len] = '\0';
entry = bsearch(color_name,
color_table,
FF_ARRAY_ELEMS(color_table),
sizeof(ColorEntry),
color_table_compare);
if (!entry)
return ret;
ret = entry->rgb_color;
}
return ret;
}
| 238,040,376,254,480,200,000,000,000,000,000,000,000 | xpmdec.c | 78,083,234,821,023,300,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9990 | Stack-based buffer overflow in the color_string_to_rgba function in libavcodec/xpmdec.c in FFmpeg 3.3 before 3.3.1 allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9990 |
2,745 | linux | 20e2b791796bd68816fa115f12be5320de2b8021 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/20e2b791796bd68816fa115f12be5320de2b8021 | ALSA: msnd: Optimize / harden DSP and MIDI loops
The ISA msnd drivers have loops fetching the ring-buffer head, tail
and size values inside the loops. Such codes are inefficient and
fragile.
This patch optimizes it, and also adds the sanity check to avoid the
endless loops.
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133
Signed-off-by: Takashi Iwai <tiwai@suse.de> | 1 | void snd_msndmidi_input_read(void *mpuv)
{
unsigned long flags;
struct snd_msndmidi *mpu = mpuv;
void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF;
spin_lock_irqsave(&mpu->input_lock, flags);
while (readw(mpu->dev->MIDQ + JQS_wTail) !=
readw(mpu->dev->MIDQ + JQS_wHead)) {
u16 wTmp, val;
val = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead));
if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,
&mpu->mode))
snd_rawmidi_receive(mpu->substream_input,
(unsigned char *)&val, 1);
wTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1;
if (wTmp > readw(mpu->dev->MIDQ + JQS_wSize))
writew(0, mpu->dev->MIDQ + JQS_wHead);
else
writew(wTmp, mpu->dev->MIDQ + JQS_wHead);
}
spin_unlock_irqrestore(&mpu->input_lock, flags);
}
| 241,508,483,468,154,000,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-9984 | The snd_msnd_interrupt function in sound/isa/msnd/msnd_pinnacle.c in the Linux kernel through 4.11.7 allows local users to cause a denial of service (over-boundary access) or possibly have unspecified other impact by changing the value of a message queue head pointer between two kernel reads of that value, aka a "double fetch" vulnerability. | https://nvd.nist.gov/vuln/detail/CVE-2017-9984 |
2,746 | linux | 20e2b791796bd68816fa115f12be5320de2b8021 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/20e2b791796bd68816fa115f12be5320de2b8021 | ALSA: msnd: Optimize / harden DSP and MIDI loops
The ISA msnd drivers have loops fetching the ring-buffer head, tail
and size values inside the loops. Such codes are inefficient and
fragile.
This patch optimizes it, and also adds the sanity check to avoid the
endless loops.
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133
Signed-off-by: Takashi Iwai <tiwai@suse.de> | 1 | static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id)
{
struct snd_msnd *chip = dev_id;
void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF;
/* Send ack to DSP */
/* inb(chip->io + HP_RXL); */
/* Evaluate queued DSP messages */
while (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) {
u16 wTmp;
snd_msnd_eval_dsp_msg(chip,
readw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead)));
wTmp = readw(chip->DSPQ + JQS_wHead) + 1;
if (wTmp > readw(chip->DSPQ + JQS_wSize))
writew(0, chip->DSPQ + JQS_wHead);
else
writew(wTmp, chip->DSPQ + JQS_wHead);
}
/* Send ack to DSP */
inb(chip->io + HP_RXL);
return IRQ_HANDLED;
}
| 157,005,536,200,453,300,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-9984 | The snd_msnd_interrupt function in sound/isa/msnd/msnd_pinnacle.c in the Linux kernel through 4.11.7 allows local users to cause a denial of service (over-boundary access) or possibly have unspecified other impact by changing the value of a message queue head pointer between two kernel reads of that value, aka a "double fetch" vulnerability. | https://nvd.nist.gov/vuln/detail/CVE-2017-9984 |
2,752 | radare2 | 65000a7fd9eea62359e6d6714f17b94a99a82edd | https://github.com/radare/radare2 | https://github.com/radare/radare2/commit/65000a7fd9eea62359e6d6714f17b94a99a82edd | Fix #7723 - crash in ext2 GRUB code because of variable size array in stack | 1 | grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
#ifndef _MSC_VER
char buf[EXT2_BLOCK_SIZE (data)];
#else
char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));
#endif
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len))
return 0;
else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
return -1;
}
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS) {
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
} else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
| 210,811,521,877,163,650,000,000,000,000,000,000,000 | ext2.c | 53,758,202,141,423,640,000,000,000,000,000,000,000 | [
"CWE-119"
] | CVE-2017-9763 | The grub_ext2_read_block function in fs/ext2.c in GNU GRUB before 2013-11-12, as used in shlr/grub/fs/ext2.c in radare2 1.5.0, allows remote attackers to cause a denial of service (excessive stack use and application crash) via a crafted binary file, related to use of a variable-size stack array. | https://nvd.nist.gov/vuln/detail/CVE-2017-9763 |
2,757 | linux | 07678eca2cf9c9a18584e546c2b2a0d0c9a3150c | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/07678eca2cf9c9a18584e546c2b2a0d0c9a3150c | drm/vmwgfx: Make sure backup_handle is always valid
When vmw_gb_surface_define_ioctl() is called with an existing buffer,
we end up returning an uninitialized variable in the backup_handle.
The fix is to first initialize backup_handle to 0 just to be sure, and
second, when a user-provided buffer is found, we will use the
req->buffer_handle as the backup_handle.
Cc: <stable@vger.kernel.org>
Reported-by: Murray McAllister <murray.mcallister@insomniasec.com>
Signed-off-by: Sinclair Yeh <syeh@vmware.com>
Reviewed-by: Deepak Rawat <drawat@vmware.com> | 1 | int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
struct vmw_resource *res;
struct vmw_resource *tmp;
union drm_vmw_gb_surface_create_arg *arg =
(union drm_vmw_gb_surface_create_arg *)data;
struct drm_vmw_gb_surface_create_req *req = &arg->req;
struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
uint32_t size;
uint32_t backup_handle;
if (req->multisample_count != 0)
return -EINVAL;
if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS)
return -EINVAL;
if (unlikely(vmw_user_surface_size == 0))
vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) +
128;
size = vmw_user_surface_size + 128;
/* Define a surface based on the parameters. */
ret = vmw_surface_gb_priv_define(dev,
size,
req->svga3d_flags,
req->format,
req->drm_surface_flags & drm_vmw_surface_flag_scanout,
req->mip_levels,
req->multisample_count,
req->array_size,
req->base_size,
&srf);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(srf, struct vmw_user_surface, srf);
if (drm_is_primary_client(file_priv))
user_srf->master = drm_master_get(file_priv->master);
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
res = &user_srf->srf.res;
if (req->buffer_handle != SVGA3D_INVALID_ID) {
ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle,
&res->backup,
&user_srf->backup_base);
if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE <
res->backup_size) {
DRM_ERROR("Surface backup buffer is too small.\n");
vmw_dmabuf_unreference(&res->backup);
ret = -EINVAL;
goto out_unlock;
}
} else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer)
ret = vmw_user_dmabuf_alloc(dev_priv, tfile,
res->backup_size,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
&backup_handle,
&res->backup,
&user_srf->backup_base);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&res);
goto out_unlock;
}
tmp = vmw_resource_reference(res);
ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
VMW_RES_SURFACE,
&vmw_user_surface_base_release, NULL);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&tmp);
vmw_resource_unreference(&res);
goto out_unlock;
}
rep->handle = user_srf->prime.base.hash.key;
rep->backup_size = res->backup_size;
if (res->backup) {
rep->buffer_map_handle =
drm_vma_node_offset_addr(&res->backup->base.vma_node);
rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE;
rep->buffer_handle = backup_handle;
} else {
rep->buffer_map_handle = 0;
rep->buffer_size = 0;
rep->buffer_handle = SVGA3D_INVALID_ID;
}
vmw_resource_unreference(&res);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
| 174,250,850,425,960,800,000,000,000,000,000,000,000 | vmwgfx_surface.c | 245,292,923,373,553,170,000,000,000,000,000,000,000 | [
"CWE-200"
] | CVE-2017-9605 | The vmw_gb_surface_define_ioctl function (accessible via DRM_IOCTL_VMW_GB_SURFACE_CREATE) in drivers/gpu/drm/vmwgfx/vmwgfx_surface.c in the Linux kernel through 4.11.4 defines a backup_handle variable but does not give it an initial value. If one attempts to create a GB surface, with a previously allocated DMA buffer to be used as a backup buffer, the backup_handle variable does not get written to and is then later returned to user space, allowing local users to obtain sensitive information from uninitialized kernel memory via a crafted ioctl call. | https://nvd.nist.gov/vuln/detail/CVE-2017-9605 |
2,758 | mruby | 5c114c91d4ff31859fcd84cf8bf349b737b90d99 | https://github.com/mruby/mruby | https://github.com/mruby/mruby/commit/5c114c91d4ff31859fcd84cf8bf349b737b90d99 | Clear unused stack region that may refer freed objects; fix #3596 | 1 | mark_context_stack(mrb_state *mrb, struct mrb_context *c)
{
size_t i;
size_t e;
if (c->stack == NULL) return;
e = c->stack - c->stbase;
if (c->ci) e += c->ci->nregs;
if (c->stbase + e > c->stend) e = c->stend - c->stbase;
for (i=0; i<e; i++) {
mrb_value v = c->stbase[i];
if (!mrb_immediate_p(v)) {
if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) {
c->stbase[i] = mrb_nil_value();
}
else {
mrb_gc_mark(mrb, mrb_basic_ptr(v));
}
}
}
}
| 125,574,988,804,055,740,000,000,000,000,000,000,000 | gc.c | 192,625,814,561,719,470,000,000,000,000,000,000,000 | [
"CWE-416"
] | CVE-2017-9527 | The mark_context_stack function in gc.c in mruby through 1.2.0 allows attackers to cause a denial of service (heap-based use-after-free and application crash) or possibly have unspecified other impact via a crafted .rb file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9527 |
2,759 | radare2 | f85bc674b2a2256a364fe796351bc1971e106005 | https://github.com/radare/radare2 | https://github.com/radare/radare2/commit/f85bc674b2a2256a364fe796351bc1971e106005 | Fix #7698 - UAF in r_config_set when loading a dex | 1 | R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) {
RConfigNode *node = NULL;
char *ov = NULL;
ut64 oi;
if (!cfg || STRNULL (name)) {
return NULL;
}
node = r_config_node_get (cfg, name);
if (node) {
if (node->flags & CN_RO) {
eprintf ("(error: '%s' config key is read only)\n", name);
return node;
}
oi = node->i_value;
if (node->value) {
ov = strdup (node->value);
if (!ov) {
goto beach;
}
} else {
free (node->value);
node->value = strdup ("");
}
if (node->flags & CN_BOOL) {
bool b = is_true (value);
node->i_value = (ut64) b? 1: 0;
char *value = strdup (r_str_bool (b));
if (value) {
free (node->value);
node->value = value;
}
} else {
if (!value) {
free (node->value);
node->value = strdup ("");
node->i_value = 0;
} else {
if (node->value == value) {
goto beach;
}
free (node->value);
node->value = strdup (value);
if (IS_DIGIT (*value)) {
if (strchr (value, '/')) {
node->i_value = r_num_get (cfg->num, value);
} else {
node->i_value = r_num_math (cfg->num, value);
}
} else {
node->i_value = 0;
}
node->flags |= CN_INT;
}
}
} else { // Create a new RConfigNode
oi = UT64_MAX;
if (!cfg->lock) {
node = r_config_node_new (name, value);
if (node) {
if (value && is_bool (value)) {
node->flags |= CN_BOOL;
node->i_value = is_true (value)? 1: 0;
}
if (cfg->ht) {
ht_insert (cfg->ht, node->name, node);
r_list_append (cfg->nodes, node);
cfg->n_nodes++;
}
} else {
eprintf ("r_config_set: unable to create a new RConfigNode\n");
}
} else {
eprintf ("r_config_set: variable '%s' not found\n", name);
}
}
if (node && node->setter) {
int ret = node->setter (cfg->user, node);
if (ret == false) {
if (oi != UT64_MAX) {
node->i_value = oi;
}
free (node->value);
node->value = strdup (ov? ov: "");
}
}
beach:
free (ov);
return node;
}
| 266,006,440,521,677,500,000,000,000,000,000,000,000 | config.c | 257,283,705,418,955,800,000,000,000,000,000,000,000 | [
"CWE-416"
] | CVE-2017-9520 | The r_config_set function in libr/config/config.c in radare2 1.5.0 allows remote attackers to cause a denial of service (use-after-free and application crash) via a crafted DEX file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9520 |
2,760 | ImageMagick | 01843366d6a7b96e22ad7bb67f3df7d9fd4d5d74 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/01843366d6a7b96e22ad7bb67f3df7d9fd4d5d74 | None | 1 | MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
double
scale;
Image
*clone_image;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->channels=image->channels;
clone_image->colorspace=image->colorspace;
clone_image->matte=image->matte;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelPacket *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelPacket *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
InitializeExceptionInfo(&clone_image->exception);
InheritException(&clone_image->exception,&image->exception);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
clone_image->clip_mask=NewImageList();
clone_image->mask=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AllocateSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
if ((columns == image->columns) && (rows == image->rows))
{
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows) == MagickFalse)
{
InheritException(exception,&clone_image->exception);
clone_image=DestroyImage(clone_image);
}
return(clone_image);
}
| 30,295,949,585,114,532,000,000,000,000,000,000,000 | None | null | [
"CWE-617"
] | CVE-2017-9501 | In ImageMagick 7.0.5-7 Q16, an assertion failure was found in the function LockSemaphoreInfo, which allows attackers to cause a denial of service via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9501 |
2,761 | ImageMagick | 7fd419441bc7103398e313558171d342c6315f44 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/7fd419441bc7103398e313558171d342c6315f44 | Added check for incorrect number of meta channels report in #492. | 1 | static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
cache_filename[MagickPathExtent],
id[MagickPathExtent],
keyword[MagickPathExtent],
*options;
const unsigned char
*p;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
register ssize_t
i;
size_t
depth,
length;
ssize_t
count;
StringInfo
*profile;
unsigned int
signature;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CopyMagickString(cache_filename,image->filename,MagickPathExtent);
AppendImageFormat("cache",cache_filename);
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
offset=0;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
profiles=(LinkedListInfo *) NULL;
length=MagickPathExtent;
options=AcquireString((char *) NULL);
signature=GetMagickSignature((const StringInfo *) NULL);
image->depth=8;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MagickPathExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MagickPathExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MagickPathExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MagickPathExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'a':
case 'A':
{
if (LocaleCompare(keyword,"alpha-trait") == 0)
{
ssize_t
alpha_trait;
alpha_trait=ParseCommandOption(MagickPixelTraitOptions,
MagickFalse,options);
if (alpha_trait < 0)
break;
image->alpha_trait=(PixelTrait) alpha_trait;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->border_color,exception);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
image->colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
if (LocaleCompare(keyword,"error") == 0)
{
image->error.mean_error_per_pixel=StringToDouble(options,
(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MagickPathExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"magick-signature") == 0)
{
signature=(unsigned int) StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"mattecolor") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->matte_color,exception);
break;
}
if (LocaleCompare(keyword,"maximum-error") == 0)
{
image->error.normalized_maximum_error=StringToDouble(
options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"mean-error") == 0)
{
image->error.normalized_mean_error=StringToDouble(options,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'n':
case 'N':
{
if (LocaleCompare(keyword,"number-channels") == 0)
{
image->number_channels=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"number-meta-channels") == 0)
{
image->number_meta_channels=StringToUnsignedLong(options);
break;
}
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile,exception);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
if ((flags & SigmaValue) != 0)
image->chromaticity.red_primary.y=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,
MagickFalse,options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options,exception);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"MagickCache") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) || (image->columns == 0) ||
(image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (signature != GetMagickSignature((const StringInfo *) NULL))
ThrowReaderException(CacheError,"IncompatibleAPI");
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MagickPathExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MagickPathExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MagickPathExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
register unsigned char
*p;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
count=ReadBlob(image,GetStringInfoLength(profile),p);
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
/*
Create image colormap.
*/
image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1,
sizeof(*image->colormap));
if (image->colormap == (PixelInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->colors != 0)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Read image colormap from file.
*/
packet_size=(size_t) (3UL*depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=colormap;
switch (depth)
{
default:
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
/*
Attach persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
if (status == MagickFalse)
ThrowReaderException(CacheError,"UnableToPersistPixelCache");
/*
Proceed to next image.
*/
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 109,762,771,306,384,910,000,000,000,000,000,000,000 | mpc.c | 33,984,905,082,564,350,000,000,000,000,000,000,000 | [
"CWE-617"
] | CVE-2017-9499 | In ImageMagick 7.0.5-7 Q16, an assertion failure was found in the function SetPixelChannelAttributes, which allows attackers to cause a denial of service via a crafted file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9499 |
2,765 | jerryscript | 03a8c630f015f63268639d3ed3bf82cff6fa77d8 | https://github.com/zherczeg/jerryscript | https://github.com/zherczeg/jerryscript/commit/03a8c630f015f63268639d3ed3bf82cff6fa77d8 | None | 1 | lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */
| 197,513,151,461,081,370,000,000,000,000,000,000,000 | js-lexer.c | 126,318,166,963,366,350,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-9250 | The lexer_process_char_literal function in jerry-core/parser/js/js-lexer.c in JerryScript 1.0 does not skip memory allocation for empty strings, which allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via malformed JavaScript source code, related to the jmem_heap_free_block function. | https://nvd.nist.gov/vuln/detail/CVE-2017-9250 |
2,766 | linux | 232cd35d0804cc241eb887bb8d4d9b3b9881c64a | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/232cd35d0804cc241eb887bb8d4d9b3b9881c64a | ipv6: fix out of bound writes in __ip6_append_data()
Andrey Konovalov and idaifish@gmail.com reported crashes caused by
one skb shared_info being overwritten from __ip6_append_data()
Andrey program lead to following state :
copy -4200 datalen 2000 fraglen 2040
maxfraglen 2040 alloclen 2048 transhdrlen 0 offset 0 fraggap 6200
The skb_copy_and_csum_bits(skb_prev, maxfraglen, data + transhdrlen,
fraggap, 0); is overwriting skb->head and skb_shared_info
Since we apparently detect this rare condition too late, move the
code earlier to even avoid allocating skb and risking crashes.
Once again, many thanks to Andrey and syzkaller team.
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
Reported-by: <idaifish@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static int __ip6_append_data(struct sock *sk,
struct flowi6 *fl6,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct inet6_cork *v6_cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags, struct ipcm6_cookie *ipc6,
const struct sockcm_cookie *sockc)
{
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen = 0;
int dst_exthdrlen = 0;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
u32 tskey = 0;
struct rt6_info *rt = (struct rt6_info *)cork->dst;
struct ipv6_txoptions *opt = v6_cork->opt;
int csummode = CHECKSUM_NONE;
unsigned int maxnonfragsize, headersize;
skb = skb_peek_tail(queue);
if (!skb) {
exthdrlen = opt ? opt->opt_flen : 0;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
}
mtu = cork->fragsize;
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
sizeof(struct frag_hdr);
headersize = sizeof(struct ipv6hdr) +
(opt ? opt->opt_flen + opt->opt_nflen : 0) +
(dst_allfrag(&rt->dst) ?
sizeof(struct frag_hdr) : 0) +
rt->rt6i_nfheader_len;
if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
(sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
sizeof(struct ipv6hdr));
goto emsgsize;
}
if (ip6_sk_ignore_df(sk))
maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
else
maxnonfragsize = mtu;
if (cork->length + length > maxnonfragsize - headersize) {
emsgsize:
ipv6_local_error(sk, EMSGSIZE, fl6,
mtu - headersize +
sizeof(struct ipv6hdr));
return -EMSGSIZE;
}
/* CHECKSUM_PARTIAL only with no extension headers and when
* we are not going to fragment
*/
if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
headersize == sizeof(struct ipv6hdr) &&
length <= mtu - headersize &&
!(flags & MSG_MORE) &&
rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
csummode = CHECKSUM_PARTIAL;
if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) {
sock_tx_timestamp(sk, sockc->tsflags, &tx_flags);
if (tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if ((((length + fragheaderlen) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) {
err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, exthdrlen,
transhdrlen, mtu, flags, fl6);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (!skb || !skb_prev)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
/* Only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = tx_flags;
tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
| 120,470,980,408,117,320,000,000,000,000,000,000,000 | ip6_output.c | 289,318,388,227,575,940,000,000,000,000,000,000,000 | [
"CWE-20"
] | CVE-2017-9242 | The __ip6_append_data function in net/ipv6/ip6_output.c in the Linux kernel through 4.11.3 is too late in checking whether an overwrite of an skb data structure may occur, which allows local users to cause a denial of service (system crash) via crafted system calls. | https://nvd.nist.gov/vuln/detail/CVE-2017-9242 |
2,767 | oniguruma | b690371bbf97794b4a1d3f295d4fb9a8b05d402d | https://github.com/kkos/oniguruma | https://github.com/kkos/oniguruma/commit/b690371bbf97794b4a1d3f295d4fb9a8b05d402d | fix #59 : access to invalid address by reg->dmax value | 1 | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
| 107,914,413,019,882,700,000,000,000,000,000,000,000 | regexec.c | 288,161,812,901,203,540,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-9229 | An issue was discovered in Oniguruma 6.2.0, as used in Oniguruma-mod in Ruby through 2.4.1 and mbstring in PHP through 7.1.5. A SIGSEGV occurs in left_adjust_char_head() during regular expression compilation. Invalid handling of reg->dmax in forward_search_range() could result in an invalid pointer dereference, normally as an immediate denial-of-service condition. | https://nvd.nist.gov/vuln/detail/CVE-2017-9229 |
2,768 | oniguruma | 9690d3ab1f9bcd2db8cbe1fe3ee4a5da606b8814 | https://github.com/kkos/oniguruma | https://github.com/kkos/oniguruma/commit/9690d3ab1f9bcd2db8cbe1fe3ee4a5da606b8814 | fix #58 : access to invalid address by reg->dmin value | 1 | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
| 291,227,733,650,060,420,000,000,000,000,000,000,000 | regexec.c | 1,961,275,105,264,870,000,000,000,000,000,000,000 | [
"CWE-125"
] | CVE-2017-9227 | An issue was discovered in Oniguruma 6.2.0, as used in Oniguruma-mod in Ruby through 2.4.1 and mbstring in PHP through 7.1.5. A stack out-of-bounds read occurs in mbc_enc_len() during regular expression searching. Invalid handling of reg->dmin in forward_search_range() could result in an invalid pointer dereference, as an out-of-bounds read from a stack buffer. | https://nvd.nist.gov/vuln/detail/CVE-2017-9227 |
2,769 | oniguruma | 166a6c3999bf06b4de0ab4ce6b088a468cc4029f | https://github.com/kkos/oniguruma | https://github.com/kkos/oniguruma/commit/166a6c3999bf06b4de0ab4ce6b088a468cc4029f | fix #56 : return invalid result for codepoint 0xFFFFFFFF | 1 | unicode_unfold_key(OnigCodePoint code)
{
static const struct ByUnfoldKey wordlist[] =
{
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0x1040a, 3267, 1},
{0x1e0a, 1727, 1},
{0x040a, 1016, 1},
{0x010a, 186, 1},
{0x1f0a, 2088, 1},
{0x2c0a, 2451, 1},
{0x0189, 619, 1},
{0x1f89, 134, 2},
{0x1f85, 154, 2},
{0x0389, 733, 1},
{0x03ff, 724, 1},
{0xab89, 1523, 1},
{0xab85, 1511, 1},
{0x10c89, 3384, 1},
{0x10c85, 3372, 1},
{0x1e84, 1911, 1},
{0x03f5, 752, 1},
{0x0184, 360, 1},
{0x1f84, 149, 2},
{0x2c84, 2592, 1},
{0x017d, 351, 1},
{0x1ff3, 96, 2},
{0xab84, 1508, 1},
{0xa784, 3105, 1},
{0x10c84, 3369, 1},
{0xab7d, 1487, 1},
{0xa77d, 1706, 1},
{0x1e98, 38, 2},
{0x0498, 1106, 1},
{0x0198, 375, 1},
{0x1f98, 169, 2},
{0x2c98, 2622, 1},
{0x0398, 762, 1},
{0xa684, 2940, 1},
{0xab98, 1568, 1},
{0xa798, 3123, 1},
{0x10c98, 3429, 1},
{0x050a, 1277, 1},
{0x1ffb, 2265, 1},
{0x1e96, 16, 2},
{0x0496, 1103, 1},
{0x0196, 652, 1},
{0x1f96, 199, 2},
{0x2c96, 2619, 1},
{0x0396, 756, 1},
{0xa698, 2970, 1},
{0xab96, 1562, 1},
{0xa796, 3120, 1},
{0x10c96, 3423, 1},
{0x1feb, 2259, 1},
{0x2ceb, 2736, 1},
{0x1e90, 1929, 1},
{0x0490, 1094, 1},
{0x0190, 628, 1},
{0x1f90, 169, 2},
{0x2c90, 2610, 1},
{0x0390, 25, 3},
{0xa696, 2967, 1},
{0xab90, 1544, 1},
{0xa790, 3114, 1},
{0x10c90, 3405, 1},
{0x01d7, 444, 1},
{0x1fd7, 31, 3},
{0x1ea6, 1947, 1},
{0x04a6, 1127, 1},
{0x01a6, 676, 1},
{0x1fa6, 239, 2},
{0x2ca6, 2643, 1},
{0x03a6, 810, 1},
{0xa690, 2958, 1},
{0xaba6, 1610, 1},
{0xa7a6, 3144, 1},
{0x10ca6, 3471, 1},
{0x1ea4, 1944, 1},
{0x04a4, 1124, 1},
{0x01a4, 390, 1},
{0x1fa4, 229, 2},
{0x2ca4, 2640, 1},
{0x03a4, 804, 1},
{0x10a6, 2763, 1},
{0xaba4, 1604, 1},
{0xa7a4, 3141, 1},
{0x10ca4, 3465, 1},
{0x1ea0, 1938, 1},
{0x04a0, 1118, 1},
{0x01a0, 384, 1},
{0x1fa0, 209, 2},
{0x2ca0, 2634, 1},
{0x03a0, 792, 1},
{0x10a4, 2757, 1},
{0xaba0, 1592, 1},
{0xa7a0, 3135, 1},
{0x10ca0, 3453, 1},
{0x1eb2, 1965, 1},
{0x04b2, 1145, 1},
{0x01b2, 694, 1},
{0x1fb2, 249, 2},
{0x2cb2, 2661, 1},
{0x03fd, 718, 1},
{0x10a0, 2745, 1},
{0xabb2, 1646, 1},
{0xa7b2, 703, 1},
{0x10cb2, 3507, 1},
{0x1eac, 1956, 1},
{0x04ac, 1136, 1},
{0x01ac, 396, 1},
{0x1fac, 229, 2},
{0x2cac, 2652, 1},
{0x0537, 1352, 1},
{0x10b2, 2799, 1},
{0xabac, 1628, 1},
{0xa7ac, 637, 1},
{0x10cac, 3489, 1},
{0x1eaa, 1953, 1},
{0x04aa, 1133, 1},
{0x00dd, 162, 1},
{0x1faa, 219, 2},
{0x2caa, 2649, 1},
{0x03aa, 824, 1},
{0x10ac, 2781, 1},
{0xabaa, 1622, 1},
{0xa7aa, 646, 1},
{0x10caa, 3483, 1},
{0x1ea8, 1950, 1},
{0x04a8, 1130, 1},
{0x020a, 517, 1},
{0x1fa8, 209, 2},
{0x2ca8, 2646, 1},
{0x03a8, 817, 1},
{0x10aa, 2775, 1},
{0xaba8, 1616, 1},
{0xa7a8, 3147, 1},
{0x10ca8, 3477, 1},
{0x1ea2, 1941, 1},
{0x04a2, 1121, 1},
{0x01a2, 387, 1},
{0x1fa2, 219, 2},
{0x2ca2, 2637, 1},
{0x118a6, 3528, 1},
{0x10a8, 2769, 1},
{0xaba2, 1598, 1},
{0xa7a2, 3138, 1},
{0x10ca2, 3459, 1},
{0x2ced, 2739, 1},
{0x1fe9, 2283, 1},
{0x1fe7, 47, 3},
{0x1eb0, 1962, 1},
{0x04b0, 1142, 1},
{0x118a4, 3522, 1},
{0x10a2, 2751, 1},
{0x2cb0, 2658, 1},
{0x03b0, 41, 3},
{0x1fe3, 41, 3},
{0xabb0, 1640, 1},
{0xa7b0, 706, 1},
{0x10cb0, 3501, 1},
{0x01d9, 447, 1},
{0x1fd9, 2277, 1},
{0x118a0, 3510, 1},
{0x00df, 24, 2},
{0x00d9, 150, 1},
{0xab77, 1469, 1},
{0x10b0, 2793, 1},
{0x1eae, 1959, 1},
{0x04ae, 1139, 1},
{0x01ae, 685, 1},
{0x1fae, 239, 2},
{0x2cae, 2655, 1},
{0x118b2, 3564, 1},
{0xab73, 1457, 1},
{0xabae, 1634, 1},
{0xab71, 1451, 1},
{0x10cae, 3495, 1},
{0x1e2a, 1775, 1},
{0x042a, 968, 1},
{0x012a, 234, 1},
{0x1f2a, 2130, 1},
{0x2c2a, 2547, 1},
{0x118ac, 3546, 1},
{0x10ae, 2787, 1},
{0x0535, 1346, 1},
{0xa72a, 2988, 1},
{0x1e9a, 0, 2},
{0x049a, 1109, 1},
{0xff37, 3225, 1},
{0x1f9a, 179, 2},
{0x2c9a, 2625, 1},
{0x039a, 772, 1},
{0x118aa, 3540, 1},
{0xab9a, 1574, 1},
{0xa79a, 3126, 1},
{0x10c9a, 3435, 1},
{0x1e94, 1935, 1},
{0x0494, 1100, 1},
{0x0194, 640, 1},
{0x1f94, 189, 2},
{0x2c94, 2616, 1},
{0x0394, 749, 1},
{0x118a8, 3534, 1},
{0xab94, 1556, 1},
{0xa69a, 2973, 1},
{0x10c94, 3417, 1},
{0x10402, 3243, 1},
{0x1e02, 1715, 1},
{0x0402, 992, 1},
{0x0102, 174, 1},
{0x0533, 1340, 1},
{0x2c02, 2427, 1},
{0x118a2, 3516, 1},
{0x052a, 1325, 1},
{0xa694, 2964, 1},
{0x1e92, 1932, 1},
{0x0492, 1097, 1},
{0x2165, 2307, 1},
{0x1f92, 179, 2},
{0x2c92, 2613, 1},
{0x0392, 742, 1},
{0x2161, 2295, 1},
{0xab92, 1550, 1},
{0xa792, 3117, 1},
{0x10c92, 3411, 1},
{0x118b0, 3558, 1},
{0x1f5f, 2199, 1},
{0x1e8e, 1926, 1},
{0x048e, 1091, 1},
{0x018e, 453, 1},
{0x1f8e, 159, 2},
{0x2c8e, 2607, 1},
{0x038e, 833, 1},
{0xa692, 2961, 1},
{0xab8e, 1538, 1},
{0x0055, 59, 1},
{0x10c8e, 3399, 1},
{0x1f5d, 2196, 1},
{0x212a, 27, 1},
{0x04cb, 1181, 1},
{0x01cb, 425, 1},
{0x1fcb, 2241, 1},
{0x118ae, 3552, 1},
{0x0502, 1265, 1},
{0x00cb, 111, 1},
{0xa68e, 2955, 1},
{0x1e8a, 1920, 1},
{0x048a, 1085, 1},
{0x018a, 622, 1},
{0x1f8a, 139, 2},
{0x2c8a, 2601, 1},
{0x038a, 736, 1},
{0x2c67, 2571, 1},
{0xab8a, 1526, 1},
{0x1e86, 1914, 1},
{0x10c8a, 3387, 1},
{0x0186, 616, 1},
{0x1f86, 159, 2},
{0x2c86, 2595, 1},
{0x0386, 727, 1},
{0xff35, 3219, 1},
{0xab86, 1514, 1},
{0xa786, 3108, 1},
{0x10c86, 3375, 1},
{0xa68a, 2949, 1},
{0x0555, 1442, 1},
{0x1ebc, 1980, 1},
{0x04bc, 1160, 1},
{0x01bc, 411, 1},
{0x1fbc, 62, 2},
{0x2cbc, 2676, 1},
{0x1f5b, 2193, 1},
{0xa686, 2943, 1},
{0xabbc, 1676, 1},
{0x1eb8, 1974, 1},
{0x04b8, 1154, 1},
{0x01b8, 408, 1},
{0x1fb8, 2268, 1},
{0x2cb8, 2670, 1},
{0x01db, 450, 1},
{0x1fdb, 2247, 1},
{0xabb8, 1664, 1},
{0x10bc, 2829, 1},
{0x00db, 156, 1},
{0x1eb6, 1971, 1},
{0x04b6, 1151, 1},
{0xff33, 3213, 1},
{0x1fb6, 58, 2},
{0x2cb6, 2667, 1},
{0xff2a, 3186, 1},
{0x10b8, 2817, 1},
{0xabb6, 1658, 1},
{0xa7b6, 3153, 1},
{0x10426, 3351, 1},
{0x1e26, 1769, 1},
{0x0426, 956, 1},
{0x0126, 228, 1},
{0x0053, 52, 1},
{0x2c26, 2535, 1},
{0x0057, 65, 1},
{0x10b6, 2811, 1},
{0x022a, 562, 1},
{0xa726, 2982, 1},
{0x1e2e, 1781, 1},
{0x042e, 980, 1},
{0x012e, 240, 1},
{0x1f2e, 2142, 1},
{0x2c2e, 2559, 1},
{0xffffffff, -1, 0},
{0x2167, 2313, 1},
{0xffffffff, -1, 0},
{0xa72e, 2994, 1},
{0x1e2c, 1778, 1},
{0x042c, 974, 1},
{0x012c, 237, 1},
{0x1f2c, 2136, 1},
{0x2c2c, 2553, 1},
{0x1f6f, 2223, 1},
{0x2c6f, 604, 1},
{0xabbf, 1685, 1},
{0xa72c, 2991, 1},
{0x1e28, 1772, 1},
{0x0428, 962, 1},
{0x0128, 231, 1},
{0x1f28, 2124, 1},
{0x2c28, 2541, 1},
{0xffffffff, -1, 0},
{0x0553, 1436, 1},
{0x10bf, 2838, 1},
{0xa728, 2985, 1},
{0x0526, 1319, 1},
{0x0202, 505, 1},
{0x1e40, 1808, 1},
{0x10424, 3345, 1},
{0x1e24, 1766, 1},
{0x0424, 950, 1},
{0x0124, 225, 1},
{0xffffffff, -1, 0},
{0x2c24, 2529, 1},
{0x052e, 1331, 1},
{0xa740, 3018, 1},
{0x118bc, 3594, 1},
{0xa724, 2979, 1},
{0x1ef2, 2061, 1},
{0x04f2, 1241, 1},
{0x01f2, 483, 1},
{0x1ff2, 257, 2},
{0x2cf2, 2742, 1},
{0x052c, 1328, 1},
{0x118b8, 3582, 1},
{0xa640, 2865, 1},
{0x10422, 3339, 1},
{0x1e22, 1763, 1},
{0x0422, 944, 1},
{0x0122, 222, 1},
{0x2126, 820, 1},
{0x2c22, 2523, 1},
{0x0528, 1322, 1},
{0x01f1, 483, 1},
{0x118b6, 3576, 1},
{0xa722, 2976, 1},
{0x03f1, 796, 1},
{0x1ebe, 1983, 1},
{0x04be, 1163, 1},
{0xfb02, 12, 2},
{0x1fbe, 767, 1},
{0x2cbe, 2679, 1},
{0x01b5, 405, 1},
{0x0540, 1379, 1},
{0xabbe, 1682, 1},
{0x0524, 1316, 1},
{0x00b5, 779, 1},
{0xabb5, 1655, 1},
{0x1eba, 1977, 1},
{0x04ba, 1157, 1},
{0x216f, 2337, 1},
{0x1fba, 2226, 1},
{0x2cba, 2673, 1},
{0x10be, 2835, 1},
{0x0051, 46, 1},
{0xabba, 1670, 1},
{0x10b5, 2808, 1},
{0x1e6e, 1878, 1},
{0x046e, 1055, 1},
{0x016e, 330, 1},
{0x1f6e, 2220, 1},
{0x2c6e, 664, 1},
{0x118bf, 3603, 1},
{0x0522, 1313, 1},
{0x10ba, 2823, 1},
{0xa76e, 3087, 1},
{0x1eb4, 1968, 1},
{0x04b4, 1148, 1},
{0x2c75, 2583, 1},
{0x1fb4, 50, 2},
{0x2cb4, 2664, 1},
{0xab75, 1463, 1},
{0x1ec2, 1989, 1},
{0xabb4, 1652, 1},
{0xa7b4, 3150, 1},
{0x1fc2, 253, 2},
{0x2cc2, 2685, 1},
{0x03c2, 800, 1},
{0x00c2, 83, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff26, 3174, 1},
{0x10b4, 2805, 1},
{0x1eca, 2001, 1},
{0x0551, 1430, 1},
{0x01ca, 425, 1},
{0x1fca, 2238, 1},
{0x2cca, 2697, 1},
{0x10c2, 2847, 1},
{0x00ca, 108, 1},
{0xff2e, 3198, 1},
{0x1e8c, 1923, 1},
{0x048c, 1088, 1},
{0x0226, 556, 1},
{0x1f8c, 149, 2},
{0x2c8c, 2604, 1},
{0x038c, 830, 1},
{0xffffffff, -1, 0},
{0xab8c, 1532, 1},
{0xff2c, 3192, 1},
{0x10c8c, 3393, 1},
{0x1ec4, 1992, 1},
{0x022e, 568, 1},
{0x01c4, 417, 1},
{0x1fc4, 54, 2},
{0x2cc4, 2688, 1},
{0xffffffff, -1, 0},
{0x00c4, 89, 1},
{0xff28, 3180, 1},
{0xa68c, 2952, 1},
{0x01cf, 432, 1},
{0x022c, 565, 1},
{0x118be, 3600, 1},
{0x03cf, 839, 1},
{0x00cf, 123, 1},
{0x118b5, 3573, 1},
{0xffffffff, -1, 0},
{0x10c4, 2853, 1},
{0x216e, 2334, 1},
{0x24cb, 2406, 1},
{0x0228, 559, 1},
{0xff24, 3168, 1},
{0xffffffff, -1, 0},
{0x118ba, 3588, 1},
{0x1efe, 2079, 1},
{0x04fe, 1259, 1},
{0x01fe, 499, 1},
{0x1e9e, 24, 2},
{0x049e, 1115, 1},
{0x03fe, 721, 1},
{0x1f9e, 199, 2},
{0x2c9e, 2631, 1},
{0x039e, 786, 1},
{0x0224, 553, 1},
{0xab9e, 1586, 1},
{0xa79e, 3132, 1},
{0x10c9e, 3447, 1},
{0x01f7, 414, 1},
{0x1ff7, 67, 3},
{0xff22, 3162, 1},
{0x03f7, 884, 1},
{0x118b4, 3570, 1},
{0x049c, 1112, 1},
{0x019c, 661, 1},
{0x1f9c, 189, 2},
{0x2c9c, 2628, 1},
{0x039c, 779, 1},
{0x24bc, 2361, 1},
{0xab9c, 1580, 1},
{0xa79c, 3129, 1},
{0x10c9c, 3441, 1},
{0x0222, 550, 1},
{0x1e7c, 1899, 1},
{0x047c, 1076, 1},
{0x1e82, 1908, 1},
{0x24b8, 2349, 1},
{0x0182, 357, 1},
{0x1f82, 139, 2},
{0x2c82, 2589, 1},
{0xab7c, 1484, 1},
{0xffffffff, -1, 0},
{0xab82, 1502, 1},
{0xa782, 3102, 1},
{0x10c82, 3363, 1},
{0x2c63, 1709, 1},
{0x24b6, 2343, 1},
{0x1e80, 1905, 1},
{0x0480, 1082, 1},
{0x1f59, 2190, 1},
{0x1f80, 129, 2},
{0x2c80, 2586, 1},
{0x0059, 71, 1},
{0xa682, 2937, 1},
{0xab80, 1496, 1},
{0xa780, 3099, 1},
{0x10c80, 3357, 1},
{0xffffffff, -1, 0},
{0x1e4c, 1826, 1},
{0x0145, 270, 1},
{0x014c, 279, 1},
{0x1f4c, 2184, 1},
{0x0345, 767, 1},
{0x0045, 12, 1},
{0x004c, 31, 1},
{0xa680, 2934, 1},
{0xa74c, 3036, 1},
{0x1e4a, 1823, 1},
{0x01d5, 441, 1},
{0x014a, 276, 1},
{0x1f4a, 2178, 1},
{0x03d5, 810, 1},
{0x00d5, 141, 1},
{0x004a, 24, 1},
{0x24bf, 2370, 1},
{0xa74a, 3033, 1},
{0xa64c, 2883, 1},
{0x1041c, 3321, 1},
{0x1e1c, 1754, 1},
{0x041c, 926, 1},
{0x011c, 213, 1},
{0x1f1c, 2118, 1},
{0x2c1c, 2505, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xa64a, 2880, 1},
{0x1041a, 3315, 1},
{0x1e1a, 1751, 1},
{0x041a, 920, 1},
{0x011a, 210, 1},
{0x1f1a, 2112, 1},
{0x2c1a, 2499, 1},
{0xabbd, 1679, 1},
{0x0545, 1394, 1},
{0x054c, 1415, 1},
{0x10418, 3309, 1},
{0x1e18, 1748, 1},
{0x0418, 914, 1},
{0x0118, 207, 1},
{0x1f18, 2106, 1},
{0x2c18, 2493, 1},
{0x10bd, 2832, 1},
{0x2163, 2301, 1},
{0x054a, 1409, 1},
{0x1040e, 3279, 1},
{0x1e0e, 1733, 1},
{0x040e, 1028, 1},
{0x010e, 192, 1},
{0x1f0e, 2100, 1},
{0x2c0e, 2463, 1},
{0x1efc, 2076, 1},
{0x04fc, 1256, 1},
{0x01fc, 496, 1},
{0x1ffc, 96, 2},
{0x051c, 1304, 1},
{0x1040c, 3273, 1},
{0x1e0c, 1730, 1},
{0x040c, 1022, 1},
{0x010c, 189, 1},
{0x1f0c, 2094, 1},
{0x2c0c, 2457, 1},
{0x1f6d, 2217, 1},
{0x2c6d, 607, 1},
{0x051a, 1301, 1},
{0x24be, 2367, 1},
{0x10408, 3261, 1},
{0x1e08, 1724, 1},
{0x0408, 1010, 1},
{0x0108, 183, 1},
{0x1f08, 2082, 1},
{0x2c08, 2445, 1},
{0x04c9, 1178, 1},
{0x0518, 1298, 1},
{0x1fc9, 2235, 1},
{0xffffffff, -1, 0},
{0x24ba, 2355, 1},
{0x00c9, 105, 1},
{0x10416, 3303, 1},
{0x1e16, 1745, 1},
{0x0416, 908, 1},
{0x0116, 204, 1},
{0x050e, 1283, 1},
{0x2c16, 2487, 1},
{0x10414, 3297, 1},
{0x1e14, 1742, 1},
{0x0414, 902, 1},
{0x0114, 201, 1},
{0x042b, 971, 1},
{0x2c14, 2481, 1},
{0x1f2b, 2133, 1},
{0x2c2b, 2550, 1},
{0xffffffff, -1, 0},
{0x050c, 1280, 1},
{0x10406, 3255, 1},
{0x1e06, 1721, 1},
{0x0406, 1004, 1},
{0x0106, 180, 1},
{0x13fb, 1697, 1},
{0x2c06, 2439, 1},
{0x24c2, 2379, 1},
{0x118bd, 3597, 1},
{0xffffffff, -1, 0},
{0x0508, 1274, 1},
{0x10404, 3249, 1},
{0x1e04, 1718, 1},
{0x0404, 998, 1},
{0x0104, 177, 1},
{0x1f95, 194, 2},
{0x2c04, 2433, 1},
{0x0395, 752, 1},
{0x24ca, 2403, 1},
{0xab95, 1559, 1},
{0x0531, 1334, 1},
{0x10c95, 3420, 1},
{0x0516, 1295, 1},
{0x1e6c, 1875, 1},
{0x046c, 1052, 1},
{0x016c, 327, 1},
{0x1f6c, 2214, 1},
{0x216d, 2331, 1},
{0x0514, 1292, 1},
{0x0245, 697, 1},
{0x024c, 598, 1},
{0xa76c, 3084, 1},
{0x10400, 3237, 1},
{0x1e00, 1712, 1},
{0x0400, 986, 1},
{0x0100, 171, 1},
{0x24c4, 2385, 1},
{0x2c00, 2421, 1},
{0x0506, 1271, 1},
{0x024a, 595, 1},
{0x1fab, 224, 2},
{0xa66c, 2931, 1},
{0x03ab, 827, 1},
{0x24cf, 2418, 1},
{0xabab, 1625, 1},
{0xa7ab, 631, 1},
{0x10cab, 3486, 1},
{0xffffffff, -1, 0},
{0x0504, 1268, 1},
{0xffffffff, -1, 0},
{0x021c, 544, 1},
{0x01a9, 679, 1},
{0x1fa9, 214, 2},
{0x10ab, 2778, 1},
{0x03a9, 820, 1},
{0x212b, 92, 1},
{0xaba9, 1619, 1},
{0x1e88, 1917, 1},
{0x10ca9, 3480, 1},
{0x021a, 541, 1},
{0x1f88, 129, 2},
{0x2c88, 2598, 1},
{0x0388, 730, 1},
{0x13fd, 1703, 1},
{0xab88, 1520, 1},
{0x10a9, 2772, 1},
{0x10c88, 3381, 1},
{0xffffffff, -1, 0},
{0x0218, 538, 1},
{0x0500, 1262, 1},
{0x1f4d, 2187, 1},
{0x01a7, 393, 1},
{0x1fa7, 244, 2},
{0x004d, 34, 1},
{0x03a7, 814, 1},
{0xa688, 2946, 1},
{0xaba7, 1613, 1},
{0x020e, 523, 1},
{0x10ca7, 3474, 1},
{0x1e6a, 1872, 1},
{0x046a, 1049, 1},
{0x016a, 324, 1},
{0x1f6a, 2208, 1},
{0xffffffff, -1, 0},
{0x216c, 2328, 1},
{0x10a7, 2766, 1},
{0x01d1, 435, 1},
{0xa76a, 3081, 1},
{0x020c, 520, 1},
{0x03d1, 762, 1},
{0x00d1, 129, 1},
{0x1e68, 1869, 1},
{0x0468, 1046, 1},
{0x0168, 321, 1},
{0x1f68, 2202, 1},
{0xffffffff, -1, 0},
{0xff31, 3207, 1},
{0xa66a, 2928, 1},
{0x0208, 514, 1},
{0xa768, 3078, 1},
{0x1e64, 1863, 1},
{0x0464, 1040, 1},
{0x0164, 315, 1},
{0x054d, 1418, 1},
{0x2c64, 673, 1},
{0xffffffff, -1, 0},
{0xff2b, 3189, 1},
{0xffffffff, -1, 0},
{0xa764, 3072, 1},
{0xa668, 2925, 1},
{0x0216, 535, 1},
{0xffffffff, -1, 0},
{0x118ab, 3543, 1},
{0x1e62, 1860, 1},
{0x0462, 1037, 1},
{0x0162, 312, 1},
{0x0214, 532, 1},
{0x2c62, 655, 1},
{0xa664, 2919, 1},
{0x1ed2, 2013, 1},
{0x04d2, 1193, 1},
{0xa762, 3069, 1},
{0x1fd2, 20, 3},
{0x2cd2, 2709, 1},
{0x118a9, 3537, 1},
{0x00d2, 132, 1},
{0x0206, 511, 1},
{0x10420, 3333, 1},
{0x1e20, 1760, 1},
{0x0420, 938, 1},
{0x0120, 219, 1},
{0xa662, 2916, 1},
{0x2c20, 2517, 1},
{0x1e60, 1856, 1},
{0x0460, 1034, 1},
{0x0160, 309, 1},
{0x0204, 508, 1},
{0x2c60, 2562, 1},
{0xffffffff, -1, 0},
{0x24bd, 2364, 1},
{0x216a, 2322, 1},
{0xa760, 3066, 1},
{0xffffffff, -1, 0},
{0xfb16, 125, 2},
{0x118a7, 3531, 1},
{0x1efa, 2073, 1},
{0x04fa, 1253, 1},
{0x01fa, 493, 1},
{0x1ffa, 2262, 1},
{0xfb14, 109, 2},
{0x03fa, 887, 1},
{0xa660, 2913, 1},
{0x2168, 2316, 1},
{0x01b7, 700, 1},
{0x1fb7, 10, 3},
{0x1f6b, 2211, 1},
{0x2c6b, 2577, 1},
{0x0200, 502, 1},
{0xabb7, 1661, 1},
{0xfb06, 29, 2},
{0x1e56, 1841, 1},
{0x2164, 2304, 1},
{0x0156, 294, 1},
{0x1f56, 62, 3},
{0x0520, 1310, 1},
{0x004f, 40, 1},
{0x0056, 62, 1},
{0x10b7, 2814, 1},
{0xa756, 3051, 1},
{0xfb04, 5, 3},
{0x1e78, 1893, 1},
{0x0478, 1070, 1},
{0x0178, 168, 1},
{0x1e54, 1838, 1},
{0x2162, 2298, 1},
{0x0154, 291, 1},
{0x1f54, 57, 3},
{0xab78, 1472, 1},
{0xa656, 2898, 1},
{0x0054, 56, 1},
{0x1e52, 1835, 1},
{0xa754, 3048, 1},
{0x0152, 288, 1},
{0x1f52, 52, 3},
{0x24c9, 2400, 1},
{0x1e32, 1787, 1},
{0x0052, 49, 1},
{0x0132, 243, 1},
{0xa752, 3045, 1},
{0xffffffff, -1, 0},
{0xfb00, 4, 2},
{0xa654, 2895, 1},
{0xffffffff, -1, 0},
{0xa732, 2997, 1},
{0x2160, 2292, 1},
{0x054f, 1424, 1},
{0x0556, 1445, 1},
{0x1e50, 1832, 1},
{0xa652, 2892, 1},
{0x0150, 285, 1},
{0x1f50, 84, 2},
{0x017b, 348, 1},
{0x1e4e, 1829, 1},
{0x0050, 43, 1},
{0x014e, 282, 1},
{0xa750, 3042, 1},
{0xab7b, 1481, 1},
{0xa77b, 3093, 1},
{0x004e, 37, 1},
{0x0554, 1439, 1},
{0xa74e, 3039, 1},
{0x1e48, 1820, 1},
{0xffffffff, -1, 0},
{0x216b, 2325, 1},
{0x1f48, 2172, 1},
{0xa650, 2889, 1},
{0x0552, 1433, 1},
{0x0048, 21, 1},
{0xffffffff, -1, 0},
{0xa748, 3030, 1},
{0xa64e, 2886, 1},
{0x0532, 1337, 1},
{0x1041e, 3327, 1},
{0x1e1e, 1757, 1},
{0x041e, 932, 1},
{0x011e, 216, 1},
{0x118b7, 3579, 1},
{0x2c1e, 2511, 1},
{0xffffffff, -1, 0},
{0xa648, 2877, 1},
{0x1ff9, 2253, 1},
{0xffffffff, -1, 0},
{0x03f9, 878, 1},
{0x0550, 1427, 1},
{0x10412, 3291, 1},
{0x1e12, 1739, 1},
{0x0412, 896, 1},
{0x0112, 198, 1},
{0x054e, 1421, 1},
{0x2c12, 2475, 1},
{0x10410, 3285, 1},
{0x1e10, 1736, 1},
{0x0410, 890, 1},
{0x0110, 195, 1},
{0xffffffff, -1, 0},
{0x2c10, 2469, 1},
{0x2132, 2289, 1},
{0x0548, 1403, 1},
{0x1ef8, 2070, 1},
{0x04f8, 1250, 1},
{0x01f8, 490, 1},
{0x1ff8, 2250, 1},
{0x0220, 381, 1},
{0x1ee2, 2037, 1},
{0x04e2, 1217, 1},
{0x01e2, 462, 1},
{0x1fe2, 36, 3},
{0x2ce2, 2733, 1},
{0x03e2, 857, 1},
{0x051e, 1307, 1},
{0x1ede, 2031, 1},
{0x04de, 1211, 1},
{0x01de, 456, 1},
{0xffffffff, -1, 0},
{0x2cde, 2727, 1},
{0x03de, 851, 1},
{0x00de, 165, 1},
{0x1f69, 2205, 1},
{0x2c69, 2574, 1},
{0x1eda, 2025, 1},
{0x04da, 1205, 1},
{0x0512, 1289, 1},
{0x1fda, 2244, 1},
{0x2cda, 2721, 1},
{0x03da, 845, 1},
{0x00da, 153, 1},
{0xffffffff, -1, 0},
{0x0510, 1286, 1},
{0x1ed8, 2022, 1},
{0x04d8, 1202, 1},
{0xffffffff, -1, 0},
{0x1fd8, 2274, 1},
{0x2cd8, 2718, 1},
{0x03d8, 842, 1},
{0x00d8, 147, 1},
{0x1ed6, 2019, 1},
{0x04d6, 1199, 1},
{0xffffffff, -1, 0},
{0x1fd6, 76, 2},
{0x2cd6, 2715, 1},
{0x03d6, 792, 1},
{0x00d6, 144, 1},
{0x1ec8, 1998, 1},
{0xffffffff, -1, 0},
{0x01c8, 421, 1},
{0x1fc8, 2232, 1},
{0x2cc8, 2694, 1},
{0xff32, 3210, 1},
{0x00c8, 102, 1},
{0x04c7, 1175, 1},
{0x01c7, 421, 1},
{0x1fc7, 15, 3},
{0x1ec0, 1986, 1},
{0x04c0, 1187, 1},
{0x00c7, 99, 1},
{0xffffffff, -1, 0},
{0x2cc0, 2682, 1},
{0x0179, 345, 1},
{0x00c0, 77, 1},
{0x0232, 574, 1},
{0x01b3, 402, 1},
{0x1fb3, 62, 2},
{0xab79, 1475, 1},
{0xa779, 3090, 1},
{0x10c7, 2859, 1},
{0xabb3, 1649, 1},
{0xa7b3, 3156, 1},
{0x1fa5, 234, 2},
{0x10c0, 2841, 1},
{0x03a5, 807, 1},
{0xffffffff, -1, 0},
{0xaba5, 1607, 1},
{0x01b1, 691, 1},
{0x10ca5, 3468, 1},
{0x10b3, 2802, 1},
{0x2169, 2319, 1},
{0x024e, 601, 1},
{0xabb1, 1643, 1},
{0xa7b1, 682, 1},
{0x10cb1, 3504, 1},
{0x10a5, 2760, 1},
{0xffffffff, -1, 0},
{0x01af, 399, 1},
{0x1faf, 244, 2},
{0xffffffff, -1, 0},
{0x0248, 592, 1},
{0x10b1, 2796, 1},
{0xabaf, 1637, 1},
{0x1fad, 234, 2},
{0x10caf, 3498, 1},
{0x04cd, 1184, 1},
{0x01cd, 429, 1},
{0xabad, 1631, 1},
{0xa7ad, 658, 1},
{0x10cad, 3492, 1},
{0x00cd, 117, 1},
{0x10af, 2790, 1},
{0x021e, 547, 1},
{0x1fa3, 224, 2},
{0xffffffff, -1, 0},
{0x03a3, 800, 1},
{0x10ad, 2784, 1},
{0xaba3, 1601, 1},
{0xffffffff, -1, 0},
{0x10ca3, 3462, 1},
{0x10cd, 2862, 1},
{0x1fa1, 214, 2},
{0x24b7, 2346, 1},
{0x03a1, 796, 1},
{0x0212, 529, 1},
{0xaba1, 1595, 1},
{0x10a3, 2754, 1},
{0x10ca1, 3456, 1},
{0x01d3, 438, 1},
{0x1fd3, 25, 3},
{0x0210, 526, 1},
{0xffffffff, -1, 0},
{0x00d3, 135, 1},
{0x1e97, 34, 2},
{0x10a1, 2748, 1},
{0x0197, 649, 1},
{0x1f97, 204, 2},
{0xffffffff, -1, 0},
{0x0397, 759, 1},
{0x1041d, 3324, 1},
{0xab97, 1565, 1},
{0x041d, 929, 1},
{0x10c97, 3426, 1},
{0x1f1d, 2121, 1},
{0x2c1d, 2508, 1},
{0x1e72, 1884, 1},
{0x0472, 1061, 1},
{0x0172, 336, 1},
{0x118b3, 3567, 1},
{0x2c72, 2580, 1},
{0x0372, 712, 1},
{0x1041b, 3318, 1},
{0xab72, 1454, 1},
{0x041b, 923, 1},
{0x118a5, 3525, 1},
{0x1f1b, 2115, 1},
{0x2c1b, 2502, 1},
{0x1e70, 1881, 1},
{0x0470, 1058, 1},
{0x0170, 333, 1},
{0x118b1, 3561, 1},
{0x2c70, 610, 1},
{0x0370, 709, 1},
{0x1e46, 1817, 1},
{0xab70, 1448, 1},
{0x1e66, 1866, 1},
{0x0466, 1043, 1},
{0x0166, 318, 1},
{0x1e44, 1814, 1},
{0x0046, 15, 1},
{0x118af, 3555, 1},
{0xa746, 3027, 1},
{0xffffffff, -1, 0},
{0xa766, 3075, 1},
{0x0044, 9, 1},
{0x118ad, 3549, 1},
{0xa744, 3024, 1},
{0x1e7a, 1896, 1},
{0x047a, 1073, 1},
{0x1e3a, 1799, 1},
{0xffffffff, -1, 0},
{0xa646, 2874, 1},
{0x1f3a, 2154, 1},
{0xa666, 2922, 1},
{0xab7a, 1478, 1},
{0x118a3, 3519, 1},
{0xa644, 2871, 1},
{0xa73a, 3009, 1},
{0xffffffff, -1, 0},
{0x1ef4, 2064, 1},
{0x04f4, 1244, 1},
{0x01f4, 487, 1},
{0x1ff4, 101, 2},
{0x118a1, 3513, 1},
{0x03f4, 762, 1},
{0x1eec, 2052, 1},
{0x04ec, 1232, 1},
{0x01ec, 477, 1},
{0x1fec, 2286, 1},
{0x0546, 1397, 1},
{0x03ec, 872, 1},
{0xffffffff, -1, 0},
{0x013f, 261, 1},
{0x1f3f, 2169, 1},
{0x0544, 1391, 1},
{0x1eea, 2049, 1},
{0x04ea, 1229, 1},
{0x01ea, 474, 1},
{0x1fea, 2256, 1},
{0xffffffff, -1, 0},
{0x03ea, 869, 1},
{0x1ee8, 2046, 1},
{0x04e8, 1226, 1},
{0x01e8, 471, 1},
{0x1fe8, 2280, 1},
{0x053a, 1361, 1},
{0x03e8, 866, 1},
{0x1ee6, 2043, 1},
{0x04e6, 1223, 1},
{0x01e6, 468, 1},
{0x1fe6, 88, 2},
{0x1f4b, 2181, 1},
{0x03e6, 863, 1},
{0x1e5e, 1853, 1},
{0x004b, 27, 1},
{0x015e, 306, 1},
{0x2166, 2310, 1},
{0x1ee4, 2040, 1},
{0x04e4, 1220, 1},
{0x01e4, 465, 1},
{0x1fe4, 80, 2},
{0xa75e, 3063, 1},
{0x03e4, 860, 1},
{0x1ee0, 2034, 1},
{0x04e0, 1214, 1},
{0x01e0, 459, 1},
{0x053f, 1376, 1},
{0x2ce0, 2730, 1},
{0x03e0, 854, 1},
{0x1edc, 2028, 1},
{0x04dc, 1208, 1},
{0xa65e, 2910, 1},
{0xffffffff, -1, 0},
{0x2cdc, 2724, 1},
{0x03dc, 848, 1},
{0x00dc, 159, 1},
{0x1ed0, 2010, 1},
{0x04d0, 1190, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x2cd0, 2706, 1},
{0x03d0, 742, 1},
{0x00d0, 126, 1},
{0x1ecc, 2004, 1},
{0x054b, 1412, 1},
{0xffffffff, -1, 0},
{0x1fcc, 71, 2},
{0x2ccc, 2700, 1},
{0x1ec6, 1995, 1},
{0x00cc, 114, 1},
{0xffffffff, -1, 0},
{0x1fc6, 67, 2},
{0x2cc6, 2691, 1},
{0x24c8, 2397, 1},
{0x00c6, 96, 1},
{0x04c5, 1172, 1},
{0x01c5, 417, 1},
{0xffffffff, -1, 0},
{0x1fbb, 2229, 1},
{0x24c7, 2394, 1},
{0x00c5, 92, 1},
{0x1fb9, 2271, 1},
{0xabbb, 1673, 1},
{0x24c0, 2373, 1},
{0x04c3, 1169, 1},
{0xabb9, 1667, 1},
{0x1fc3, 71, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x00c3, 86, 1},
{0x10c5, 2856, 1},
{0x10bb, 2826, 1},
{0x1ed4, 2016, 1},
{0x04d4, 1196, 1},
{0x10b9, 2820, 1},
{0x13fc, 1700, 1},
{0x2cd4, 2712, 1},
{0x0246, 589, 1},
{0x00d4, 138, 1},
{0x10c3, 2850, 1},
{0xffffffff, -1, 0},
{0xff3a, 3234, 1},
{0x0244, 688, 1},
{0x019f, 670, 1},
{0x1f9f, 204, 2},
{0xffffffff, -1, 0},
{0x039f, 789, 1},
{0xffffffff, -1, 0},
{0xab9f, 1589, 1},
{0xffffffff, -1, 0},
{0x10c9f, 3450, 1},
{0x019d, 667, 1},
{0x1f9d, 194, 2},
{0x023a, 2565, 1},
{0x039d, 783, 1},
{0x1e5a, 1847, 1},
{0xab9d, 1583, 1},
{0x015a, 300, 1},
{0x10c9d, 3444, 1},
{0x1e9b, 1856, 1},
{0x24cd, 2412, 1},
{0x005a, 74, 1},
{0x1f9b, 184, 2},
{0xa75a, 3057, 1},
{0x039b, 776, 1},
{0x1ece, 2007, 1},
{0xab9b, 1577, 1},
{0x1e99, 42, 2},
{0x10c9b, 3438, 1},
{0x2cce, 2703, 1},
{0x1f99, 174, 2},
{0x00ce, 120, 1},
{0x0399, 767, 1},
{0xa65a, 2904, 1},
{0xab99, 1571, 1},
{0xffffffff, -1, 0},
{0x10c99, 3432, 1},
{0x0193, 634, 1},
{0x1f93, 184, 2},
{0x1e58, 1844, 1},
{0x0393, 746, 1},
{0x0158, 297, 1},
{0xab93, 1553, 1},
{0xffffffff, -1, 0},
{0x10c93, 3414, 1},
{0x0058, 68, 1},
{0x042d, 977, 1},
{0xa758, 3054, 1},
{0x1f2d, 2139, 1},
{0x2c2d, 2556, 1},
{0x118bb, 3591, 1},
{0x0191, 369, 1},
{0x1f91, 174, 2},
{0x118b9, 3585, 1},
{0x0391, 739, 1},
{0xffffffff, -1, 0},
{0xab91, 1547, 1},
{0xa658, 2901, 1},
{0x10c91, 3408, 1},
{0x018f, 625, 1},
{0x1f8f, 164, 2},
{0xffffffff, -1, 0},
{0x038f, 836, 1},
{0xffffffff, -1, 0},
{0xab8f, 1541, 1},
{0xffffffff, -1, 0},
{0x10c8f, 3402, 1},
{0x018b, 366, 1},
{0x1f8b, 144, 2},
{0xffffffff, -1, 0},
{0x0187, 363, 1},
{0x1f87, 164, 2},
{0xab8b, 1529, 1},
{0xa78b, 3111, 1},
{0x10c8b, 3390, 1},
{0xab87, 1517, 1},
{0x04c1, 1166, 1},
{0x10c87, 3378, 1},
{0x1e7e, 1902, 1},
{0x047e, 1079, 1},
{0xffffffff, -1, 0},
{0x00c1, 80, 1},
{0x2c7e, 580, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xab7e, 1490, 1},
{0xa77e, 3096, 1},
{0x1e76, 1890, 1},
{0x0476, 1067, 1},
{0x0176, 342, 1},
{0x1e42, 1811, 1},
{0x10c1, 2844, 1},
{0x0376, 715, 1},
{0x1e36, 1793, 1},
{0xab76, 1466, 1},
{0x0136, 249, 1},
{0x0042, 3, 1},
{0x1e3e, 1805, 1},
{0xa742, 3021, 1},
{0x1e38, 1796, 1},
{0x1f3e, 2166, 1},
{0xa736, 3003, 1},
{0x1f38, 2148, 1},
{0xffffffff, -1, 0},
{0x0587, 105, 2},
{0xa73e, 3015, 1},
{0xffffffff, -1, 0},
{0xa738, 3006, 1},
{0xa642, 2868, 1},
{0x1e5c, 1850, 1},
{0x1e34, 1790, 1},
{0x015c, 303, 1},
{0x0134, 246, 1},
{0x1ef6, 2067, 1},
{0x04f6, 1247, 1},
{0x01f6, 372, 1},
{0x1ff6, 92, 2},
{0xa75c, 3060, 1},
{0xa734, 3000, 1},
{0x1ef0, 2058, 1},
{0x04f0, 1238, 1},
{0x01f0, 20, 2},
{0xffffffff, -1, 0},
{0x1e30, 1784, 1},
{0x03f0, 772, 1},
{0x0130, 261, 2},
{0x0542, 1385, 1},
{0xa65c, 2907, 1},
{0x1f83, 144, 2},
{0x0536, 1349, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xab83, 1505, 1},
{0x053e, 1373, 1},
{0x10c83, 3366, 1},
{0x0538, 1355, 1},
{0x1eee, 2055, 1},
{0x04ee, 1235, 1},
{0x01ee, 480, 1},
{0x1f8d, 154, 2},
{0xffffffff, -1, 0},
{0x03ee, 875, 1},
{0xffffffff, -1, 0},
{0xab8d, 1535, 1},
{0xa78d, 643, 1},
{0x10c8d, 3396, 1},
{0x0534, 1343, 1},
{0x0181, 613, 1},
{0x1f81, 134, 2},
{0x013d, 258, 1},
{0x1f3d, 2163, 1},
{0xffffffff, -1, 0},
{0xab81, 1499, 1},
{0x017f, 52, 1},
{0x10c81, 3360, 1},
{0x2c7f, 583, 1},
{0x037f, 881, 1},
{0xff2d, 3195, 1},
{0xab7f, 1493, 1},
{0x1e74, 1887, 1},
{0x0474, 1064, 1},
{0x0174, 339, 1},
{0x1e3c, 1802, 1},
{0x0149, 46, 2},
{0x1f49, 2175, 1},
{0x1f3c, 2160, 1},
{0xab74, 1460, 1},
{0x0049, 3606, 1},
{0x0143, 267, 1},
{0x24cc, 2409, 1},
{0xa73c, 3012, 1},
{0xffffffff, -1, 0},
{0x0043, 6, 1},
{0x0141, 264, 1},
{0x24c6, 2391, 1},
{0x013b, 255, 1},
{0x1f3b, 2157, 1},
{0x0041, 0, 1},
{0x0139, 252, 1},
{0x1f39, 2151, 1},
{0x24c5, 2388, 1},
{0x24bb, 2358, 1},
{0x13fa, 1694, 1},
{0x053d, 1370, 1},
{0x24b9, 2352, 1},
{0x0429, 965, 1},
{0x2183, 2340, 1},
{0x1f29, 2127, 1},
{0x2c29, 2544, 1},
{0x24c3, 2382, 1},
{0x10427, 3354, 1},
{0x10425, 3348, 1},
{0x0427, 959, 1},
{0x0425, 953, 1},
{0xffffffff, -1, 0},
{0x2c27, 2538, 1},
{0x2c25, 2532, 1},
{0x0549, 1406, 1},
{0x053c, 1367, 1},
{0x10423, 3342, 1},
{0xffffffff, -1, 0},
{0x0423, 947, 1},
{0x0543, 1388, 1},
{0xffffffff, -1, 0},
{0x2c23, 2526, 1},
{0xff36, 3222, 1},
{0xffffffff, -1, 0},
{0x0541, 1382, 1},
{0x10421, 3336, 1},
{0x053b, 1364, 1},
{0x0421, 941, 1},
{0xff38, 3228, 1},
{0x0539, 1358, 1},
{0x2c21, 2520, 1},
{0x10419, 3312, 1},
{0x10417, 3306, 1},
{0x0419, 917, 1},
{0x0417, 911, 1},
{0x1f19, 2109, 1},
{0x2c19, 2496, 1},
{0x2c17, 2490, 1},
{0x023e, 2568, 1},
{0xff34, 3216, 1},
{0x10415, 3300, 1},
{0x10413, 3294, 1},
{0x0415, 905, 1},
{0x0413, 899, 1},
{0xffffffff, -1, 0},
{0x2c15, 2484, 1},
{0x2c13, 2478, 1},
{0xffffffff, -1, 0},
{0x24ce, 2415, 1},
{0x1040f, 3282, 1},
{0xffffffff, -1, 0},
{0x040f, 1031, 1},
{0xff30, 3204, 1},
{0x1f0f, 2103, 1},
{0x2c0f, 2466, 1},
{0x1040d, 3276, 1},
{0xffffffff, -1, 0},
{0x040d, 1025, 1},
{0x0147, 273, 1},
{0x1f0d, 2097, 1},
{0x2c0d, 2460, 1},
{0x1040b, 3270, 1},
{0x0047, 18, 1},
{0x040b, 1019, 1},
{0x0230, 571, 1},
{0x1f0b, 2091, 1},
{0x2c0b, 2454, 1},
{0x10409, 3264, 1},
{0x10405, 3252, 1},
{0x0409, 1013, 1},
{0x0405, 1001, 1},
{0x1f09, 2085, 1},
{0x2c09, 2448, 1},
{0x2c05, 2436, 1},
{0x10403, 3246, 1},
{0x10401, 3240, 1},
{0x0403, 995, 1},
{0x0401, 989, 1},
{0xffffffff, -1, 0},
{0x2c03, 2430, 1},
{0x2c01, 2424, 1},
{0x13f9, 1691, 1},
{0x042f, 983, 1},
{0xffffffff, -1, 0},
{0x1f2f, 2145, 1},
{0x1041f, 3330, 1},
{0xffffffff, -1, 0},
{0x041f, 935, 1},
{0x023d, 378, 1},
{0x10411, 3288, 1},
{0x2c1f, 2514, 1},
{0x0411, 893, 1},
{0x0547, 1400, 1},
{0xffffffff, -1, 0},
{0x2c11, 2472, 1},
{0x10407, 3258, 1},
{0xffffffff, -1, 0},
{0x0407, 1007, 1},
{0x24c1, 2376, 1},
{0xffffffff, -1, 0},
{0x2c07, 2442, 1},
{0xffffffff, -1, 0},
{0x13f8, 1688, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff39, 3231, 1},
{0xffffffff, -1, 0},
{0x0243, 354, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x0241, 586, 1},
{0xff29, 3183, 1},
{0x023b, 577, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff27, 3177, 1},
{0xff25, 3171, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff23, 3165, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff21, 3159, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0xfb17, 117, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff2f, 3201, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xfb15, 113, 2},
{0xfb13, 121, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0xfb05, 29, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xfb03, 0, 3},
{0xfb01, 8, 2}
};
if (0 == 0)
{
int key = hash(&code);
if (key <= MAX_HASH_VALUE && key >= 0)
{
OnigCodePoint gcode = wordlist[key].code;
if (code == gcode)
return &wordlist[key];
}
}
return 0;
}
| 128,717,731,226,755,270,000,000,000,000,000,000,000 | None | null | [
"CWE-787"
] | CVE-2017-9225 | An issue was discovered in Oniguruma 6.2.0, as used in Oniguruma-mod in Ruby through 2.4.1 and mbstring in PHP through 7.1.5. A stack out-of-bounds write in onigenc_unicode_get_case_fold_codes_by_str() occurs during regular expression compilation. Code point 0xFFFFFFFF is not properly handled in unicode_unfold_key(). A malformed regular expression could result in 4 bytes being written off the end of a stack buffer of expand_case_fold_string() during the call to onigenc_unicode_get_case_fold_codes_by_str(), a typical stack buffer overflow. | https://nvd.nist.gov/vuln/detail/CVE-2017-9225 |
2,770 | oniguruma | 690313a061f7a4fa614ec5cc8368b4f2284e059b | https://github.com/kkos/oniguruma | https://github.com/kkos/oniguruma/commit/690313a061f7a4fa614ec5cc8368b4f2284e059b | fix #57 : DATA_ENSURE() check must be before data access | 1 | match_at(regex_t* reg, const UChar* str, const UChar* end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar* right_range,
#endif
const UChar* sstart, UChar* sprev, OnigMatchArg* msa)
{
static UChar FinishCode[] = { OP_FINISH };
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *sbegin;
int is_alloca;
char *alloc_base;
OnigStackType *stk_base, *stk, *stk_end;
OnigStackType *stkp; /* used as any purpose. */
OnigStackIndex si;
OnigStackIndex *repeat_stk;
OnigStackIndex *mem_start_stk, *mem_end_stk;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
int scv;
unsigned char* state_check_buff = msa->state_check_buff;
int num_comb_exp_check = reg->num_comb_exp_check;
#endif
UChar *p = reg->p;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n",
(int )str, (int )end, (int )sstart, (int )sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */
best_len = ONIG_MISMATCH;
s = (UChar* )sstart;
while (1) {
#ifdef ONIG_DEBUG_MATCH
{
UChar *q, *bp, buf[50];
int len;
fprintf(stderr, "%4d> \"", (int )(s - str));
bp = buf;
for (i = 0, q = s; i < 7 && q < end; i++) {
len = enclen(encode, q);
while (len-- > 0) *bp++ = *q++;
}
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }
else { xmemcpy(bp, "\"", 1); bp += 1; }
*bp = 0;
fputs((char* )buf, stderr);
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);
onig_print_compiled_byte_code(stderr, p, NULL, encode);
fprintf(stderr, "\n");
}
#endif
sbegin = s;
switch (*p++) {
case OP_END: MOP_IN(OP_END);
n = s - sstart;
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = sstart - str;
rmt[0].rm_eo = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str;
rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = sstart - str;
region->end[0] = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str;
region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = sstart - str;
node->end = s - str;
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
MOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
break;
case OP_EXACT1: MOP_IN(OP_EXACT1);
#if 0
DATA_ENSURE(1);
if (*p != *s) goto fail;
p++; s++;
#endif
if (*p != *s++) goto fail;
DATA_ENSURE(0);
p++;
MOP_OUT;
break;
case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC);
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) {
goto fail;
}
p++; q++;
}
}
MOP_OUT;
break;
case OP_EXACT2: MOP_IN(OP_EXACT2);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT3: MOP_IN(OP_EXACT3);
DATA_ENSURE(3);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT4: MOP_IN(OP_EXACT4);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT5: MOP_IN(OP_EXACT5);
DATA_ENSURE(5);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTN: MOP_IN(OP_EXACTN);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen);
while (tlen-- > 0) {
if (*p++ != *s++) goto fail;
}
sprev = s - 1;
MOP_OUT;
continue;
break;
case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC);
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
GET_LENGTH_INC(tlen, p);
endp = p + tlen;
while (p < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) goto fail;
p++; q++;
}
}
}
MOP_OUT;
continue;
break;
case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3);
DATA_ENSURE(6);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 2);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 2;
MOP_OUT;
continue;
break;
case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 3);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 3;
MOP_OUT;
continue;
break;
case OP_EXACTMBN: MOP_IN(OP_EXACTMBN);
GET_LENGTH_INC(tlen, p); /* mb-len */
GET_LENGTH_INC(tlen2, p); /* string len */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
while (tlen2-- > 0) {
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - tlen;
MOP_OUT;
continue;
break;
case OP_CCLASS: MOP_IN(OP_CCLASS);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */
MOP_OUT;
break;
case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (! onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (! onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
MOP_OUT;
break;
case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) == 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
GET_LENGTH_INC(tlen, p);
p += tlen;
goto cc_mb_not_success;
}
cclass_mb_not:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
p += tlen;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
cc_mb_not_success:
MOP_OUT;
break;
case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb_not;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) != 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE);
{
OnigCodePoint code;
void *node;
int mb_len;
UChar *ss;
DATA_ENSURE(1);
GET_POINTER_INC(node, p);
mb_len = enclen(encode, s);
ss = s;
s += mb_len;
DATA_ENSURE(0);
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail;
}
MOP_OUT;
break;
case OP_ANYCHAR: MOP_IN(OP_ANYCHAR);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
p++;
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
p++;
MOP_OUT;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_STATE_CHECK_ANYCHAR_ML_STAR:
MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_WORD: MOP_IN(OP_WORD);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_NOT_WORD: MOP_IN(OP_NOT_WORD);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (! ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
== ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
!= ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
#ifdef USE_WORD_BEGIN_END
case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN);
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) {
if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
case OP_WORD_END: MOP_IN(OP_WORD_END);
if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
#endif
case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF);
if (! ON_STR_BEGIN(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_END_BUF: MOP_IN(OP_END_BUF);
if (! ON_STR_END(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE);
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
MOP_OUT;
continue;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
MOP_OUT;
continue;
}
goto fail;
break;
case OP_END_LINE: MOP_IN(OP_END_LINE);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
MOP_OUT;
continue;
}
#endif
goto fail;
break;
case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
MOP_OUT;
continue;
}
}
#endif
goto fail;
break;
case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION);
if (s != msa->start)
goto fail;
MOP_OUT;
continue;
break;
case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_START(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_START: MOP_IN(OP_MEMORY_START);
GET_MEMNUM_INC(mem, p);
mem_start_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_END(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END: MOP_IN(OP_MEMORY_END);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
#ifdef USE_SUBEXP_CALL
case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC);
GET_MEMNUM_INC(mem, p);
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
MOP_OUT;
continue;
break;
#endif
case OP_BACKREF1: MOP_IN(OP_BACKREF1);
mem = 1;
goto backref;
break;
case OP_BACKREF2: MOP_IN(OP_BACKREF2);
mem = 2;
goto backref;
break;
case OP_BACKREFN: MOP_IN(OP_BACKREFN);
GET_MEMNUM_INC(mem, p);
backref:
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP(pstart, s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC);
GET_MEMNUM_INC(mem, p);
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(pstart, swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
{
int len;
OnigOptionType ic;
LengthType level;
GET_OPTION_INC(ic, p);
GET_LENGTH_INC(level, p);
GET_LENGTH_INC(tlen, p);
sprev = s;
if (backref_match_at_nested_level(reg, stk, stk_base, ic
, case_fold_flag, (int )level, (int )tlen, p, &s, end)) {
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * tlen);
}
else
goto fail;
MOP_OUT;
continue;
}
break;
#endif
#if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */
case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH);
GET_OPTION_INC(option, p);
STACK_PUSH_ALT(p, s, sprev);
p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL;
MOP_OUT;
continue;
break;
case OP_SET_OPTION: MOP_IN(OP_SET_OPTION);
GET_OPTION_INC(option, p);
MOP_OUT;
continue;
break;
#endif
case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START);
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_PUSH_NULL_CHECK_START(mem, s);
MOP_OUT;
continue;
break;
case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK(isnull, mem, s);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
null_check_found:
/* empty loop founded, skip next instruction */
switch (*p++) {
case OP_JUMP:
case OP_PUSH:
p += SIZE_RELADDR;
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
p += SIZE_MEMNUM;
break;
default:
goto unexpected_bytecode_error;
break;
}
}
}
MOP_OUT;
continue;
break;
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK_MEMST(isnull, mem, s, reg);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
}
MOP_OUT;
continue;
break;
#endif
#ifdef USE_SUBEXP_CALL
case OP_NULL_CHECK_END_MEMST_PUSH:
MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg);
#else
STACK_NULL_CHECK_REC(isnull, mem, s);
#endif
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
else {
STACK_PUSH_NULL_CHECK_END(mem);
}
}
MOP_OUT;
continue;
break;
#endif
case OP_JUMP: MOP_IN(OP_JUMP);
GET_RELADDR_INC(addr, p);
p += addr;
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_PUSH: MOP_IN(OP_PUSH);
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
MOP_OUT;
continue;
break;
case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP);
GET_STATE_CHECK_NUM_INC(mem, p);
GET_RELADDR_INC(addr, p);
STATE_CHECK_VAL(scv, mem);
if (scv) {
p += addr;
}
else {
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
}
MOP_OUT;
continue;
break;
case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_STATE_CHECK(s, mem);
MOP_OUT;
continue;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_POP: MOP_IN(OP_POP);
STACK_POP_ONE;
MOP_OUT;
continue;
break;
case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1);
GET_RELADDR_INC(addr, p);
if (*p == *s && DATA_ENSURE_CHECK1) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p += (addr + 1);
MOP_OUT;
continue;
break;
case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT);
GET_RELADDR_INC(addr, p);
if (*p == *s) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p++;
MOP_OUT;
continue;
break;
case OP_REPEAT: MOP_IN(OP_REPEAT);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p, s, sprev);
p += addr;
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
break;
case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
UChar* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
}
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
break;
case OP_PUSH_POS: MOP_IN(OP_PUSH_POS);
STACK_PUSH_POS(s, sprev);
MOP_OUT;
continue;
break;
case OP_POP_POS: MOP_IN(OP_POP_POS);
{
STACK_POS_END(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
}
MOP_OUT;
continue;
break;
case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT);
GET_RELADDR_INC(addr, p);
STACK_PUSH_POS_NOT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
case OP_FAIL_POS: MOP_IN(OP_FAIL_POS);
STACK_POP_TIL_POS_NOT;
goto fail;
break;
case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT);
STACK_PUSH_STOP_BT;
MOP_OUT;
continue;
break;
case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT);
STACK_STOP_BT_END;
MOP_OUT;
continue;
break;
case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND);
GET_LENGTH_INC(tlen, p);
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
MOP_OUT;
continue;
break;
case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT);
GET_RELADDR_INC(addr, p);
GET_LENGTH_INC(tlen, p);
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
}
MOP_OUT;
continue;
break;
case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT);
STACK_POP_TIL_LOOK_BEHIND_NOT;
goto fail;
break;
#ifdef USE_SUBEXP_CALL
case OP_CALL: MOP_IN(OP_CALL);
GET_ABSADDR_INC(addr, p);
STACK_PUSH_CALL_FRAME(p);
p = reg->p + addr;
MOP_OUT;
continue;
break;
case OP_RETURN: MOP_IN(OP_RETURN);
STACK_RETURN(p);
STACK_PUSH_RETURN;
MOP_OUT;
continue;
break;
#endif
case OP_FINISH:
goto finish;
break;
fail:
MOP_OUT;
/* fall */
case OP_FAIL: MOP_IN(OP_FAIL);
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
if (stk->u.state.state_check != 0) {
stk->type = STK_STATE_CHECK_MARK;
stk++;
}
#endif
MOP_OUT;
continue;
break;
default:
goto bytecode_error;
} /* end of switch */
sprev = sbegin;
} /* end of while(1) */
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
}
| 332,565,493,828,376,550,000,000,000,000,000,000,000 | None | null | [
"CWE-125"
] | CVE-2017-9224 | An issue was discovered in Oniguruma 6.2.0, as used in Oniguruma-mod in Ruby through 2.4.1 and mbstring in PHP through 7.1.5. A stack out-of-bounds read occurs in match_at() during regular expression searching. A logical error involving order of validation and access in match_at() could result in an out-of-bounds read from a stack buffer. | https://nvd.nist.gov/vuln/detail/CVE-2017-9224 |
2,771 | systemd | a924f43f30f9c4acaf70618dd2a055f8b0f166be | https://github.com/systemd/systemd | https://github.com/systemd/systemd/commit/a924f43f30f9c4acaf70618dd2a055f8b0f166be | resolved: bugfix of null pointer p->question dereferencing (#6020)
See https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1621396 | 1 | int dns_packet_is_reply_for(DnsPacket *p, const DnsResourceKey *key) {
int r;
assert(p);
assert(key);
/* Checks if the specified packet is a reply for the specified
* key and the specified key is the only one in the question
* section. */
if (DNS_PACKET_QR(p) != 1)
return 0;
/* Let's unpack the packet, if that hasn't happened yet. */
r = dns_packet_extract(p);
if (r < 0)
return r;
if (p->question->n_keys != 1)
return 0;
return dns_resource_key_equal(p->question->keys[0], key);
}
| 149,971,713,116,709,730,000,000,000,000,000,000,000 | None | null | [
"CWE-20"
] | CVE-2017-9217 | systemd-resolved through 233 allows remote attackers to cause a denial of service (daemon crash) via a crafted DNS response with an empty question section. | https://nvd.nist.gov/vuln/detail/CVE-2017-9217 |
2,772 | linux | 9933e113c2e87a9f46a40fde8dafbf801dca1ab9 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/9933e113c2e87a9f46a40fde8dafbf801dca1ab9 | crypto: skcipher - Add missing API setkey checks
The API setkey checks for key sizes and alignment went AWOL during the
skcipher conversion. This patch restores them.
Cc: <stable@vger.kernel.org>
Fixes: 4e6c3df4d729 ("crypto: skcipher - Add low-level skcipher...")
Reported-by: Baozeng <sploving1@gmail.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> | 1 | static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = alg->setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
}
| 61,488,329,509,381,175,000,000,000,000,000,000,000 | skcipher.c | 125,395,647,683,953,660,000,000,000,000,000,000,000 | [
"CWE-476"
] | CVE-2017-9211 | The crypto_skcipher_init_tfm function in crypto/skcipher.c in the Linux kernel through 4.11.2 relies on a setkey function that lacks a key-size check, which allows local users to cause a denial of service (NULL pointer dereference) via a crafted application. | https://nvd.nist.gov/vuln/detail/CVE-2017-9211 |
2,777 | imageworsener | dc49c807926b96e503bd7c0dec35119eecd6c6fe | https://github.com/jsummers/imageworsener | https://github.com/jsummers/imageworsener/commit/dc49c807926b96e503bd7c0dec35119eecd6c6fe | Double-check that the input image's density is valid
Fixes a bug that could result in division by zero, at least for a JPEG
source image.
Fixes issues #19, #20 | 1 | IW_IMPL(int) iw_get_input_density(struct iw_context *ctx,
double *px, double *py, int *pcode)
{
*px = 1.0;
*py = 1.0;
*pcode = ctx->img1.density_code;
if(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) {
*px = ctx->img1.density_x;
*py = ctx->img1.density_y;
return 1;
}
return 0;
}
| 145,137,936,264,817,800,000,000,000,000,000,000,000 | None | null | [
"CWE-369"
] | CVE-2017-9201 | imagew-cmd.c:850:46 in libimageworsener.a in ImageWorsener 1.3.1 allows remote attackers to cause a denial of service (divide-by-zero error) via a crafted image, related to imagew-api.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-9201 |
2,778 | linux | 0d0e57697f162da4aa218b5feafe614fb666db07 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/0d0e57697f162da4aa218b5feafe614fb666db07 | bpf: don't let ldimm64 leak map addresses on unprivileged
The patch fixes two things at once:
1) It checks the env->allow_ptr_leaks and only prints the map address to
the log if we have the privileges to do so, otherwise it just dumps 0
as we would when kptr_restrict is enabled on %pK. Given the latter is
off by default and not every distro sets it, I don't want to rely on
this, hence the 0 by default for unprivileged.
2) Printing of ldimm64 in the verifier log is currently broken in that
we don't print the full immediate, but only the 32 bit part of the
first insn part for ldimm64. Thus, fix this up as well; it's okay to
access, since we verified all ldimm64 earlier already (including just
constants) through replace_map_fd_with_map_ptr().
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = &env->cur_state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs = state->regs;
int insn_cnt = env->prog->len;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
init_reg_state(regs);
insn_idx = 0;
env->varlen_map_value_access = false;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose("invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose("BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (log_level) {
if (do_print_state)
verbose("\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose("%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (log_level && do_print_state) {
verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
print_verifier_state(&env->cur_state);
do_print_state = false;
}
if (log_level) {
verbose("%d: ", insn_idx);
print_bpf_insn(insn);
}
err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
if (err)
return err;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(regs, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg);
if (err)
return err;
if (BPF_SIZE(insn->code) != BPF_W &&
BPF_SIZE(insn->code) != BPF_DW) {
insn_idx++;
continue;
}
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose("same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(regs, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose("same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose("BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
if (err)
return err;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose("BPF_CALL uses reserved fields\n");
return -EINVAL;
}
err = check_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose("BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose("BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose("R0 leaks addr as return value\n");
return -EACCES;
}
process_bpf_exit:
insn_idx = pop_stack(env, &prev_insn_idx);
if (insn_idx < 0) {
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
} else {
verbose("invalid BPF_LD mode\n");
return -EINVAL;
}
reset_reg_range_values(regs, insn->dst_reg);
} else {
verbose("unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose("processed %d insns\n", insn_processed);
return 0;
}
| 267,242,719,816,233,600,000,000,000,000,000,000,000 | verifier.c | 294,082,422,712,252,900,000,000,000,000,000,000,000 | [
"CWE-200"
] | CVE-2017-9150 | The do_check function in kernel/bpf/verifier.c in the Linux kernel before 4.11.1 does not make the allow_ptr_leaks value available for restricting the output of the print_bpf_insn function, which allows local users to obtain sensitive address information via crafted bpf system calls. | https://nvd.nist.gov/vuln/detail/CVE-2017-9150 |
2,779 | linux | 0d0e57697f162da4aa218b5feafe614fb666db07 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/0d0e57697f162da4aa218b5feafe614fb666db07 | bpf: don't let ldimm64 leak map addresses on unprivileged
The patch fixes two things at once:
1) It checks the env->allow_ptr_leaks and only prints the map address to
the log if we have the privileges to do so, otherwise it just dumps 0
as we would when kptr_restrict is enabled on %pK. Given the latter is
off by default and not every distro sets it, I don't want to rely on
this, hence the 0 by default for unprivileged.
2) Printing of ldimm64 in the verifier log is currently broken in that
we don't print the full immediate, but only the 32 bit part of the
first insn part for ldimm64. Thus, fix this up as well; it's okay to
access, since we verified all ldimm64 earlier already (including just
constants) through replace_map_fd_with_map_ptr().
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static void print_bpf_insn(struct bpf_insn *insn)
{
u8 class = BPF_CLASS(insn->code);
if (class == BPF_ALU || class == BPF_ALU64) {
if (BPF_SRC(insn->code) == BPF_X)
verbose("(%02x) %sr%d %s %sr%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->src_reg);
else
verbose("(%02x) %sr%d %s %s%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->imm);
} else if (class == BPF_STX) {
if (BPF_MODE(insn->code) == BPF_MEM)
verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->src_reg);
else if (BPF_MODE(insn->code) == BPF_XADD)
verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg, insn->off,
insn->src_reg);
else
verbose("BUG_%02x\n", insn->code);
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_st_%02x\n", insn->code);
return;
}
verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->imm);
} else if (class == BPF_LDX) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_ldx_%02x\n", insn->code);
return;
}
verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
insn->code, insn->dst_reg,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->off);
} else if (class == BPF_LD) {
if (BPF_MODE(insn->code) == BPF_ABS) {
verbose("(%02x) r0 = *(%s *)skb[%d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IND) {
verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IMM) {
verbose("(%02x) r%d = 0x%x\n",
insn->code, insn->dst_reg, insn->imm);
} else {
verbose("BUG_ld_%02x\n", insn->code);
return;
}
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
verbose("(%02x) call %s#%d\n", insn->code,
func_id_name(insn->imm), insn->imm);
} else if (insn->code == (BPF_JMP | BPF_JA)) {
verbose("(%02x) goto pc%+d\n",
insn->code, insn->off);
} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
verbose("(%02x) exit\n", insn->code);
} else if (BPF_SRC(insn->code) == BPF_X) {
verbose("(%02x) if r%d %s r%d goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->src_reg, insn->off);
} else {
verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->imm, insn->off);
}
} else {
verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
}
}
| 308,871,137,822,813,300,000,000,000,000,000,000,000 | verifier.c | 294,082,422,712,252,900,000,000,000,000,000,000,000 | [
"CWE-200"
] | CVE-2017-9150 | The do_check function in kernel/bpf/verifier.c in the Linux kernel before 4.11.1 does not make the allow_ptr_leaks value available for restricting the output of the print_bpf_insn function, which allows local users to obtain sensitive address information via crafted bpf system calls. | https://nvd.nist.gov/vuln/detail/CVE-2017-9150 |
2,780 | ImageMagick | 7fdf9ea808caa3c81a0eb42656e5fafc59084198 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/7fdf9ea808caa3c81a0eb42656e5fafc59084198 | None | 1 | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum(
ReadBlobLSBShort(image)));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,pixel_info_length);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 253,340,010,299,841,030,000,000,000,000,000,000,000 | None | null | [
"CWE-20"
] | CVE-2017-9144 | In ImageMagick 7.0.5-5, a crafted RLE image can trigger a crash because of incorrect EOF handling in coders/rle.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-9144 |
2,781 | ImageMagick | 7b8c1df65b25d6671f113e2306982eded44ce3b4 | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/7b8c1df65b25d6671f113e2306982eded44ce3b4 | None | 1 | static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const unsigned char
*pixels;
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01,
GetQuantumPixels(quantum_info),&count);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 223,781,554,613,943,000,000,000,000,000,000,000,000 | None | null | [
"CWE-772"
] | CVE-2017-9143 | In ImageMagick 7.0.5-5, the ReadARTImage function in coders/art.c allows attackers to cause a denial of service (memory leak) via a crafted .art file. | https://nvd.nist.gov/vuln/detail/CVE-2017-9143 |
2,782 | ImageMagick | 72f5c8632bff2daf3c95005f9b4cf2982786b52a | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/72f5c8632bff2daf3c95005f9b4cf2982786b52a | None | 1 | static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
chunk[i]=(unsigned char) ReadBlobByte(image);
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
(void) WriteBlob(color_image,length,chunk);
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
| 237,712,577,469,856,300,000,000,000,000,000,000,000 | None | null | [
"CWE-20"
] | CVE-2017-9142 | In ImageMagick 7.0.5-7 Q16, a crafted file could trigger an assertion failure in the WriteBlob function in MagickCore/blob.c because of missing checks in the ReadOneJNGImage function in coders/png.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-9142 |
2,783 | ImageMagick | f5910e91b0778e03ded45b9022be8eb8f77942cd | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/f5910e91b0778e03ded45b9022be8eb8f77942cd | None | 1 | static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 98,055,214,651,978,080,000,000,000,000,000,000,000 | None | null | [
"CWE-20"
] | CVE-2017-9141 | In ImageMagick 7.0.5-7 Q16, a crafted file could trigger an assertion failure in the ResetImageProfileIterator function in MagickCore/profile.c because of missing checks in the ReadDDSImage function in coders/dds.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-9141 |
2,784 | ImageMagick | 1c358ffe0049f768dd49a8a889c1cbf99ac9849b | https://github.com/ImageMagick/ImageMagick | https://github.com/ImageMagick/ImageMagick/commit/1c358ffe0049f768dd49a8a889c1cbf99ac9849b | Reset memory for RLE decoder (patch provided by scarybeasts) | 1 | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
ValidateColormapValue(image,*p & mask,&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
ValidateColormapValue(image,(size_t) (x*map_length+
(*p & mask)),&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 286,992,895,385,432,100,000,000,000,000,000,000,000 | rle.c | 133,078,342,380,417,530,000,000,000,000,000,000,000 | [
"CWE-200"
] | CVE-2017-9098 | ImageMagick before 7.0.5-2 and GraphicsMagick before 1.3.24 use uninitialized memory in the RLE decoder, allowing an attacker to leak sensitive information from process memory space, as demonstrated by remote attacks against ImageMagick code in a long-running server process that converts image data on behalf of multiple users. This is caused by a missing initialization step in the ReadRLEImage function in coders/rle.c. | https://nvd.nist.gov/vuln/detail/CVE-2017-9098 |
2,785 | linux | 83eaddab4378db256d00d295bda6ca997cd13a52 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/83eaddab4378db256d00d295bda6ca997cd13a52 | ipv6/dccp: do not inherit ipv6_mc_list from parent
Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent")
we should clear ipv6_mc_list etc. for IPv6 sockets too.
Cc: Eric Dumazet <edumazet@google.com>
Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com>
Acked-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
struct flowi6 fl6;
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);
if (!dst)
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
opt = ireq->ipv6_opt;
if (!opt)
opt = rcu_dereference(np->opt);
if (opt) {
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (opt)
inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen +
opt->opt_flen;
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
dccp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
/* Clone pktoptions received with SYN, if we own the req */
if (*own_req && ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
return newsk;
out_overflow:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
}
| 280,222,012,026,830,700,000,000,000,000,000,000,000 | None | null | [
"CWE-241"
] | CVE-2017-9077 | The tcp_v6_syn_recv_sock function in net/ipv6/tcp_ipv6.c in the Linux kernel through 4.11.1 mishandles inheritance, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls, a related issue to CVE-2017-8890. | https://nvd.nist.gov/vuln/detail/CVE-2017-9077 |
2,786 | linux | 83eaddab4378db256d00d295bda6ca997cd13a52 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/83eaddab4378db256d00d295bda6ca997cd13a52 | ipv6/dccp: do not inherit ipv6_mc_list from parent
Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent")
we should clear ipv6_mc_list etc. for IPv6 sockets too.
Cc: Eric Dumazet <edumazet@google.com>
Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com>
Acked-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq;
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
struct tcp6_sock *newtcp6sk;
struct inet_sock *newinet;
struct tcp_sock *newtp;
struct sock *newsk;
#ifdef CONFIG_TCP_MD5SIG
struct tcp_md5sig_key *key;
#endif
struct flowi6 fl6;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (!newsk)
return NULL;
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
newtp = tcp_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &ipv6_mapped;
newsk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
newtp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = tcp_v6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb));
if (np->repflow)
newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb));
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, tcp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
ireq = inet_rsk(req);
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP);
if (!dst)
goto out;
}
newsk = tcp_create_openreq_child(sk, req, skb);
if (!newsk)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, tcp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
newsk->sk_gso_type = SKB_GSO_TCPV6;
ip6_dst_store(newsk, dst, NULL, NULL);
inet6_sk_rx_dst_set(newsk, skb);
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newtp = tcp_sk(newsk);
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = tcp_v6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb));
if (np->repflow)
newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb));
/* Clone native IPv6 options from listening socket (if any)
Yes, keeping reference count would be much more clever,
but we make one more one thing there: reattach optmem
to newsk.
*/
opt = ireq->ipv6_opt;
if (!opt)
opt = rcu_dereference(np->opt);
if (opt) {
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (opt)
inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen +
opt->opt_flen;
tcp_ca_openreq_child(newsk, dst);
tcp_sync_mss(newsk, dst_mtu(dst));
newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst));
tcp_initialize_rcv_mss(newsk);
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
#ifdef CONFIG_TCP_MD5SIG
/* Copy over the MD5 key from the original socket */
key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr);
if (key) {
/* We're using one, so create a matching key
* on the newsk structure. If we fail to get
* memory, then we end up not copying the key
* across. Shucks.
*/
tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr,
AF_INET6, key->key, key->keylen,
sk_gfp_mask(sk, GFP_ATOMIC));
}
#endif
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
tcp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
if (*own_req) {
tcp_move_syn(newtp, req);
/* Clone pktoptions received with SYN, if we own the req */
if (ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts,
sk_gfp_mask(sk, GFP_ATOMIC));
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions) {
tcp_v6_restore_cb(newnp->pktoptions);
skb_set_owner_r(newnp->pktoptions, newsk);
}
}
}
return newsk;
out_overflow:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
tcp_listendrop(sk);
return NULL;
}
| 161,845,565,954,695,880,000,000,000,000,000,000,000 | None | null | [
"CWE-241"
] | CVE-2017-9077 | The tcp_v6_syn_recv_sock function in net/ipv6/tcp_ipv6.c in the Linux kernel through 4.11.1 mishandles inheritance, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls, a related issue to CVE-2017-8890. | https://nvd.nist.gov/vuln/detail/CVE-2017-9077 |
2,787 | linux | fdcee2cbb8438702ea1b328fb6e0ac5e9a40c7f8 | https://github.com/torvalds/linux | https://github.com/torvalds/linux/commit/fdcee2cbb8438702ea1b328fb6e0ac5e9a40c7f8 | sctp: do not inherit ipv6_{mc|ac|fl}_list from parent
SCTP needs fixes similar to 83eaddab4378 ("ipv6/dccp: do not inherit
ipv6_mc_list from parent"), otherwise bad things can happen.
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net> | 1 | static struct sock *sctp_v6_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct sctp6_sock *newsctp6sk;
struct ipv6_txoptions *opt;
newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(sk, SOCK_ZAPPED);
newsctp6sk = (struct sctp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newsctp6sk->inet6;
sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt)
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
rcu_read_unlock();
/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()
* and getpeername().
*/
sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);
newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
sk_refcnt_debug_inc(newsk);
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
| 192,876,189,377,108,080,000,000,000,000,000,000,000 | None | null | [
"CWE-241"
] | CVE-2017-9075 | The sctp_v6_create_accept_sk function in net/sctp/ipv6.c in the Linux kernel through 4.11.1 mishandles inheritance, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls, a related issue to CVE-2017-8890. | https://nvd.nist.gov/vuln/detail/CVE-2017-9075 |