]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/validators/videos/video-imports.ts
Prevent video import on non unicast ips
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-imports.ts
index 5dc5db5338fd8250e6bcceb79d022ac9eb85a5ba..e4b54283f6349f46d7156cc17f74947f2a23afc1 100644 (file)
@@ -1,15 +1,19 @@
-import * as express from 'express'
+import express from 'express'
 import { body } from 'express-validator'
+import { isPreImportVideoAccepted } from '@server/lib/moderation'
+import { Hooks } from '@server/lib/plugins/hooks'
+import { HttpStatusCode } from '@shared/models'
+import { VideoImportCreate } from '@shared/models/videos/import/video-import-create.model'
 import { isIdValid, toIntOrNull } from '../../../helpers/custom-validators/misc'
-import { logger } from '../../../helpers/logger'
-import { areValidationErrors } from '../utils'
-import { getCommonVideoEditAttributes } from './videos'
 import { isVideoImportTargetUrlValid, isVideoImportTorrentFile } from '../../../helpers/custom-validators/video-imports'
-import { cleanUpReqFiles } from '../../../helpers/express-utils'
 import { isVideoMagnetUriValid, isVideoNameValid } from '../../../helpers/custom-validators/videos'
+import { cleanUpReqFiles } from '../../../helpers/express-utils'
+import { logger } from '../../../helpers/logger'
 import { CONFIG } from '../../../initializers/config'
 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
-import { doesVideoChannelOfAccountExist } from '../../../helpers/middlewares'
+import { areValidationErrors, doesVideoChannelOfAccountExist } from '../shared'
+import { getCommonVideoEditAttributes } from './videos'
+import { isValid as isIPValid, parse as parseIP } from 'ipaddr.js'
 
 const videoImportAddValidator = getCommonVideoEditAttributes().concat([
   body('channelId')
@@ -29,28 +33,34 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([
     ),
   body('name')
     .optional()
-    .custom(isVideoNameValid).withMessage('Should have a valid name'),
+    .custom(isVideoNameValid).withMessage(
+      `Should have a video name between ${CONSTRAINTS_FIELDS.VIDEOS.NAME.min} and ${CONSTRAINTS_FIELDS.VIDEOS.NAME.max} characters long`
+    ),
 
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
     logger.debug('Checking videoImportAddValidator parameters', { parameters: req.body })
 
     const user = res.locals.oauth.token.User
-    const torrentFile = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
+    const torrentFile = req.files?.['torrentfile'] ? req.files['torrentfile'][0] : undefined
 
     if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
 
-    if (req.body.targetUrl && CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true) {
+    if (CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true && req.body.targetUrl) {
       cleanUpReqFiles(req)
-      return res.status(409)
-        .json({ error: 'HTTP import is not enabled on this instance.' })
-        .end()
+
+      return res.fail({
+        status: HttpStatusCode.CONFLICT_409,
+        message: 'HTTP import is not enabled on this instance.'
+      })
     }
 
     if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) {
       cleanUpReqFiles(req)
-      return res.status(409)
-                .json({ error: 'Torrent/magnet URI import is not enabled on this instance.' })
-                .end()
+
+      return res.fail({
+        status: HttpStatusCode.CONFLICT_409,
+        message: 'Torrent/magnet URI import is not enabled on this instance.'
+      })
     }
 
     if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
@@ -59,11 +69,28 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([
     if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) {
       cleanUpReqFiles(req)
 
-      return res.status(400)
-        .json({ error: 'Should have a magnetUri or a targetUrl or a torrent file.' })
-        .end()
+      return res.fail({ message: 'Should have a magnetUri or a targetUrl or a torrent file.' })
     }
 
+    if (req.body.targetUrl) {
+      const hostname = new URL(req.body.targetUrl).hostname
+
+      if (isIPValid(hostname)) {
+        const parsed = parseIP(hostname)
+
+        if (parsed.range() !== 'unicast') {
+          cleanUpReqFiles(req)
+
+          return res.fail({
+            status: HttpStatusCode.FORBIDDEN_403,
+            message: 'Cannot use non unicast IP as targetUrl.'
+          })
+        }
+      }
+    }
+
+    if (!await isImportAccepted(req, res)) return cleanUpReqFiles(req)
+
     return next()
   }
 ])
@@ -75,3 +102,33 @@ export {
 }
 
 // ---------------------------------------------------------------------------
+
+async function isImportAccepted (req: express.Request, res: express.Response) {
+  const body: VideoImportCreate = req.body
+  const hookName = body.targetUrl
+    ? 'filter:api.video.pre-import-url.accept.result'
+    : 'filter:api.video.pre-import-torrent.accept.result'
+
+  // Check we accept this video
+  const acceptParameters = {
+    videoImportBody: body,
+    user: res.locals.oauth.token.User
+  }
+  const acceptedResult = await Hooks.wrapFun(
+    isPreImportVideoAccepted,
+    acceptParameters,
+    hookName
+  )
+
+  if (!acceptedResult || acceptedResult.accepted !== true) {
+    logger.info('Refused to import video.', { acceptedResult, acceptParameters })
+
+    res.fail({
+      status: HttpStatusCode.FORBIDDEN_403,
+      message: acceptedResult.errorMessage || 'Refused to import video'
+    })
+    return false
+  }
+
+  return true
+}