001/*
002 * (C) Copyright 2013-2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Wojciech Sulejman
018 *     Florent Guillaume
019 *     Vladimir Pasquier <vpasquier@nuxeo.com>
020 */
021package org.nuxeo.ecm.platform.signature.core.sign;
022
023import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.SIGNED_CURRENT;
024import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.SIGNED_OTHER;
025import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.UNSIGNABLE;
026import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.UNSIGNED;
027
028import java.io.File;
029import java.io.FileOutputStream;
030import java.io.IOException;
031import java.io.Serializable;
032import java.security.KeyPair;
033import java.security.KeyStore;
034import java.security.cert.Certificate;
035import java.security.cert.X509Certificate;
036import java.util.ArrayList;
037import java.util.Collections;
038import java.util.HashMap;
039import java.util.List;
040import java.util.Map;
041
042import org.apache.commons.io.FilenameUtils;
043import org.apache.commons.lang3.StringUtils;
044import org.apache.commons.logging.Log;
045import org.apache.commons.logging.LogFactory;
046import org.nuxeo.ecm.core.api.Blob;
047import org.nuxeo.ecm.core.api.Blobs;
048import org.nuxeo.ecm.core.api.DocumentModel;
049import org.nuxeo.ecm.core.api.ListDiff;
050import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
051import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;
052import org.nuxeo.ecm.core.api.blobholder.SimpleBlobHolder;
053import org.nuxeo.ecm.core.convert.api.ConversionException;
054import org.nuxeo.ecm.core.convert.api.ConversionService;
055import org.nuxeo.ecm.platform.signature.api.exception.AlreadySignedException;
056import org.nuxeo.ecm.platform.signature.api.exception.CertException;
057import org.nuxeo.ecm.platform.signature.api.exception.SignException;
058import org.nuxeo.ecm.platform.signature.api.pki.CertService;
059import org.nuxeo.ecm.platform.signature.api.sign.SignatureAppearanceFactory;
060import org.nuxeo.ecm.platform.signature.api.sign.SignatureLayout;
061import org.nuxeo.ecm.platform.signature.api.sign.SignatureService;
062import org.nuxeo.ecm.platform.signature.api.user.AliasType;
063import org.nuxeo.ecm.platform.signature.api.user.AliasWrapper;
064import org.nuxeo.ecm.platform.signature.api.user.CUserService;
065import org.nuxeo.runtime.api.Framework;
066import org.nuxeo.runtime.model.ComponentInstance;
067import org.nuxeo.runtime.model.DefaultComponent;
068
069import com.lowagie.text.DocumentException;
070import com.lowagie.text.Rectangle;
071import com.lowagie.text.pdf.AcroFields;
072import com.lowagie.text.pdf.PdfPKCS7;
073import com.lowagie.text.pdf.PdfReader;
074import com.lowagie.text.pdf.PdfSignatureAppearance;
075import com.lowagie.text.pdf.PdfStamper;
076
077/**
078 * Base implementation for the signature service (also a Nuxeo component).
079 * <p>
080 * The main document is signed. If it's not already a PDF, then a PDF conversion is done.
081 * <p>
082 * Once signed, it can replace the main document or be stored as the first attachment. If replacing the main document,
083 * an archive of the original can be kept.
084 * <p>
085 * <ul>
086 * <li>
087 */
088public class SignatureServiceImpl extends DefaultComponent implements SignatureService {
089
090    private static final Log log = LogFactory.getLog(SignatureServiceImpl.class);
091
092    protected static final int SIGNATURE_FIELD_HEIGHT = 50;
093
094    protected static final int SIGNATURE_FIELD_WIDTH = 150;
095
096    protected static final int SIGNATURE_MARGIN = 10;
097
098    protected static final int PAGE_TO_SIGN = 1;
099
100    protected static final String XP_SIGNATURE = "signature";
101
102    protected static final String ALREADY_SIGNED_BY = "This document has already been signed by ";
103
104    protected static final String MIME_TYPE_PDF = "application/pdf";
105
106    /** From JODBasedConverter */
107    protected static final String PDFA1_PARAM = "PDF/A-1";
108
109    protected static final String FILE_CONTENT = "file:content";
110
111    protected static final String FILES_FILES = "files:files";
112
113    protected static final String FILES_FILE = "file";
114
115    protected static final String USER_EMAIL = "user:email";
116
117    protected final Map<String, SignatureDescriptor> signatureRegistryMap;
118
119    public SignatureServiceImpl() {
120        signatureRegistryMap = new HashMap<>();
121    }
122
123    @Override
124    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
125        if (XP_SIGNATURE.equals(extensionPoint)) {
126            SignatureDescriptor signatureDescriptor = (SignatureDescriptor) contribution;
127            if (!signatureDescriptor.getRemoveExtension()) {
128                signatureRegistryMap.put(signatureDescriptor.getId(), signatureDescriptor);
129            } else {
130                signatureRegistryMap.remove(signatureDescriptor.getId());
131            }
132        }
133    }
134
135    @Override
136    public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
137        if (XP_SIGNATURE.equals(extensionPoint)) {
138            SignatureDescriptor signatureDescriptor = (SignatureDescriptor) contribution;
139            if (!signatureDescriptor.getRemoveExtension()) {
140                signatureRegistryMap.remove(signatureDescriptor.getId());
141            }
142        }
143    }
144
145    //
146    // ----- SignatureService -----
147    //
148
149    @Override
150    public StatusWithBlob getSigningStatus(DocumentModel doc, DocumentModel user) {
151        if (doc == null) {
152            return new StatusWithBlob(UNSIGNABLE, null, null, null);
153        }
154        StatusWithBlob blobAndStatus = getSignedPdfBlobAndStatus(doc, user);
155        if (blobAndStatus != null) {
156            return blobAndStatus;
157        }
158        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
159        Blob blob;
160        if (mbh == null || (blob = mbh.getBlob()) == null) {
161            return new StatusWithBlob(UNSIGNABLE, null, null, null);
162        }
163        return new StatusWithBlob(UNSIGNED, blob, mbh, FILE_CONTENT);
164    }
165
166    protected int getSigningStatus(Blob pdfBlob, DocumentModel user) {
167        if (pdfBlob == null) {
168            return UNSIGNED;
169        }
170        List<X509Certificate> certificates = getCertificates(pdfBlob);
171        if (certificates.isEmpty()) {
172            return UNSIGNED;
173        }
174        if (user == null) {
175            return SIGNED_OTHER;
176        }
177        String email = (String) user.getPropertyValue(USER_EMAIL);
178        if (StringUtils.isEmpty(email)) {
179            return SIGNED_OTHER;
180        }
181        CertService certService = Framework.getService(CertService.class);
182        for (X509Certificate certificate : certificates) {
183            String certEmail;
184            try {
185                certEmail = certService.getCertificateEmail(certificate);
186            } catch (CertException e) {
187                continue;
188            }
189            if (email.equals(certEmail)) {
190                return SIGNED_CURRENT;
191            }
192        }
193        return SIGNED_OTHER;
194    }
195
196    /**
197     * Finds the first signed PDF blob.
198     */
199    protected StatusWithBlob getSignedPdfBlobAndStatus(DocumentModel doc, DocumentModel user) {
200        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
201        if (mbh != null) {
202            Blob blob = mbh.getBlob();
203            if (blob != null && MIME_TYPE_PDF.equals(blob.getMimeType())) {
204                int status = getSigningStatus(blob, user);
205                if (status != UNSIGNED) {
206                    // TODO for File document it works, but for general
207                    // blob holders the path may be incorrect
208                    return new StatusWithBlob(status, blob, mbh, FILE_CONTENT);
209                }
210            }
211        }
212        @SuppressWarnings("unchecked")
213        List<Map<String, Serializable>> files = (List<Map<String, Serializable>>) doc.getPropertyValue(FILES_FILES);
214        int i = -1;
215        for (Map<String, Serializable> map : files) {
216            i++;
217            Blob blob = (Blob) map.get(FILES_FILE);
218            if (blob != null && MIME_TYPE_PDF.equals(blob.getMimeType())) {
219                int status = getSigningStatus(blob, user);
220                if (status != UNSIGNED) {
221                    String pathbase = FILES_FILES + "/" + i + "/";
222                    String path = pathbase + FILES_FILE;
223                    BlobHolder bh = new DocumentBlobHolder(doc, path);
224                    return new StatusWithBlob(status, blob, bh, path);
225                }
226            }
227        }
228        return null;
229    }
230
231    @Override
232    public Blob signDocument(DocumentModel doc, DocumentModel user, String keyPassword, String reason, boolean pdfa,
233            SigningDisposition disposition, String archiveFilename) {
234
235        StatusWithBlob blobAndStatus = getSignedPdfBlobAndStatus(doc, user);
236        if (blobAndStatus != null) {
237            // re-sign it
238            Blob signedBlob = signPDF(blobAndStatus.blob, doc, user, keyPassword, reason);
239            signedBlob.setFilename(blobAndStatus.blob.getFilename());
240            // replace the previous blob with a new one
241            blobAndStatus.blobHolder.setBlob(signedBlob);
242            return signedBlob;
243        }
244
245        Blob originalBlob;
246        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
247        if (mbh == null || (originalBlob = mbh.getBlob()) == null) {
248            return null;
249        }
250
251        Blob pdfBlob;
252        if (MIME_TYPE_PDF.equals(originalBlob.getMimeType())) {
253            pdfBlob = originalBlob;
254        } else {
255            // convert to PDF or PDF/A first
256            ConversionService conversionService = Framework.getService(ConversionService.class);
257            Map<String, Serializable> parameters = new HashMap<>();
258            if (pdfa) {
259                parameters.put(PDFA1_PARAM, Boolean.TRUE);
260            }
261            try {
262                BlobHolder holder = conversionService.convert("any2pdf", new SimpleBlobHolder(originalBlob),
263                        parameters);
264                pdfBlob = holder.getBlob();
265            } catch (ConversionException conversionException) {
266                throw new SignException(conversionException);
267            }
268        }
269
270        Blob signedBlob = signPDF(pdfBlob, doc, user, keyPassword, reason);
271        signedBlob.setFilename(FilenameUtils.getBaseName(originalBlob.getFilename()) + ".pdf");
272
273        Map<String, Serializable> map;
274        ListDiff listDiff;
275        switch (disposition) {
276        case REPLACE:
277            // replace main blob
278            mbh.setBlob(signedBlob);
279            break;
280        case ARCHIVE:
281            // archive as attachment
282            originalBlob.setFilename(archiveFilename);
283            map = new HashMap<>();
284            map.put(FILES_FILE, (Serializable) originalBlob);
285            listDiff = new ListDiff();
286            listDiff.add(map);
287            doc.setPropertyValue(FILES_FILES, listDiff);
288            // and replace main blob
289            mbh.setBlob(signedBlob);
290            break;
291        case ATTACH:
292            // set as first attachment
293            map = new HashMap<>();
294            map.put(FILES_FILE, (Serializable) signedBlob);
295            listDiff = new ListDiff();
296            listDiff.insert(0, map);
297            doc.setPropertyValue(FILES_FILES, listDiff);
298            break;
299        }
300
301        return signedBlob;
302    }
303
304    @Override
305    public Blob signPDF(Blob pdfBlob, DocumentModel doc, DocumentModel user, String keyPassword, String reason) {
306        CertService certService = Framework.getService(CertService.class);
307        CUserService cUserService = Framework.getService(CUserService.class);
308        try {
309            File outputFile = Framework.createTempFile("signed-", ".pdf");
310            Blob blob = Blobs.createBlob(outputFile, MIME_TYPE_PDF);
311            Framework.trackFile(outputFile, blob);
312
313            PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
314            List<X509Certificate> pdfCertificates = getCertificates(pdfReader);
315
316            // allows for multiple signatures
317            PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, new FileOutputStream(outputFile), '\0', null,
318                    true);
319
320            String userID = (String) user.getPropertyValue("user:username");
321            AliasWrapper alias = new AliasWrapper(userID);
322            KeyStore keystore = cUserService.getUserKeystore(userID, keyPassword);
323            Certificate certificate = certService.getCertificate(keystore, alias.getId(AliasType.CERT));
324            KeyPair keyPair = certService.getKeyPair(keystore, alias.getId(AliasType.KEY), alias.getId(AliasType.CERT),
325                    keyPassword);
326
327            if (certificatePresentInPDF(certificate, pdfCertificates)) {
328                X509Certificate userX509Certificate = (X509Certificate) certificate;
329                String message = ALREADY_SIGNED_BY + userX509Certificate.getSubjectDN();
330                log.debug(message);
331                throw new AlreadySignedException(message);
332            }
333
334            PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
335            pdfSignatureAppearance.setCrypto(keyPair.getPrivate(), (X509Certificate) certificate, null, PdfSignatureAppearance.SELF_SIGNED);
336            if (StringUtils.isBlank(reason)) {
337                reason = getSigningReason();
338            }
339            pdfSignatureAppearance.setVisibleSignature(getNextCertificatePosition(pdfReader, pdfCertificates), 1, null);
340            getSignatureAppearanceFactory().format(pdfSignatureAppearance, doc, userID, reason);
341
342            pdfStamper.close(); // closes the file
343
344            log.debug("File " + outputFile.getAbsolutePath() + " created and signed with " + reason);
345
346            return blob;
347        } catch (IOException | DocumentException | InstantiationException | IllegalAccessException e) {
348            throw new SignException(e);
349        } catch (IllegalArgumentException e) {
350            if (String.valueOf(e.getMessage()).contains("PdfReader not opened with owner password")) {
351                // iText PDF reading
352                throw new SignException("PDF is password-protected");
353            }
354            throw new SignException(e);
355        }
356    }
357
358    /**
359     * @since 5.8
360     * @return the signature layout. Default one if no contribution.
361     */
362    @Override
363    public SignatureLayout getSignatureLayout() {
364        for (SignatureDescriptor signatureDescriptor : signatureRegistryMap.values()) {
365            SignatureLayout signatureLayout = signatureDescriptor.getSignatureLayout();
366            if (signatureLayout != null) {
367                return signatureLayout;
368            }
369        }
370        return new SignatureDescriptor.SignatureLayout();
371    }
372
373    protected SignatureAppearanceFactory getSignatureAppearanceFactory()
374            throws InstantiationException, IllegalAccessException {
375        if (!signatureRegistryMap.isEmpty()) {
376            SignatureDescriptor signatureDescriptor = signatureRegistryMap.values().iterator().next();
377            return signatureDescriptor.getAppearanceFatory();
378        }
379        return new DefaultSignatureAppearanceFactory();
380    }
381
382    protected String getSigningReason() throws SignException {
383        for (SignatureDescriptor sd : signatureRegistryMap.values()) {
384            String reason = sd.getReason();
385            if (!StringUtils.isBlank(reason)) {
386                return reason;
387            }
388        }
389        throw new SignException("No default signing reason provided in configuration");
390    }
391
392    protected boolean certificatePresentInPDF(Certificate userCert, List<X509Certificate> pdfCertificates)
393            throws SignException {
394        X509Certificate xUserCert = (X509Certificate) userCert;
395        for (X509Certificate xcert : pdfCertificates) {
396            // matching certificate found
397            if (xcert.getSubjectX500Principal().equals(xUserCert.getSubjectX500Principal())) {
398                return true;
399            }
400        }
401        return false;
402    }
403
404    /**
405     * @since 5.8 Provides the position rectangle for the next certificate. An assumption is made that all previous
406     *        certificates in a given PDF were placed using the same technique and settings. New certificates are added
407     *        depending of signature layout contributed.
408     */
409    protected Rectangle getNextCertificatePosition(PdfReader pdfReader, List<X509Certificate> pdfCertificates)
410            throws SignException {
411        int numberOfSignatures = pdfCertificates.size();
412
413        Rectangle pageSize = pdfReader.getPageSize(PAGE_TO_SIGN);
414
415        // PDF size
416        float width = pageSize.getWidth();
417        float height = pageSize.getHeight();
418
419        // Signature size
420        float rectangleWidth = width / getSignatureLayout().getColumns();
421        float rectangeHeight = height / getSignatureLayout().getLines();
422
423        // Signature location
424        int column = numberOfSignatures % getSignatureLayout().getColumns() + getSignatureLayout().getStartColumn();
425        int line = numberOfSignatures / getSignatureLayout().getColumns() + getSignatureLayout().getStartLine();
426        if (column > getSignatureLayout().getColumns()) {
427            column = column % getSignatureLayout().getColumns();
428            line++;
429        }
430
431        // Skip rectangle display If number of signatures exceed free locations
432        // on pdf layout
433        if (line > getSignatureLayout().getLines()) {
434            return new Rectangle(0, 0, 0, 0);
435        }
436
437        // make smaller by page margin
438        float topRightX = rectangleWidth * column;
439        float bottomLeftY = height - rectangeHeight * line;
440        float bottomLeftX = topRightX - SIGNATURE_FIELD_WIDTH;
441        float topRightY = bottomLeftY + SIGNATURE_FIELD_HEIGHT;
442
443        // verify current position coordinates in case they were
444        // misconfigured
445        validatePageBounds(pdfReader, 1, bottomLeftX, true);
446        validatePageBounds(pdfReader, 1, bottomLeftY, false);
447        validatePageBounds(pdfReader, 1, topRightX, true);
448        validatePageBounds(pdfReader, 1, topRightY, false);
449
450        Rectangle positionRectangle = new Rectangle(bottomLeftX, bottomLeftY, topRightX, topRightY);
451
452        return positionRectangle;
453    }
454
455    /**
456     * Verifies that a provided value fits within the page bounds. If it does not, a sign exception is thrown. This is
457     * to verify externally configurable signature positioning.
458     *
459     * @param isHorizontal - if false, the current value is checked agains the vertical page dimension
460     */
461    protected void validatePageBounds(PdfReader pdfReader, int pageNo, float valueToCheck, boolean isHorizontal)
462            throws SignException {
463        if (valueToCheck < 0) {
464            String message = "The new signature position " + valueToCheck
465                    + " exceeds the page bounds. The position must be a positive number.";
466            log.debug(message);
467            throw new SignException(message);
468        }
469
470        Rectangle pageRectangle = pdfReader.getPageSize(pageNo);
471        if (isHorizontal && valueToCheck > pageRectangle.getRight()) {
472            String message = "The new signature position " + valueToCheck
473                    + " exceeds the horizontal page bounds. The page dimensions are: (" + pageRectangle + ").";
474            log.debug(message);
475            throw new SignException(message);
476        }
477        if (!isHorizontal && valueToCheck > pageRectangle.getTop()) {
478            String message = "The new signature position " + valueToCheck
479                    + " exceeds the vertical page bounds. The page dimensions are: (" + pageRectangle + ").";
480            log.debug(message);
481            throw new SignException(message);
482        }
483    }
484
485    @Override
486    public List<X509Certificate> getCertificates(DocumentModel doc) {
487        StatusWithBlob signedBlob = getSignedPdfBlobAndStatus(doc, null);
488        if (signedBlob == null) {
489            return Collections.emptyList();
490        }
491        return getCertificates(signedBlob.blob);
492    }
493
494    protected List<X509Certificate> getCertificates(Blob pdfBlob) throws SignException {
495        try {
496            PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
497            return getCertificates(pdfReader);
498        } catch (IOException e) {
499            String message = "";
500            if (e.getMessage().equals("PDF header signature not found.")) {
501                message = "PDF seems to be corrupted";
502            }
503            throw new SignException(message, e);
504        }
505    }
506
507    protected List<X509Certificate> getCertificates(PdfReader pdfReader) throws SignException {
508        List<X509Certificate> pdfCertificates = new ArrayList<>();
509        AcroFields acroFields = pdfReader.getAcroFields();
510        @SuppressWarnings("unchecked")
511        List<String> signatureNames = acroFields.getSignatureNames();
512        for (String signatureName : signatureNames) {
513            PdfPKCS7 pdfPKCS7 = acroFields.verifySignature(signatureName);
514            X509Certificate signingCertificate = pdfPKCS7.getSigningCertificate();
515            pdfCertificates.add(signingCertificate);
516        }
517        return pdfCertificates;
518    }
519
520}